Repository: google/CodeCity Branch: master Commit: fa1bd2734b80 Files: 780 Total size: 7.8 MB Directory structure: gitextract_2201ao9s/ ├── .clang-format ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── bin/ │ ├── dump-core │ ├── nginx-dev │ └── startup.command ├── connect/ │ ├── connect.html │ ├── connectServer │ ├── log.html │ └── world.html ├── core/ │ ├── README │ ├── core_10_base.js │ ├── core_11_$.utils.js │ ├── core_12_$.utils.code.js │ ├── core_13_$.Selector.js │ ├── core_20_$.utils.html.js │ ├── core_21_$.jssp.js │ ├── core_22_$.connection.js │ ├── core_23_$.servers.http.js │ ├── core_24_$.hosts.js │ ├── core_25_$.db.tempId.js │ ├── core_25_$.userDatabase.js │ ├── core_26_inline_editor.js │ ├── core_27_editor.js │ ├── core_28_$.servers.eval.js │ ├── core_30_$.utils.command.js │ ├── core_31_$.utils_world.js │ ├── core_32_physical.js │ ├── core_33_world.js │ ├── core_34_$.servers.login.js │ ├── core_34_$.servers.telnet.js │ ├── core_40_$.startRoom.js │ ├── core_41_deutsche_zimmer.js │ ├── core_42_plant.js │ ├── core_43_genetics_lab.js │ ├── core_44_$.assistant.js │ ├── core_45_Challenge_Room.js │ ├── core_46_$.secuityCourse.js │ ├── core_99_startup.js │ └── dump_spec.json ├── database/ │ ├── README │ └── codecity.cfg ├── docs/ │ └── setup.md ├── etc/ │ ├── apache.conf │ ├── cc-localhost.conf │ ├── cc-onedomain.conf │ ├── cc-subdomain.conf │ ├── codecity-connect.service │ ├── codecity-login.service │ ├── codecity-mobwrite.service │ ├── codecity.service │ └── gcloud-snapshot ├── login/ │ ├── login.html │ ├── loginServer │ └── package.json ├── minimal/ │ ├── core_01_minimal.js │ ├── minimal.cfg │ └── readme.txt ├── mobwrite/ │ ├── mobwrite.cfg │ ├── mobwrite_core.py │ ├── mobwrite_core_test.py │ └── mobwrite_server.py ├── server/ │ ├── code.js │ ├── codecity │ ├── compile │ ├── config.txt │ ├── dump │ ├── dumper.js │ ├── externs/ │ │ ├── WeakRef.js │ │ ├── buffer/ │ │ │ ├── buffer.js │ │ │ └── package.json │ │ ├── crypto/ │ │ │ ├── crypto.js │ │ │ └── package.json │ │ ├── events/ │ │ │ ├── events.js │ │ │ └── package.json │ │ ├── fs/ │ │ │ ├── fs.js │ │ │ └── package.json │ │ ├── http/ │ │ │ ├── http.js │ │ │ └── package.json │ │ ├── https/ │ │ │ ├── https.js │ │ │ └── package.json │ │ ├── net/ │ │ │ ├── net.js │ │ │ └── package.json │ │ ├── node.js │ │ ├── path/ │ │ │ ├── package.json │ │ │ └── path.js │ │ ├── stream/ │ │ │ ├── package.json │ │ │ └── stream.js │ │ ├── tls/ │ │ │ ├── package.json │ │ │ └── tls.js │ │ └── util/ │ │ ├── package.json │ │ └── util.js │ ├── interpreter.js │ ├── iterable_weakmap.js │ ├── iterable_weakset.js │ ├── package.json │ ├── parser.js │ ├── priorityqueue.js │ ├── registry.js │ ├── repl │ ├── selector.js │ ├── serialize.js │ ├── startup/ │ │ ├── cc.js │ │ ├── es5.js │ │ ├── es6.js │ │ ├── es7.js │ │ ├── es8.js │ │ └── esx.js │ └── tests/ │ ├── code_test.js │ ├── db/ │ │ ├── core_01_$.js │ │ ├── core_01_$.system.js │ │ ├── test.cfg │ │ ├── test_00_start.js │ │ ├── test_01_es5.js │ │ ├── test_01_es6.js │ │ ├── test_01_es7.js │ │ ├── test_02_errors.js │ │ ├── test_02_perms.js │ │ ├── test_09_end.js │ │ ├── test_10_fibonacci.js │ │ └── test_20_reboot.js │ ├── dump_test.js │ ├── dumper_test.js │ ├── interpreter_bench.js │ ├── interpreter_common.js │ ├── interpreter_test.js │ ├── interpreter_unit_test.js │ ├── iterable_weakmap_test.js │ ├── iterable_weakset_test.js │ ├── priorityqueue_test.js │ ├── registry_test.js │ ├── run │ ├── run.js │ ├── selector_test.js │ ├── serialize_bench.js │ ├── serialize_test.js │ ├── testcases.js │ ├── testing.js │ └── tinycore/ │ ├── README │ ├── core_00_es_minimal.js │ ├── core_10_base.js │ ├── core_13_$.utils.code.js │ ├── core_35_$.servers.eval.js │ ├── dump_spec.json │ └── tiny.cfg ├── static/ │ ├── 503.html │ ├── code/ │ │ ├── code.js │ │ ├── common.js │ │ ├── diff.css │ │ ├── diff.js │ │ ├── editor.css │ │ ├── editor.js │ │ ├── explorer.js │ │ ├── mobwrite/ │ │ │ ├── demo/ │ │ │ │ ├── editor.html │ │ │ │ ├── form.html │ │ │ │ ├── mobwrite_form.js │ │ │ │ └── test.html │ │ │ ├── mobwrite_cc.js │ │ │ └── mobwrite_core.js │ │ ├── objectPanel.js │ │ ├── style.css │ │ ├── svg.css │ │ ├── svg.js │ │ └── tests/ │ │ ├── test.html │ │ └── test.js │ ├── connect/ │ │ ├── common.css │ │ ├── common.js │ │ ├── connect.css │ │ ├── connect.js │ │ ├── log.css │ │ ├── log.js │ │ ├── prettify.css │ │ ├── prettify.js │ │ ├── tests/ │ │ │ ├── test.html │ │ │ └── test.js │ │ ├── world.css │ │ └── world.js │ ├── flamethrower.html │ ├── login-close.html │ ├── securitystore/ │ │ ├── style.css │ │ └── utils.js │ └── style/ │ ├── jfk.css │ └── svg.css └── third_party/ ├── CodeMirror/ │ ├── AUTHORS │ ├── CHANGELOG.md │ ├── CONTRIBUTING.md │ ├── LICENSE │ ├── METADATA │ ├── README.md │ ├── addon/ │ │ ├── comment/ │ │ │ ├── comment.js │ │ │ └── continuecomment.js │ │ ├── dialog/ │ │ │ ├── dialog.css │ │ │ └── dialog.js │ │ ├── display/ │ │ │ ├── autorefresh.js │ │ │ ├── fullscreen.css │ │ │ ├── fullscreen.js │ │ │ ├── panel.js │ │ │ ├── placeholder.js │ │ │ └── rulers.js │ │ ├── edit/ │ │ │ ├── closebrackets.js │ │ │ ├── closetag.js │ │ │ ├── continuelist.js │ │ │ ├── matchbrackets.js │ │ │ ├── matchtags.js │ │ │ └── trailingspace.js │ │ ├── fold/ │ │ │ ├── brace-fold.js │ │ │ ├── comment-fold.js │ │ │ ├── foldcode.js │ │ │ ├── foldgutter.css │ │ │ ├── foldgutter.js │ │ │ ├── indent-fold.js │ │ │ ├── markdown-fold.js │ │ │ └── xml-fold.js │ │ ├── hint/ │ │ │ ├── anyword-hint.js │ │ │ ├── css-hint.js │ │ │ ├── html-hint.js │ │ │ ├── javascript-hint.js │ │ │ ├── show-hint.css │ │ │ ├── show-hint.js │ │ │ ├── sql-hint.js │ │ │ └── xml-hint.js │ │ ├── lint/ │ │ │ ├── coffeescript-lint.js │ │ │ ├── css-lint.js │ │ │ ├── html-lint.js │ │ │ ├── javascript-lint.js │ │ │ ├── json-lint.js │ │ │ ├── lint.css │ │ │ ├── lint.js │ │ │ └── yaml-lint.js │ │ ├── merge/ │ │ │ ├── merge.css │ │ │ └── merge.js │ │ ├── mode/ │ │ │ ├── loadmode.js │ │ │ ├── multiplex.js │ │ │ ├── multiplex_test.js │ │ │ ├── overlay.js │ │ │ └── simple.js │ │ ├── runmode/ │ │ │ ├── colorize.js │ │ │ ├── runmode-standalone.js │ │ │ ├── runmode.js │ │ │ └── runmode.node.js │ │ ├── scroll/ │ │ │ ├── annotatescrollbar.js │ │ │ ├── scrollpastend.js │ │ │ ├── simplescrollbars.css │ │ │ └── simplescrollbars.js │ │ ├── search/ │ │ │ ├── jump-to-line.js │ │ │ ├── match-highlighter.js │ │ │ ├── matchesonscrollbar.css │ │ │ ├── matchesonscrollbar.js │ │ │ ├── search.js │ │ │ └── searchcursor.js │ │ ├── selection/ │ │ │ ├── active-line.js │ │ │ ├── mark-selection.js │ │ │ └── selection-pointer.js │ │ ├── tern/ │ │ │ ├── tern.css │ │ │ ├── tern.js │ │ │ └── worker.js │ │ └── wrap/ │ │ └── hardwrap.js │ ├── bin/ │ │ ├── authors.sh │ │ ├── lint │ │ ├── release │ │ ├── source-highlight │ │ └── upload-release.js │ ├── demo/ │ │ ├── activeline.html │ │ ├── anywordhint.html │ │ ├── bidi.html │ │ ├── btree.html │ │ ├── buffers.html │ │ ├── changemode.html │ │ ├── closebrackets.html │ │ ├── closetag.html │ │ ├── complete.html │ │ ├── emacs.html │ │ ├── folding.html │ │ ├── fullscreen.html │ │ ├── hardwrap.html │ │ ├── html5complete.html │ │ ├── indentwrap.html │ │ ├── lint.html │ │ ├── loadmode.html │ │ ├── marker.html │ │ ├── markselection.html │ │ ├── matchhighlighter.html │ │ ├── matchtags.html │ │ ├── merge.html │ │ ├── multiplex.html │ │ ├── mustache.html │ │ ├── panel.html │ │ ├── placeholder.html │ │ ├── preview.html │ │ ├── requirejs.html │ │ ├── resize.html │ │ ├── rulers.html │ │ ├── runmode.html │ │ ├── search.html │ │ ├── simplemode.html │ │ ├── simplescrollbars.html │ │ ├── spanaffectswrapping_shim.html │ │ ├── sublime.html │ │ ├── tern.html │ │ ├── theme.html │ │ ├── trailingspace.html │ │ ├── variableheight.html │ │ ├── vim.html │ │ ├── visibletabs.html │ │ ├── widget.html │ │ └── xmlcomplete.html │ ├── doc/ │ │ ├── activebookmark.js │ │ ├── docs.css │ │ ├── internals.html │ │ ├── manual.html │ │ ├── realworld.html │ │ ├── releases.html │ │ ├── reporting.html │ │ ├── upgrade_v2.2.html │ │ ├── upgrade_v3.html │ │ └── upgrade_v4.html │ ├── index.html │ ├── keymap/ │ │ ├── emacs.js │ │ ├── sublime.js │ │ └── vim.js │ ├── lib/ │ │ ├── codemirror.css │ │ └── codemirror.js │ ├── mode/ │ │ ├── apl/ │ │ │ ├── apl.js │ │ │ └── index.html │ │ ├── asciiarmor/ │ │ │ ├── asciiarmor.js │ │ │ └── index.html │ │ ├── asn.1/ │ │ │ ├── asn.1.js │ │ │ └── index.html │ │ ├── asterisk/ │ │ │ ├── asterisk.js │ │ │ └── index.html │ │ ├── brainfuck/ │ │ │ ├── brainfuck.js │ │ │ └── index.html │ │ ├── clike/ │ │ │ ├── clike.js │ │ │ ├── index.html │ │ │ ├── scala.html │ │ │ └── test.js │ │ ├── clojure/ │ │ │ ├── clojure.js │ │ │ ├── index.html │ │ │ └── test.js │ │ ├── cmake/ │ │ │ ├── cmake.js │ │ │ └── index.html │ │ ├── cobol/ │ │ │ ├── cobol.js │ │ │ └── index.html │ │ ├── coffeescript/ │ │ │ ├── coffeescript.js │ │ │ └── index.html │ │ ├── commonlisp/ │ │ │ ├── commonlisp.js │ │ │ └── index.html │ │ ├── crystal/ │ │ │ ├── crystal.js │ │ │ └── index.html │ │ ├── css/ │ │ │ ├── css.js │ │ │ ├── gss.html │ │ │ ├── gss_test.js │ │ │ ├── index.html │ │ │ ├── less.html │ │ │ ├── less_test.js │ │ │ ├── scss.html │ │ │ ├── scss_test.js │ │ │ └── test.js │ │ ├── cypher/ │ │ │ ├── cypher.js │ │ │ ├── index.html │ │ │ └── test.js │ │ ├── d/ │ │ │ ├── d.js │ │ │ ├── index.html │ │ │ └── test.js │ │ ├── dart/ │ │ │ ├── dart.js │ │ │ └── index.html │ │ ├── diff/ │ │ │ ├── diff.js │ │ │ └── index.html │ │ ├── django/ │ │ │ ├── django.js │ │ │ └── index.html │ │ ├── dockerfile/ │ │ │ ├── dockerfile.js │ │ │ ├── index.html │ │ │ └── test.js │ │ ├── dtd/ │ │ │ ├── dtd.js │ │ │ └── index.html │ │ ├── dylan/ │ │ │ ├── dylan.js │ │ │ ├── index.html │ │ │ └── test.js │ │ ├── ebnf/ │ │ │ ├── ebnf.js │ │ │ └── index.html │ │ ├── ecl/ │ │ │ ├── ecl.js │ │ │ └── index.html │ │ ├── eiffel/ │ │ │ ├── eiffel.js │ │ │ └── index.html │ │ ├── elm/ │ │ │ ├── elm.js │ │ │ └── index.html │ │ ├── erlang/ │ │ │ ├── erlang.js │ │ │ └── index.html │ │ ├── factor/ │ │ │ ├── factor.js │ │ │ └── index.html │ │ ├── fcl/ │ │ │ ├── fcl.js │ │ │ └── index.html │ │ ├── forth/ │ │ │ ├── forth.js │ │ │ └── index.html │ │ ├── fortran/ │ │ │ ├── fortran.js │ │ │ └── index.html │ │ ├── gas/ │ │ │ ├── gas.js │ │ │ └── index.html │ │ ├── gfm/ │ │ │ ├── gfm.js │ │ │ ├── index.html │ │ │ └── test.js │ │ ├── gherkin/ │ │ │ ├── gherkin.js │ │ │ └── index.html │ │ ├── go/ │ │ │ ├── go.js │ │ │ └── index.html │ │ ├── groovy/ │ │ │ ├── groovy.js │ │ │ └── index.html │ │ ├── haml/ │ │ │ ├── haml.js │ │ │ ├── index.html │ │ │ └── test.js │ │ ├── handlebars/ │ │ │ ├── handlebars.js │ │ │ └── index.html │ │ ├── haskell/ │ │ │ ├── haskell.js │ │ │ └── index.html │ │ ├── haskell-literate/ │ │ │ ├── haskell-literate.js │ │ │ └── index.html │ │ ├── haxe/ │ │ │ ├── haxe.js │ │ │ └── index.html │ │ ├── htmlembedded/ │ │ │ ├── htmlembedded.js │ │ │ └── index.html │ │ ├── htmlmixed/ │ │ │ ├── htmlmixed.js │ │ │ └── index.html │ │ ├── http/ │ │ │ ├── http.js │ │ │ └── index.html │ │ ├── idl/ │ │ │ ├── idl.js │ │ │ └── index.html │ │ ├── index.html │ │ ├── javascript/ │ │ │ ├── index.html │ │ │ ├── javascript.js │ │ │ ├── json-ld.html │ │ │ ├── test.js │ │ │ └── typescript.html │ │ ├── jinja2/ │ │ │ ├── index.html │ │ │ └── jinja2.js │ │ ├── jsx/ │ │ │ ├── index.html │ │ │ ├── jsx.js │ │ │ └── test.js │ │ ├── julia/ │ │ │ ├── index.html │ │ │ └── julia.js │ │ ├── livescript/ │ │ │ ├── index.html │ │ │ └── livescript.js │ │ ├── lua/ │ │ │ ├── index.html │ │ │ └── lua.js │ │ ├── markdown/ │ │ │ ├── index.html │ │ │ ├── markdown.js │ │ │ └── test.js │ │ ├── mathematica/ │ │ │ ├── index.html │ │ │ └── mathematica.js │ │ ├── mbox/ │ │ │ ├── index.html │ │ │ └── mbox.js │ │ ├── meta.js │ │ ├── mirc/ │ │ │ ├── index.html │ │ │ └── mirc.js │ │ ├── mllike/ │ │ │ ├── index.html │ │ │ └── mllike.js │ │ ├── modelica/ │ │ │ ├── index.html │ │ │ └── modelica.js │ │ ├── mscgen/ │ │ │ ├── index.html │ │ │ ├── mscgen.js │ │ │ ├── mscgen_test.js │ │ │ ├── msgenny_test.js │ │ │ └── xu_test.js │ │ ├── mumps/ │ │ │ ├── index.html │ │ │ └── mumps.js │ │ ├── nginx/ │ │ │ ├── index.html │ │ │ └── nginx.js │ │ ├── nsis/ │ │ │ ├── index.html │ │ │ └── nsis.js │ │ ├── ntriples/ │ │ │ ├── index.html │ │ │ └── ntriples.js │ │ ├── octave/ │ │ │ ├── index.html │ │ │ └── octave.js │ │ ├── oz/ │ │ │ ├── index.html │ │ │ └── oz.js │ │ ├── pascal/ │ │ │ ├── index.html │ │ │ └── pascal.js │ │ ├── pegjs/ │ │ │ ├── index.html │ │ │ └── pegjs.js │ │ ├── perl/ │ │ │ ├── index.html │ │ │ └── perl.js │ │ ├── php/ │ │ │ ├── index.html │ │ │ ├── php.js │ │ │ └── test.js │ │ ├── pig/ │ │ │ ├── index.html │ │ │ └── pig.js │ │ ├── powershell/ │ │ │ ├── index.html │ │ │ ├── powershell.js │ │ │ └── test.js │ │ ├── properties/ │ │ │ ├── index.html │ │ │ └── properties.js │ │ ├── protobuf/ │ │ │ ├── index.html │ │ │ └── protobuf.js │ │ ├── pug/ │ │ │ ├── index.html │ │ │ └── pug.js │ │ ├── puppet/ │ │ │ ├── index.html │ │ │ └── puppet.js │ │ ├── python/ │ │ │ ├── index.html │ │ │ ├── python.js │ │ │ └── test.js │ │ ├── q/ │ │ │ ├── index.html │ │ │ └── q.js │ │ ├── r/ │ │ │ ├── index.html │ │ │ └── r.js │ │ ├── rpm/ │ │ │ ├── changes/ │ │ │ │ └── index.html │ │ │ ├── index.html │ │ │ └── rpm.js │ │ ├── rst/ │ │ │ ├── index.html │ │ │ └── rst.js │ │ ├── ruby/ │ │ │ ├── index.html │ │ │ ├── ruby.js │ │ │ └── test.js │ │ ├── rust/ │ │ │ ├── index.html │ │ │ ├── rust.js │ │ │ └── test.js │ │ ├── sas/ │ │ │ ├── index.html │ │ │ └── sas.js │ │ ├── sass/ │ │ │ ├── index.html │ │ │ ├── sass.js │ │ │ └── test.js │ │ ├── scheme/ │ │ │ ├── index.html │ │ │ └── scheme.js │ │ ├── shell/ │ │ │ ├── index.html │ │ │ ├── shell.js │ │ │ └── test.js │ │ ├── sieve/ │ │ │ ├── index.html │ │ │ └── sieve.js │ │ ├── slim/ │ │ │ ├── index.html │ │ │ ├── slim.js │ │ │ └── test.js │ │ ├── smalltalk/ │ │ │ ├── index.html │ │ │ └── smalltalk.js │ │ ├── smarty/ │ │ │ ├── index.html │ │ │ └── smarty.js │ │ ├── solr/ │ │ │ ├── index.html │ │ │ └── solr.js │ │ ├── soy/ │ │ │ ├── index.html │ │ │ ├── soy.js │ │ │ └── test.js │ │ ├── sparql/ │ │ │ ├── index.html │ │ │ └── sparql.js │ │ ├── spreadsheet/ │ │ │ ├── index.html │ │ │ └── spreadsheet.js │ │ ├── sql/ │ │ │ ├── index.html │ │ │ └── sql.js │ │ ├── stex/ │ │ │ ├── index.html │ │ │ ├── stex.js │ │ │ └── test.js │ │ ├── stylus/ │ │ │ ├── index.html │ │ │ └── stylus.js │ │ ├── swift/ │ │ │ ├── index.html │ │ │ ├── swift.js │ │ │ └── test.js │ │ ├── tcl/ │ │ │ ├── index.html │ │ │ └── tcl.js │ │ ├── textile/ │ │ │ ├── index.html │ │ │ ├── test.js │ │ │ └── textile.js │ │ ├── tiddlywiki/ │ │ │ ├── index.html │ │ │ ├── tiddlywiki.css │ │ │ └── tiddlywiki.js │ │ ├── tiki/ │ │ │ ├── index.html │ │ │ ├── tiki.css │ │ │ └── tiki.js │ │ ├── toml/ │ │ │ ├── index.html │ │ │ └── toml.js │ │ ├── tornado/ │ │ │ ├── index.html │ │ │ └── tornado.js │ │ ├── troff/ │ │ │ ├── index.html │ │ │ └── troff.js │ │ ├── ttcn/ │ │ │ ├── index.html │ │ │ └── ttcn.js │ │ ├── ttcn-cfg/ │ │ │ ├── index.html │ │ │ └── ttcn-cfg.js │ │ ├── turtle/ │ │ │ ├── index.html │ │ │ └── turtle.js │ │ ├── twig/ │ │ │ ├── index.html │ │ │ └── twig.js │ │ ├── vb/ │ │ │ ├── index.html │ │ │ └── vb.js │ │ ├── vbscript/ │ │ │ ├── index.html │ │ │ └── vbscript.js │ │ ├── velocity/ │ │ │ ├── index.html │ │ │ └── velocity.js │ │ ├── verilog/ │ │ │ ├── index.html │ │ │ ├── test.js │ │ │ └── verilog.js │ │ ├── vhdl/ │ │ │ ├── index.html │ │ │ └── vhdl.js │ │ ├── vue/ │ │ │ ├── index.html │ │ │ └── vue.js │ │ ├── webidl/ │ │ │ ├── index.html │ │ │ └── webidl.js │ │ ├── xml/ │ │ │ ├── index.html │ │ │ ├── test.js │ │ │ └── xml.js │ │ ├── xquery/ │ │ │ ├── index.html │ │ │ ├── test.js │ │ │ └── xquery.js │ │ ├── yacas/ │ │ │ ├── index.html │ │ │ └── yacas.js │ │ ├── yaml/ │ │ │ ├── index.html │ │ │ └── yaml.js │ │ ├── yaml-frontmatter/ │ │ │ ├── index.html │ │ │ └── yaml-frontmatter.js │ │ └── z80/ │ │ ├── index.html │ │ └── z80.js │ ├── package.json │ ├── rollup.config.js │ ├── src/ │ │ ├── codemirror.js │ │ ├── display/ │ │ │ ├── Display.js │ │ │ ├── focus.js │ │ │ ├── gutters.js │ │ │ ├── highlight_worker.js │ │ │ ├── line_numbers.js │ │ │ ├── mode_state.js │ │ │ ├── operations.js │ │ │ ├── scroll_events.js │ │ │ ├── scrollbars.js │ │ │ ├── scrolling.js │ │ │ ├── selection.js │ │ │ ├── update_display.js │ │ │ ├── update_line.js │ │ │ ├── update_lines.js │ │ │ └── view_tracking.js │ │ ├── edit/ │ │ │ ├── CodeMirror.js │ │ │ ├── commands.js │ │ │ ├── deleteNearSelection.js │ │ │ ├── drop_events.js │ │ │ ├── fromTextArea.js │ │ │ ├── global_events.js │ │ │ ├── key_events.js │ │ │ ├── legacy.js │ │ │ ├── main.js │ │ │ ├── methods.js │ │ │ ├── mouse_events.js │ │ │ ├── options.js │ │ │ └── utils.js │ │ ├── input/ │ │ │ ├── ContentEditableInput.js │ │ │ ├── TextareaInput.js │ │ │ ├── indent.js │ │ │ ├── input.js │ │ │ ├── keymap.js │ │ │ ├── keynames.js │ │ │ └── movement.js │ │ ├── line/ │ │ │ ├── highlight.js │ │ │ ├── line_data.js │ │ │ ├── pos.js │ │ │ ├── saw_special_spans.js │ │ │ ├── spans.js │ │ │ └── utils_line.js │ │ ├── measurement/ │ │ │ ├── position_measurement.js │ │ │ └── widgets.js │ │ ├── model/ │ │ │ ├── Doc.js │ │ │ ├── change_measurement.js │ │ │ ├── changes.js │ │ │ ├── chunk.js │ │ │ ├── document_data.js │ │ │ ├── history.js │ │ │ ├── line_widget.js │ │ │ ├── mark_text.js │ │ │ ├── selection.js │ │ │ └── selection_updates.js │ │ ├── modes.js │ │ └── util/ │ │ ├── StringStream.js │ │ ├── bidi.js │ │ ├── browser.js │ │ ├── dom.js │ │ ├── event.js │ │ ├── feature_detection.js │ │ ├── misc.js │ │ └── operation_group.js │ ├── test/ │ │ ├── comment_test.js │ │ ├── contenteditable_test.js │ │ ├── doc_test.js │ │ ├── driver.js │ │ ├── emacs_test.js │ │ ├── html-hint-test.js │ │ ├── index.html │ │ ├── lint.js │ │ ├── mode_test.css │ │ ├── mode_test.js │ │ ├── multi_test.js │ │ ├── phantom_driver.js │ │ ├── run.js │ │ ├── scroll_test.js │ │ ├── search_test.js │ │ ├── sql-hint-test.js │ │ ├── sublime_test.js │ │ ├── test.js │ │ └── vim_test.js │ └── theme/ │ ├── 3024-day.css │ ├── 3024-night.css │ ├── abcdef.css │ ├── ambiance-mobile.css │ ├── ambiance.css │ ├── base16-dark.css │ ├── base16-light.css │ ├── bespin.css │ ├── blackboard.css │ ├── cobalt.css │ ├── colorforth.css │ ├── darcula.css │ ├── dracula.css │ ├── duotone-dark.css │ ├── duotone-light.css │ ├── eclipse.css │ ├── elegant.css │ ├── erlang-dark.css │ ├── gruvbox-dark.css │ ├── hopscotch.css │ ├── icecoder.css │ ├── idea.css │ ├── isotope.css │ ├── lesser-dark.css │ ├── liquibyte.css │ ├── lucario.css │ ├── material.css │ ├── mbo.css │ ├── mdn-like.css │ ├── midnight.css │ ├── monokai.css │ ├── neat.css │ ├── neo.css │ ├── night.css │ ├── oceanic-next.css │ ├── panda-syntax.css │ ├── paraiso-dark.css │ ├── paraiso-light.css │ ├── pastel-on-dark.css │ ├── railscasts.css │ ├── rubyblue.css │ ├── seti.css │ ├── shadowfox.css │ ├── solarized.css │ ├── ssms.css │ ├── the-matrix.css │ ├── tomorrow-night-bright.css │ ├── tomorrow-night-eighties.css │ ├── ttcn.css │ ├── twilight.css │ ├── vibrant-ink.css │ ├── xq-dark.css │ ├── xq-light.css │ ├── yeti.css │ └── zenburn.css ├── DMP/ │ ├── AUTHORS │ ├── LICENSE │ ├── METADATA │ ├── diff_match_patch.py │ └── diff_match_patch_uncompressed.js ├── JSHint/ │ ├── LICENSE │ ├── README.md │ └── jshint.js └── SVG-Edit/ ├── AUTHORS ├── LICENSE ├── METADATA ├── README.md └── editor/ ├── browser.js ├── canvg/ │ ├── canvg.js │ └── rgbcolor.js ├── coords.js ├── draw.js ├── external/ │ └── dynamic-import-polyfill/ │ └── importModule.js ├── history.js ├── historyrecording.js ├── jquery-svg.js ├── layer.js ├── math.js ├── path.js ├── pathseg.js ├── recalculate.js ├── sanitize.js ├── select.js ├── svgcanvas.js ├── svgedit.js ├── svgtransformlist.js ├── svgutils.js └── units.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .clang-format ================================================ Language: JavaScript BasedOnStyle: Google ColumnLimit: 80 ================================================ FILE: .gitignore ================================================ .DS_Store nohup.out *~ login/loginServer.cfg login/node_modules connect/connectServer.cfg connect/node_modules server/node_modules var/ *.city *.city.partial *.pyc ================================================ FILE: CONTRIBUTING.md ================================================ # How to Contribute We'd love to accept your patches and contributions to this project. There are just a few small guidelines you need to follow. ## Contributor License Agreement Contributions to this project must be accompanied by a Contributor License Agreement. You (or your employer) retain the copyright to your contribution; this simply gives us permission to use and redistribute your contributions as part of the project. Head over to to see your current agreements on file or to sign a new one. You generally only need to submit a CLA once, so if you've already submitted one (even if it was for a different project), you probably don't need to do it again. ## Code reviews All submissions, including submissions by project members, require review. We use GitHub pull requests for this purpose. Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more information on using pull requests. ## Community Guidelines This project follows [Google's Open Source Community Guidelines](https://opensource.google.com/conduct/). ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2011 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS ================================================ FILE: README.md ================================================ # Code City Google's Code City is a social programming environment designed mainly for education. It offers a comic book inspired virtual world where programmers can write code collaboratively. A list of running Code City instances may be found at https://codecity.world/ ================================================ FILE: bin/dump-core ================================================ #!/bin/bash # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Create configuration file for and then start nginx, for use as a # local development server. nginx is configured to run in the # foreground, and to store all runtime data in /var, # rather than in /var/ or /usr/local/var/ as it might normally. set -e # Get top level directory of the CodeCity git repository. It's the # parent directory of the directory containing this script. repo="$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. >/dev/null 2>&1 && pwd)" cd "${repo}" mkdir -p var/dump # Make way for dump. Ignore errors. rm var/dump/*.js || true rm core/core_[1-8]*.js || true rm database/core_*.js || true rm database/db_*.js || true # Get last .city file. city=$( (cd database && ls -1 *.city |sort |tail -1) ) # Run dump. server/dump "database/${city}" core/dump_spec.json core # Link core file into database, except core_99_startup.js (cd database && ln -s ../core/core_[0-8]*.js .) ================================================ FILE: bin/nginx-dev ================================================ #!/bin/bash # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Create configuration files for and then start nginx, for use as a # local development server. nginx is configured to run in the # foreground, and to store all runtime data in /var, # rather than in /var/ or /usr/local/var/ as it might normally. # # This is done by generating var/nginx-dev.conf, which will include # var/cc-localhost.conf, which is copied (with edits) from # etc/cc-localhost.conf, then starting nginx specifying # var/nginx-dev.conf as the config file to use. set -e # Get top level directory of the CodeCity git repository. It's the # parent directory of the directory containing this script. readonly repo="$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. >/dev/null 2>&1 && pwd)" # Create var directory if required if [[ ! -d "${repo}/var" ]] ; then if [[ -x "${repo}/var" ]] ; then echo "${repo}/var already exists and is not a directory" 1>&2 exit 1 fi mkdir "${repo}/var" fi # Find location where the nginx installation keeps its config files. # We only want the mime.types file. dirs=(/usr/local/etc /etc/opt /etc) if type brew >/dev/null 2>&1 ; then # Homebrew in path? dirs=("$(brew --prefix)/etc" "${dirs[@]}") fi for dir in "${dirs[@]}"; do if [[ -d "${dir}" && -f "${dir}/nginx/mime.types" ]] ; then readonly mimetypes="${dir}/nginx/mime.types" break; fi done if [[ -z "${mimetypes}" ]] ; then echo "$0: can't find mime.types file." 1>&2 exit 1; fi cat >"$repo/var/nginx-dev.conf" < ${repo}/var/cc-localhost.conf nginx -c "$repo/var/nginx-dev.conf" ================================================ FILE: bin/startup.command ================================================ #!/usr/bin/osascript # Script to open four terminal windows that execute all the Code City servers # with one double-click. For OSX. tell application "Finder" set basePath to (POSIX path of (container of (container of (path to me)) as alias)) end tell tell app "Terminal" do script "cd " & basePath & "/login ./loginServer" do script "cd " & basePath & "/connect ./connectServer" do script "cd " & basePath & "/mobwrite python2 mobwrite_server.py" do script "cd " & basePath & "/server ./codecity " & basePath & "/database/codecity.cfg" end tell ================================================ FILE: connect/connect.html ================================================ Code City
World
Log
Pause scroll
Clear buffer
Loading...
================================================ FILE: connect/connectServer ================================================ #!/usr/bin/env node /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Node.js server that provides connection services to Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; var crypto = require('crypto'); var fs = require('fs'); var http = require('http'); var net = require('net'); // Configuration constants. const configFileName = 'connectServer.cfg'; // Global variables. var CFG = null; var queueList = Object.create(null); const DEFAULT_CFG = { // Internal port for this HTTP server. Nginx hides this from users. httpPort: 7782, // URL of login page (absolute or relative). loginUrl: 'https://login.example.codecity.world/', // URL of static folder (absolute or relative). staticUrl: 'https://static.example.codecity.world/', // Host of Code City. remoteHost: 'localhost', // Port of Code City. remotePort: 7777, // Age in seconds of abandoned queues to be closed. connectionTimeout: 300 }; /** * Class for one user's connection to Code City. * Establishes a connection and buffers the text coming from Code City. * @param {string} id ID of this queue. * @constructor */ var Queue = function (id) { // Save 'this' for closures below. var thisQueue = this; /** * ID of this queue in queueList. */ this.id = id; /** * Time that this queue was pinged by a user. Abandoned queues are deleted. */ this.lastPingTime = Date.now(); /** * The index number of the most recent memo added to the memo buffer. */ this.memoNum = 0; /** * Buffer of incomplete data from Code City. * If undefined, drop all input until next linefeed. */ this.lineBuffer = ''; /** * Maximum allowed length (in bytes) of a single memo. */ this.maxLineSize = 10 * 1024 * 1024; /** * Buffer of memos from Code City to the user. */ this.memoBuffer = []; /** * The index number of the most recent command received from the user. */ this.commandNum = 0; /** * Persistent TCP connection to Code City. */ this.client = new net.Socket(); this.client.on('close', this.destroy.bind(this, 'Code City closed session')); this.client.on('error', function(error) { console.log('TCP error for session ' + id, error); }); this.client.on('data', function(data) { function drop(overflow) { console.log('Session ' + id + ' drops ' + overflow.length + ' bytes of data.'); return '{"type":"narrate","text":"[OVERFLOW: ' + overflow.length + ' bytes lost.]"}\n'; } var text = data.toString(); if (!text) { return; } if (thisQueue.lineBuffer) { text = thisQueue.lineBuffer + text; } // Split into lines, while preserving the linebreaks. var lines = text.split(/^/m); if (thisQueue.lineBuffer === undefined) { // Throw away continued oversized line. var incompleteLine = lines.shift(); lines.unshift(drop(incompleteLine)); if (incompleteLine.endsWith('\n')) { // Found the end of the oversized line. Reset the buffer. thisQueue.lineBuffer = ''; } } for (var i = 0; i < lines.length; i++) { if (lines[i].endsWith('\n')) { if (lines[i].length > thisQueue.maxLineSize) { // Line is complete, but oversized. Drop. lines[i] = drop(lines[i]); } thisQueue.memoBuffer.push(lines[i]); thisQueue.memoNum++; } else { // Incomplete line. if (lines[i].length > thisQueue.maxLineSize) { // Discard, and throw away everything till next linebreak. thisQueue.memoBuffer.push(drop(lines[i])); thisQueue.memoNum++; thisQueue.lineBuffer = undefined; } else { // Save this line to the buffer so it may be completed next time. thisQueue.lineBuffer = lines[i]; } } } }); this.client.connect(CFG.remotePort, CFG.remoteHost); }; /** * Close this queue and deregister it. * @param {string} msg Console message to print (with ID appended). */ Queue.prototype.destroy = function(msg) { if (queueList[this.id]) { delete queueList[this.id]; } this.client.end(); console.log(msg + ' ' + this.id); }; /** * Load a file from disk, add substitutions, and serve to the web. * @param {!Object} response HTTP server response object. * @param {string} filename Name of template file on disk. * @param {!Object} subs Hash of replacement strings. */ function serveFile(response, filename, subs) { fs.readFile(filename, 'utf8', function(err, data) { if (err) { response.statusCode = 500; console.log(err); response.end('Unable to load file: ' + filename + '\n' + err); } // Inject substitutions. for (var name in subs) { data = data.replace(new RegExp(name, 'g'), subs[name]); } // Serve page to user. response.statusCode = 200; response.setHeader('Content-Type', 'text/html'); response.end(data); }); } /** * Handles HTTP requests from web server. * @param {!Object} request HTTP server request object * @param {!Object} response HTTP server response object. */ function handleRequest(request, response) { if (request.connection.remoteAddress !== '127.0.0.1') { // This check is redundant, the server is only accessible to // localhost connections. console.log('Rejecting connection from ' + request.connection.remoteAddress); response.end('Connection rejected.'); return; } var path = request.url.split('?')[0]; // Strip off any parameters. if (request.method === 'GET' && path.endsWith('/log')) { serveFile(response, 'log.html', {'<<>>': CFG.staticUrl}); return; } if (request.method === 'GET' && path.endsWith('/world')) { serveFile(response, 'world.html', {'<<>>': CFG.staticUrl}); return; } if (request.method === 'GET' && path.endsWith('/')) { var cookieList = {}; var rhc = request.headers.cookie; rhc && rhc.split(';').forEach(function(cookie) { var parts = cookie.split('='); cookieList[parts.shift().trim()] = decodeURI(parts.join('=')); }); // Validate the ID to ensure there was no tampering. var m = cookieList.ID && cookieList.ID.match(/^[0-9a-f]+$/); if (!m) { console.log('Missing login cookie. Redirecting.'); response.writeHead(302, { // Temporary redirect. 'Location': CFG.loginUrl }); response.end('Login required. Redirecting.'); return; } var seed = (Date.now() * Math.random()).toString() + cookieList.ID; // This ID gets transmitted a *lot* so keep it short. var sessionId = crypto.createHash('sha3-224').update(seed).digest('base64'); if (Object.keys(queueList).length > 1000) { response.statusCode = 429; response.end('Too many queues open at once.'); console.log('Too many queues open at once.'); return; } var queue = new Queue(sessionId); queueList[sessionId] = queue; // Start a connection. queue.client.write('identify as ' + cookieList.ID + '\n'); var subs = { '<<>>': sessionId, '<<>>': CFG.staticUrl }; serveFile(response, 'connect.html', subs); console.log('Hello xxxx' + cookieList.ID.substring(cookieList.ID.length - 4) + ', starting session ' + sessionId); return; } if (request.method === 'POST' && path.endsWith('/ping')) { var requestBody = ''; request.on('data', function(data) { requestBody += data; if (requestBody.length > 1000000) { // Megabyte of commands? console.error('Oversized JSON: ' + requestBody.length / 1024 + 'kb'); response.statusCode = 413; response.end('Request Entity Too Large'); } }); request.on('end', function() { // No ID cookie, the user has logged out. if (!/(^|;)\s*ID=\w/.test(request.headers.cookie)) { console.error('Not logged in'); response.statusCode = 410; response.end('Not logged in'); return; } try { var receivedJson = JSON.parse(requestBody); if (!receivedJson['q']) { throw Error('No queue'); } } catch (e) { console.error('Illegal JSON'); response.statusCode = 412; response.end('Illegal JSON'); return; } ping(receivedJson, response); }); return; } response.statusCode = 404; response.end('Unknown connectServer URL: ' + request.url); } function ping(receivedJson, response) { var q = receivedJson['q']; var ackMemoNum = receivedJson['ackMemoNum']; var cmdNum = receivedJson['cmdNum']; var cmds = receivedJson['cmds']; var logout = receivedJson['logout']; var queue = queueList[q]; if (!queue) { console.log('Unknown session ' + q); response.statusCode = 410; response.end('Your session has timed out'); return; } queue.lastPingTime = Date.now(); if (typeof ackMemoNum === 'number') { if (ackMemoNum > queue.memoNum) { var msg = 'Client ' + q + ' ackMemoNum ' + ackMemoNum + ', but queue.memoNum is only ' + queue.memoNum; console.error(msg); response.statusCode = 412; response.end(msg); return; } // Client acknowledges receipt of memos. // Remove them from the output list. queue.memoBuffer.splice(0, queue.memoBuffer.length + ackMemoNum - queue.memoNum); } var delay = 0; if (typeof cmdNum === 'number') { // Client sent commands. Increase server's index for acknowledgment. var currentIndex = cmdNum - cmds.length + 1; for (var i = 0; i < cmds.length; i++) { if (currentIndex > queue.commandNum) { queue.commandNum = currentIndex; // Send commands to Code City. queue.client.write(cmds[i]); delay += 200; } currentIndex++; } var ackCmdNextPing = true; } else { var ackCmdNextPing = false; } if (logout) { pong(queue, response, ackCmdNextPing); queue.destroy('Client disconnected'); } else { // Wait a fifth of a second for each command, // but don't wait for more than a second. var delay = Math.min(delay, 1000); var replyFunc = pong.bind(null, queue, response, ackCmdNextPing); setTimeout(replyFunc, delay); } } function pong(queue, response, ackCmdNextPing) { var sendingJson = {}; if (ackCmdNextPing) { sendingJson['ackCmdNum'] = queue.commandNum; } if (queue.memoBuffer.length) { sendingJson['memoNum'] = queue.memoNum; sendingJson['memos'] = queue.memoBuffer; } response.statusCode = 200; response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify(sendingJson)); } /** * Read the JSON configuration file and return it. If none is * present, write a stub and throw an error. */ function readConfigFile(filename) { let data; try { data = fs.readFileSync(filename, 'utf8'); } catch (err) { console.log(`Configuration file ${filename} not found. ` + 'Creating new file.'); data = JSON.stringify(DEFAULT_CFG, null, 2) + '\n'; fs.writeFileSync(filename, data, 'utf8'); } CFG = JSON.parse(data); if (!CFG.loginUrl || CFG.loginUrl === DEFAULT_CFG.loginUrl) { throw Error( `Configuration file ${filename} not configured. ` + 'Please edit this file.'); } if (!CFG.loginUrl.endsWith('/')) CFG.loginUrl += '/'; if (!CFG.staticUrl.endsWith('/')) CFG.staticUrl += '/'; } /** * Close and destroy any abandoned queues. Called every minute. */ function cleanup() { var bestBefore = Date.now() - CFG.connectionTimeout * 1000; for (var id in queueList) { var queue = queueList[id]; if (queue.lastPingTime < bestBefore) { queue.destroy('Timeout of session'); } } } /** * Start up the HTTP server. */ function startup() { readConfigFile(configFileName); var server = http.createServer(handleRequest); server.listen(CFG.httpPort, 'localhost', function(){ console.log('Connection server listening on port ' + CFG.httpPort); }); setInterval(cleanup, 60 * 1000); } startup(); ================================================ FILE: connect/log.html ================================================ Code City: Log frame
Connected. Disconnected. Reconnect? You see %1 here. You see %1 here. %1 is here. %1 are here. Someone %1 says, "%2" You say, "%1" %1 asks, "%2" You ask, "%1" %1 exclaims, "%2" You exclaim, "%1" %1 thinks, "%2" You think, "%1" and
================================================ FILE: connect/world.html ================================================ Code City: World frame
Connected. Disconnected. Reconnect? Close iframe ↻ Relaunch iframe
================================================ FILE: core/README ================================================ This database contains the latest release of the official Code City Core. Normally, when creating a new instance, the database should be initialised by reading all these files in, in order, into the new server. This will normally be accomplished by symlinking them into the /database/ directory, making sure that no .city files are present in that directory, then starting the server using database/codecity.cfg. The following naming convention has been established to keep things organised: core_0?_*.js - ES5.1 (and later) polyfills / JS base language stuff. core_1?_*.js - Base structure & utilities ($, $.utils, etc.) core_2?_*.js - Web servers, editors, etc. core_3?_*.js - Physical world infrastructure, telnet server, etc. core_4?_*.js - Start room, demos, etc. test_??_*.js - Any tests to be run against the database. ================================================ FILE: core/core_10_base.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Database core for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// var perms = new 'perms'; var setPerms = new 'setPerms'; var $ = function $(selector) { return new $.Selector(selector).toValue(/*save:*/ true); }; $.root = new 'CC.root'; $.root.name = 'root'; $.root.toString = function toString() { return 'root'; }; $.physicals = (new 'Object.create')(null); $.physicals.Maximilian = {}; $.physicals.Neil = {}; $.system = {}; $.system.log = new 'CC.log'; $.system.checkpoint = new 'CC.checkpoint'; $.system.shutdown = new 'CC.shutdown'; $.system.connectionListen = new 'CC.connectionListen'; $.system.connectionUnlisten = new 'CC.connectionUnlisten'; $.system.connectionWrite = new 'CC.connectionWrite'; $.system.connectionClose = new 'CC.connectionClose'; $.system.xhr = new 'CC.xhr'; $.system.onStartup = function onStartup() { /* Do things needed at database start, when starting from a .js dump * rather than from a .city snapshot (which preserves threads, * listening sockets, etc.) */ // Listen on various sockets. try {$.system.connectionListen(7776, $.servers.login.connection, 100);} catch(e) {} try {$.system.connectionListen(7777, $.servers.telnet.connection, 100);} catch(e) {} try {$.system.connectionListen(7780, $.servers.http.connection, 100);} catch(e) {} try {$.system.connectionListen(9999, $.servers.eval.connection);} catch(e) {} $.system.log('Startup: listeners started.'); // Restart timers and clear auto-expring caches. $.clock.validate(); $.db.tempId.cleanNow(); suspend(); $.system.log('Startup: timers restarted and caches cleared.'); // Rebuild Selector reverse-lookup database, which is not presently // preserved in the dump as it is a WeakMap. $.Selector.db.populate(); $.system.log('Startup: Selector reverse-lookup DB rebuilt.'); }; Object.setOwnerOf($.system.onStartup, $.physicals.Neil); Object.setOwnerOf($.system.onStartup.prototype, $.physicals.Maximilian); var user = function user() { /* The global user() is intended to be used to find the current * user object from deeply-nested functions (to which it is * impractical to thread cmd.user, for whatever reason). * * Previously user was a global variable set to the current user * object by $.servers.telnet.connection.onReceiveLine, but this * can cause problems when one command's execution suspends and * another user's command runs in mean time. * * It is preferable to avoid using this function; instead, use * cmd.user or this where possible. */ $.system.log('Auditing user() usage:\n' + (new Error()).stack); return Object.getOwnerOf(Thread.current()); }; $.utils = {}; $.utils.validate = {}; $.servers = {}; ================================================ FILE: core/core_11_$.utils.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Basic utilities for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.utils.validate.ownArray = function ownArray(object, key) { // Ensure that object[key] is an array not shared with any other // object or property, not inherited from a prototype, etc. // If it is, relaced it with a new, unshared array with the same // contents (if possible). if (!object.hasOwnProperty(key) || !Array.isArray(object[key]) || object[key].forObj !== object || object[key].forKey !== key) { try { object[key] = Array.from(object[key]); } catch (e) { object[key] = []; } Object.defineProperties(object[key], {forObj: {value: object}, forKey: {value: key}}); } }; Object.setOwnerOf($.utils.validate.ownArray, $.physicals.Maximilian); $.utils.validate.functionPrototypes = function functionPrototypes() { /* Find (and fix) functions that have f.prototype.constructor !== f. */ var u = user(); u.narrate('Looking for functions with mismatched .prototype.constructor...'); $.utils.object.spider($, function findProtosHelper(object, path) { // Skip $.archive entirely. if (object === $.archive) return true; if (typeof object !== 'function') return false; var selector = $.Selector.for(object) || new $.Selector(['$'].concat(path)); if (!object.prototype) { if (!String(object).includes('[native code]')) { u.narrate(String(selector) + ' has no .prototype'); } } else if (!object.prototype.constructor) { u.narrate(String(selector) + ' has no .prototype.constructor'); } else if (object.prototype.constructor !== object) { u.narrate(String(selector) + ' has mismatched .prototype.constructor'); var protoProps = Object.getOwnPropertyNames(object.prototype); var pcSelector = $.Selector.for(object.prototype.constructor); // Does it look like a plain old boring auto-created .prototype object? var pd = Object.getOwnPropertyDescriptor(object.prototype, 'constructor'); if (Object.getPrototypeOf(object.prototype) === Object.prototype && protoProps.length === 1 && protoProps[0] === 'constructor' && pd.writable === true && pd.enumerable === false && pd.configurable === true ) { if (String(pcSelector) === String(selector) + '.prototype.constructor') { u.narrate('----Fixable?: yes!'); object.prototype.constructor = object; } else { u.narrate('----Fixable?: yes🤞 (is ' + String(pcSelector) + ')'); // Make new .prototype object, since current one is likely shared. var newProto = {constructor: object}; Object.setOwnerOf(newProto, Object.getOwnerOf(object)); Object.defineProperty(newProto, 'constructor', {enumerable: false}); object.prototype = newProto; } } else { u.narrate('----Fixable?: NO: has properties other than .constructor' + (pcSelector ? ' (is ' + String(pcSelector) + ')' : '')); } } return false; }); u.narrate('Done.'); }; Object.setOwnerOf($.utils.validate.functionPrototypes, $.physicals.Maximilian); Object.setOwnerOf($.utils.validate.functionPrototypes.prototype, $.physicals.Maximilian); $.utils.isObject = function isObject(v) { /* Returns true iff v is an object (of any class, including Array * and Function). */ return (typeof v === 'object' && v !== null) || typeof v === 'function'; }; Object.setOwnerOf($.utils.isObject, $.physicals.Maximilian); $.utils.imageMatch = {}; $.utils.imageMatch.recog = function recog(svgText) { svgText = '' + svgText + ''; var json = $.system.xhr('https://neil.fraser.name/scripts/imageMatch.py' + '?svg=' + encodeURIComponent(svgText)); return JSON.parse(json); }; Object.setOwnerOf($.utils.imageMatch.recog, $.physicals.Neil); Object.setOwnerOf($.utils.imageMatch.recog.prototype, $.physicals.Neil); $.utils.regexp = {}; Object.setOwnerOf($.utils.regexp, $.physicals.Neil); $.utils.regexp.escape = function escape(str) { // Escape a string so that it may be used as a literal in a regular expression. // Example: $.utils.regexp.escape('[...]') -> "\\[\\.\\.\\.\\]" // Usecase: new RegExp($.utils.regexp.escape('[...]')).test('Alpha [...] Beta') // // Source: https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); }; Object.setOwnerOf($.utils.regexp.escape, $.physicals.Neil); Object.setOwnerOf($.utils.regexp.escape.prototype, $.physicals.Neil); $.utils.array = {}; $.utils.array.filterUntilFound = function filterUntilFound(array, filter1 /*, filter2, filter3... */) { // Apply Array.prototype.filter.call(array, filterN) for each filter // in turn until one returns a non-empty result. Return that // result, or an empty array if there are no more filters. filters = Array.from(arguments).slice(1); while (filters.length > 0) { var filter = filters.shift(); var result = array.filter(filter); if (result.length > 0) return result; } return []; }; Object.setOwnerOf($.utils.array.filterUntilFound, $.physicals.Maximilian); $.utils.object = {}; Object.setOwnerOf($.utils.object, $.physicals.Maximilian); $.utils.object.spider = function spider(start, callback) { /* Spider the objects accessible transitively via the properties of * object. * * Arguments: * start: object: Starting point for traversal of the object graph. * callback: function(object, Array 'Foo' * Assumes incoming text is already lowercase. */ return str.charAt(0).toUpperCase() + str.substring(1); }; Object.setOwnerOf($.utils.string.capitalize, $.physicals.Neil); $.utils.string.randomCharacter = function randomCharacter(chars) { return chars.charAt(Math.random() * chars.length); }; $.utils.string.VOWELS = 'aeiouy'; $.utils.string.CONSONANTS = 'bcdfghjklmnpqrstvwxz'; $.utils.string.ALPHABET = 'abcdefghijklmnopqrstuvwxyz'; $.utils.string.hash = new 'CC.hash'; $.utils.string.translate = function translate(text, language) { /* Try to translate text into the specified language using an * external translation server. * * Arguments: * text: string: the text to be translated. * language: string: a two-character ISO 639-1 language code. * * Returns: the translated text. */ var url = 'https://translate-service.scratch.mit.edu' + '/translate?language=' + encodeURIComponent(language) + '&text=' + encodeURIComponent(text); var json = $.system.xhr(url); return JSON.parse(json).result; }; Object.setOwnerOf($.utils.string.translate, $.physicals.Maximilian); Object.setOwnerOf($.utils.string.translate.prototype, $.physicals.Maximilian); $.utils.string.generateRandom = function generateRandom(length, soup) { /* Return a string of the specified length consisting of characters from the * given soup, or $.utils.string.generateRandom.DEFAULT_SOUP if none * specified. * * E.g.: generateRandom(4, 'abc') might return 'cbca'. * * Arguments: * - length: number - length of string to generate. * - soup: string - alphabet to select characters randomly from. */ soup = soup || $.utils.string.generateRandom.DEFAULT_SOUP; var out = []; for (var i = 0; i < length; i++) { out[i] = this.randomCharacter(soup); } return out.join(''); }; Object.setOwnerOf($.utils.string.generateRandom, $.physicals.Maximilian); Object.setOwnerOf($.utils.string.generateRandom.prototype, $.physicals.Neil); $.utils.string.generateRandom.DEFAULT_SOUP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $.utils.string.prefixLines = function prefixLines(text, prefix) { // Prepend a common prefix onto each line of code. // Intended for indenting code or adding '//' comment markers. return prefix + text.replace(/(?!\n$)\n/g, '\n' + prefix); }; Object.setOwnerOf($.utils.string.prefixLines, $.physicals.Neil); Object.setOwnerOf($.utils.string.prefixLines.prototype, $.physicals.Neil); ================================================ FILE: core/core_12_$.utils.code.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Code utilities for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.utils.code = {}; $.utils.code.rewriteForEval = function rewriteForEval(src, forceExpression) { /* Eval treats {} as an empty block (return value undefined). * Eval treats {'a': 1} as a syntax error. * Eval treats {a: 1} as block with a labeled statement (return value 1). * Detect these cases and enclose in parenthesis. * But don't mess with: {var x = 1; x + x;} * This is consistent with the console on Chrome and Node. * If 'forceExpression' is true, then throw a SyntaxError if the src is * more than one expression (e.g. '1; 2;'). */ var ast = null; if (!forceExpression) { // Try to parse src as a program. try { ast = $.utils.code.parse(src); } catch (e) { // ast remains null. } } if (ast) { if (ast.type === 'Program' && ast.body.length === 1 && ast.body[0].type === 'BlockStatement') { if (ast.body[0].body.length === 0) { // This is an empty object: {} return '({})'; } if (ast.body[0].body.length === 1 && ast.body[0].body[0].type === 'LabeledStatement' && ast.body[0].body[0].body.type === 'ExpressionStatement') { // This is an unquoted object literal: {a: 1} // There might be a comment, so add a linebreak. return '(' + src + '\n)'; } } return src; } // Try parsing src as an expression. // This may throw. ast = $.utils.code.parseExpressionAt(src, 0); var remainder = src.substring(ast.end).trim(); if (remainder !== '') { // Remainder might legally include trailing comments or semicolons. // Remainder might illegally include more statements. var remainderAst = null; try { remainderAst = $.utils.code.parse(remainder); } catch (e) { // remainderAst remains null. } if (!remainderAst) { throw new SyntaxError('Syntax error beyond expression'); } if (remainderAst.type !== 'Program') { throw new SyntaxError('Unexpected code beyond expression'); // Module? } // Trim off any unnecessary trailing semicolons. while (remainderAst.body[0] && remainderAst.body[0].type === 'EmptyStatement') { remainderAst.body.shift(); } if (remainderAst.body.length !== 0) { throw new SyntaxError('Only one expression expected'); } } src = src.substring(0, ast.end); if (ast.type === 'ObjectExpression' || ast.type === 'FunctionExpression') { // {a: 1} and function () {} both need to be wrapped in parens to avoid // being syntax errors. src = '(' + src + ')'; } return src; }; Object.setOwnerOf($.utils.code.rewriteForEval, $.physicals.Maximilian); $.utils.code.rewriteForEval.unittest = function() { var cases = { // Input: [Expression, Statement(s)] '1 + 2': ['1 + 2', '1 + 2'], '2 + 3 // Comment': ['2 + 3', '2 + 3 // Comment'], '3 + 4;': ['3 + 4', '3 + 4;'], '4 + 5; 6 + 7': [SyntaxError, '4 + 5; 6 + 7'], '{}': ['({})', '({})'], '{} // Comment': ['({})', '({})'], '{};': ['({})', '{};'], '{}; {}': [SyntaxError, '{}; {}'], '{"a": 1}': ['({"a": 1})', '({"a": 1})'], '{"a": 2} // Comment': ['({"a": 2})', '({"a": 2})'], '{"a": 3};': ['({"a": 3})', '({"a": 3})'], '{"a": 4}; {"a": 4}': [SyntaxError, SyntaxError], '{b: 1}': ['({b: 1})', '({b: 1}\n)'], '{b: 2} // Comment': ['({b: 2})', '({b: 2} // Comment\n)'], '{b: 3};': ['({b: 3})', '{b: 3};'], '{b: 4}; {b: 4}': [SyntaxError, '{b: 4}; {b: 4}'], 'function () {}': ['(function () {})', '(function () {})'], 'function () {} // Comment': ['(function () {})', '(function () {})'], 'function () {};': ['(function () {})', '(function () {})'], 'function () {}; function () {}': [SyntaxError, SyntaxError], '{} + []': ['{} + []', '{} + []'] }; var actual; for (var key in cases) { if (!cases.hasOwnProperty(key)) continue; // Test eval as an expression. try { actual = $.utils.code.rewriteForEval(key, true); } catch (e) { actual = SyntaxError; } if (actual !== cases[key][0]) { throw new Error('Eval Expression\n' + 'Expected: ' + cases[key][0] + ' Actual: ' + actual); } // Test eval as a statement. try { actual = $.utils.code.rewriteForEval(key, false); } catch (e) { actual = SyntaxError; } if (actual !== cases[key][1]) { throw new Error('Eval Statement\n' + 'Expected: ' + cases[key][1] + ' Actual: ' + actual); } } }; $.utils.code.eval = function $_utils_code_eval(src, evalFunc) { // Eval src and attempt to print the resulting value readably. // // Evaluation is done by calling evalFunc (passing src) if supplied, // or by calling the eval built-in function (under a different name, // so it operates in the global scope). Unhandled exceptions are // caught and converted to a string. // // Caller may wish to transform input with // $.utils.code.rewriteForEval before passing it to this function. evalFunc = evalFunc || eval; var out; try { out = evalFunc(src); } catch (e) { // Exception thrown. Use built-in ToString via + to avoid calling // String, least it call a .toString method that itself throws. // TODO(cpcallen): find an alternative way of doing this safely // once the interpreter calls String for all string conversions. if (e instanceof Error) { out = 'Unhandled error: ' + e.name; if (e.message) out += ': ' + e.message; if (e.stack) out += '\n' + e.stack; return out; } else { return 'Unhandled exception: ' + e; } } // Suspend if needed. try {(function(){})();} catch (e) {suspend();} // Attempt to print a source-legal representation. return $.utils.code.expressionFor(out, { depth: 2, abbreviateMethods: true, proto: 'note', owner: 'ignore' }); }; Object.setOwnerOf($.utils.code.eval, $.physicals.Maximilian); $.utils.code.regexps = {}; $.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'; $.utils.code.regexps._generate = function _generate() { /* Generate some RegExps that match various bits of JavaScript syntax. * The intention is that these regular expressions conform to the * lexical grammar given ES5.1 Appendix A.1 * (https://262.ecma-international.org/5.1/#sec-A.1), in some cases * updated to include changes in the current version of the spec * (https://tc39.es/ecma262/#sec-lexical-grammar). * * TODO: add tests for generated RegExps. */ // Globally matches escape sequences found in string and regexp // literals, like '\n' or '\x20' or '\u1234'. (This is basically // the spec EscapeSequence but including the backslash prefix.) this.escapes = /\\(?:["'\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g; // Globally matches a single-quoted string literal, like "'this one'" // and "'it\\'s'". this.singleQuotedString = new RegExp("'(?:[^'\\\\\\r\\n\\u2028\\u2029]|" + this.escapes.source + ")*'", 'g'); // Globally matches a double-quoted string literal, like '"this one"' // and '"it\'s"'. this.doubleQuotedString = new RegExp('"(?:[^"\\\\\\r\\n\\u2028\\u2029]|' + this.escapes.source + ')*"', 'g'); // Globally matches a StringLiteral, like "'this one' and '"that one"' // as well as "the 'string literal' substring of this longer string" too. this.string = new RegExp('(?:' + this.singleQuotedString.source + '|' + this.doubleQuotedString.source + ')', 'g'); // Globally matches a valid JavaScript IdentifierName. Note that // this is conservative, because ANY Unicode letter can appear // in an identifier - but the full regexp is absurdly complicated. this.identifierName = /[A-Za-z_$][A-Za-z0-9_$]*/g; // Matches a valid ES2020 ReservedWord. 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/; // Matches ES5.1 FutureReservedWords not included in reserved. var reservedES5 = /implements|interface|let|package|protected|public|static/; // Globally matches a valid JavaScript ReservedWord. this.reservedWord = new RegExp('(?:' + reserved.source + '|' + reservedES5.source + ')', 'g'); //////////////////////////////////////////////////////////////////// // Exact forms of the above. These do not get the global flag. var keys = ['identifierName', 'reservedWord', 'string']; for (var key, i = 0; (key = keys[i]); i++) { this[key + 'Exact'] = new RegExp('^' + this[key].source + '$'); } }; Object.setOwnerOf($.utils.code.regexps._generate.prototype, $.physicals.Maximilian); $.utils.code.regexps.escapes = /\\(?:["'\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g; $.utils.code.regexps.singleQuotedString = /'(?:[^'\\\r\n\u2028\u2029]|\\(?:["'\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*'/g; $.utils.code.regexps.doubleQuotedString = /"(?:[^"\\\r\n\u2028\u2029]|\\(?:["'\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}))*"/g; $.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; $.utils.code.regexps.identifierName = /[A-Za-z_$][A-Za-z0-9_$]*/g; $.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; $.utils.code.regexps.identifierNameExact = /^[A-Za-z_$][A-Za-z0-9_$]*$/; $.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)$/; $.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}))*")$/; $.utils.code.parseString = function parseString(s) { /* Convert a string representation of a string literal to a string. * Basically does eval(s), but safely and only if s is a string * literal. */ if (!this.regexps.stringExact.test(s)) { throw new TypeError(this.quote(s) + ' is not a string literal'); } return s.slice(1, -1).replace(this.regexps.escapes, function(esc) { switch (esc[1]) { case "'": case '"': case '/': case '\\': return esc[1]; case '0': return '\0'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case 'u': case 'x': return String.fromCharCode(parseInt(esc.slice(2), 16)); default: // RegExp in call to replace has accepted something we // don't know how to decode. throw new Error('unknown escape sequence "' + esc + '"??'); } }); }; Object.setOwnerOf($.utils.code.parseString, $.physicals.Maximilian); $.utils.code.quote = function quote(str) { // Convert a string into a string literal. We use single or double // quotes depending on which occurs less frequently in the string to // be escaped (prefering single quotes if it's a tie). Strictly // speaking we only need to escape backslash, \r, \n, \u2028 (line // separator), \u2029 (paragraph separator) and whichever quote // character we're using, but for output readability we escape all the // control characters. // // TODO(cpcallen): Consider using optimised algorithm from Node.js's // util.format (see strEscape function in // https://github.com/nodejs/node/blob/master/lib/util.js). // @param {string} str The string to convert. // @return {string} The value s as a eval-able string literal. if (this.count(str, "'") > this.count(str, '"')) { // More 's. Use "s. return '"' + str.replace(this.quote.doubleRE, this.quote.replace) + '"'; } else { // Equal or more "s. Use 's. return "'" + str.replace(this.quote.singleRE, this.quote.replace) + "'"; } }; $.utils.code.quote.singleRE = /[\x00-\x1f\\\u2028\u2029']/g; $.utils.code.quote.doubleRE = /[\x00-\x1f\\\u2028\u2029"]/g; $.utils.code.quote.replace = function replace(c) { // Replace special characters with their quoted replacements. // Intended to be used as the second argument to // String.prototype.replace. return $.utils.code.quote.replacements[c]; }; $.utils.code.quote.replacements = {}; $.utils.code.quote.replacements['\0'] = '\\0'; $.utils.code.quote.replacements['\x01'] = '\\x01'; $.utils.code.quote.replacements['\x02'] = '\\x02'; $.utils.code.quote.replacements['\x03'] = '\\x03'; $.utils.code.quote.replacements['\x04'] = '\\x04'; $.utils.code.quote.replacements['\x05'] = '\\x05'; $.utils.code.quote.replacements['\x06'] = '\\x06'; $.utils.code.quote.replacements['\x07'] = '\\x07'; $.utils.code.quote.replacements['\b'] = '\\b'; $.utils.code.quote.replacements['\t'] = '\\t'; $.utils.code.quote.replacements['\n'] = '\\n'; $.utils.code.quote.replacements['\v'] = '\\v'; $.utils.code.quote.replacements['\f'] = '\\f'; $.utils.code.quote.replacements['\r'] = '\\r'; $.utils.code.quote.replacements['\x0e'] = '\\x0e'; $.utils.code.quote.replacements['\x0f'] = '\\x0f'; $.utils.code.quote.replacements['"'] = '\\"'; $.utils.code.quote.replacements["'"] = "\\'"; $.utils.code.quote.replacements['\\'] = '\\\\'; $.utils.code.quote.replacements['\u2028'] = '\\u2028'; $.utils.code.quote.replacements['\u2029'] = '\\u2029'; $.utils.code.count = function count(str, searchString) { // Count non-overlapping occurrences of searchString in str. return str.split(searchString).length; }; $.utils.code.isIdentifier = function isIdentifier(id) { /* Arguments: * - id: any - any JavaScript value. * * Returns: boolean - true iff id is a string representing valid * Identifier, which is any bare word that can be used * as a variable name (i.e., excluding reserved words). */ return $.utils.code.isIdentifierName(id) && !$.utils.code.regexps.reservedWordExact.test(id); }; Object.setOwnerOf($.utils.code.isIdentifier, $.physicals.Maximilian); $.utils.code.getGlobal = function getGlobal() { // Return a pseudo global object. var global = Object.create(null); global.$ = $; global.Array = Array; global.Boolean = Boolean; global.clearTimeout = clearTimeout; global.Date = Date; global.decodeURI = decodeURI; global.decodeURIComponent = decodeURIComponent; global.encodeURI = encodeURI; global.encodeURIComponent = encodeURIComponent; global.Error = Error; global.escape = escape; global.eval = eval; global.EvalError = EvalError; global.Function = Function; global.isFinite = isFinite; global.isNaN = isNaN; global.JSON = JSON; global.Math = Math; global.Number = Number; global.Object = Object; global.parseFloat = parseFloat; global.parseInt = parseInt; global.perms = perms; global.RangeError = RangeError; global.ReferenceError = ReferenceError; global.RegExp = RegExp; global.setPerms = setPerms; global.setTimeout = setTimeout; global.String = String; global.suspend = suspend; global.SyntaxError = SyntaxError; global.Thread = Thread; global.TypeError = TypeError; global.unescape = unescape; global.URIError = URIError; global.user = user; global.WeakMap = WeakMap; return global; }; Object.setOwnerOf($.utils.code.getGlobal, $.physicals.Maximilian); $.utils.code.parse = new 'CC.acorn.parse'; $.utils.code.parseExpressionAt = new 'CC.acorn.parseExpressionAt'; $.utils.code.isIdentifierName = function isIdentifierName(id) { /* Arguments: * - id: any - any JavaScript value. * * Returns: boolean - true iff id is a string representing valid * IdentifierName, which is anything bare word that can appear * after the '.' in a MemberExpresion. */ return typeof id === 'string' && $.utils.code.regexps.identifierNameExact.test(id); }; Object.setOwnerOf($.utils.code.isIdentifierName, $.physicals.Maximilian); Object.setOwnerOf($.utils.code.isIdentifierName.prototype, $.physicals.Maximilian); $.utils.code.expressionFor = function expressionFor(value, options) { /* Given an arbitrary value, return a string containing a JavaScript * expression for it. * * The intention is that expressionFor(value) should return a string * such that eval(expressionFor(value)) will be (in order of preference): * * - Identical to value (as determined by Object.is), or * - An equivalent copy of value to a specified depth, or * - Be unparsable or contain comments explaining in what way the * result of eval will differ from original value. * * Arguments: * - value: any - any JavaScript value. * - options?: Object - optional options object. See implementation. * * Returns: string - an expression for value. * * TODO: there should be flags controlling what to do when it is not * possible to construct an expression that will eval to an exact copy * of value. The options should include returning valid code containing * comments, returning unparsable code, or throwing an an error. */ var opts = { depth: 10, // How deeply shall we traverse the object tree? arrayLimit: 100, // Max number of array elements to include. propertyLimit: 100, // Max number of properties to include. abbreviateFunctions: false, // Elide all function bodies? abbreviateMethods: false, // Elide method function bodies? proto: 'set', // 'set', 'note' or (any other value) ignore prototype. owner: 'note', // 'set', 'note' or (any other value) ignore owner. lineLength: 80, // Line length limit, for formatting purposes. indent: 2, // Indent for nested expressions. seen_: [], // TODO: use Set instead of Array. }; // Like Object.assign(opts, options) but copies inherited properties too. for (var k in options) opts[k] = options[k]; // Helper to handle failures where expressionFor cannot or does not yet // return an experssion that will eval to an identical copy of value. // Typical usage: return fail('reason for failure'); function fail(message) { // TODO: have flag to make it: // throw new ReferenceError(message); return $.utils.code.blockComment(message); } // Helper for properties in array and object literals. function expressionForProperty(key) { var descriptor = Object.getOwnPropertyDescriptor(value, key); var propertyValue = descriptor.value; if (selector) { opts.selector = new $.Selector(selector.concat(key)); } opts.abbreviateFunctions = opts.abbreviateMethods; return expressionFor(propertyValue, opts); } var type = typeof value; if (value === undefined || value === null || type === 'number' || type === 'boolean') { if (Object.is(value, -0)) return '-0'; return String(value); } else if (type === 'string') { return $.utils.code.quote(value); } else if (type !== 'function' && type !== 'object') { throw new TypeError("unknown type '" + type + "'"); } // value is an object of some kind (including function). Work out a selector. var selector = $.Selector.for(value); if (opts.selector) { var suggestedSelectorValue = opts.selector.toValue(/*save:*/true); if (!selector && suggestedSelectorValue === value) { selector = opts.selector; } } // Deal with already-seen objects (and nesting limit depth limit). if (opts.seen_.includes(value)) { return fail('cyclic or shared substructure' + (selector ? ': ' + selector.toString() : 'with no known selector')); } else if (opts.depth < 1) { if (!selector) return fail(type + ' with no known selector'); return selector.toExpr(); } // Prepare for recursive calls. opts.seen_.push(value); opts.depth--; opts.lineLength -= opts.indent; // Get the object's [[Class]] - Object, Array, Date, RegExp, Error, etc. // Since 'class' isn't a legal variable name, re-use 'type'. type = Object.prototype.toString.call(value).slice(8, -1); var proto = Object.getPrototypeOf(value); // Actual prototype of value. var expectedProto; // Expected prototype of object of same [[Class]] as value. var prefix = '', expr = '', suffix = ''; // Concatenate to get final expression. var entries; // Array of initialisers for object or array literal. var notes = []; // Array of notes to postpend as comment. // Make a note about the object's selector unless it is the expected // one. Decide this before recursive calls mess with opts.selector. var selectorNote = selector ? selector.toString() : ''; if (opts.selector && selectorNote === opts.selector.toString()) { selectorNote = ''; } if (type === 'Array') { if (!Array.isArray(value)) throw TypeError('non-array array??'); expectedProto = Array.prototype; prefix = '['; suffix = ']'; entries = []; for (var i = 0; i < value.length; i++) { suspend(); if (i >= opts.arrayLimit) { entries[i] = $.utils.code.blockComment('and ' + (value.length - opts.arrayLimit) + ' more'); break; } else if (!Object.hasOwnProperty.call(value, i)) { entries[i] = ''; continue; } entries[i] = expressionForProperty(String(i)); } } else if (type === 'Date') { expr = 'new Date(\'' + value.toJSON() + '\')'; expectedProto = Date.prototype; } else if (type === 'Error') { expectedProto = proto; switch (proto) { case EvalError.prototype: prefix = 'EvalError'; break; case RangeError.prototype: prefix = 'RangeError'; break; case ReferenceError.prototype: prefix = 'ReferenceError'; break; case SyntaxError.prototype: expr = 'SyntaxError'; break; case TypeError.prototype: expr = 'TypeError'; break; case URIError.prototype: expr = 'URIError'; break; case PermissionError.prototype: expr = 'PermissionError'; break; default: expr = 'Error'; expectedProto = Error.prototype; } if (typeof value.message === 'string') { expr += '(' + $.utils.code.quote(value.message) + ')'; } else { expr += '()'; } } else if (type === 'Function') { expectedProto = Function.prototype; expr = Function.prototype.toString.call(value); if (opts.abbreviateFunctions) { expr = fail(expr.replace(/\{[^]*$/, '{ ... }')); } } else if (type === 'Object') { expectedProto = Object.prototype; prefix = '{'; suffix = '}'; entries = []; var keys = Object.getOwnPropertyNames(value); for (var i = 0; i < keys.length; i++) { suspend(); if (i >= opts.propertyLimit) { entries[i] = '/* and ' + (keys.length - opts.propertyLimit) + ' more */'; break; } var key = keys[i]; // BUG(#469): property keys that are NumericLiterals (like 3.2e4 // or 0xf00) can also appear unquoted! entries[i] = ($.utils.code.isIdentifierName(key) ? key : $.utils.code.quote(key)) + ': ' + expressionForProperty(key); } } else if (type === 'RegExp') { expr = RegExp.prototype.toString.call(value); expectedProto = RegExp.prototype; } else if (type === 'Thread') { if (selector) return selector.toExpr(); expr = 'new Thread(' + fail('unable to reconstruct thread state') + ')'; expectedProto = Thread.prototype; } else if (type === 'WeakMap') { expectedProto = WeakMap.prototype; expr = 'new WeakMap()'; } else { throw new TypeError('unknown internal type ' + type); } // TODO: Prepend/append call to Object.defineProperties for remaining // properties & property attributes. // Pre/append prototype information if it is not as expected. if (proto !== expectedProto) { var protoString = expressionFor(proto, {depth: 0}); if (opts.proto === 'set') { prefix = 'Object.setPrototypeOf(' + prefix; suffix += ', ' + protoString + ')'; } else if (opts.proto === 'note') { notes.push('[[Proto]]: ' + protoString); } } // Prepend/append owner information. var ownerString = expressionFor(Object.getOwnerOf(value), {depth: 0}); if (opts.owner === 'set') { // BUG: Object.setOwnerOf(obj, owner) does not return obj (yet). throw new Error("can't set owner in an expression yet"); // prefix = 'Object.setOwnerOf(' + prefix; // suffix += ', ' + ownerString + ')'; } else if (opts.owner === 'note') { notes.push('[[Owner]]: ' + ownerString); } // Prepend/append notes. if (selectorNote) { prefix = $.utils.code.blockComment(selectorNote) + ' ' + prefix; } if (notes.length) { suffix += ' ' + $.utils.code.blockComment(notes.join(', ')); } // Join entries choosing a suitable layout depending on available space. if (entries && entries.length) { // Try single-line output. // BUG: this omits required trailing comma when there are undefined // trailing aray elements (e.g., [1, 2, 3,,]. expr = entries.join(', '); var result = prefix + expr + suffix; if (result.length <= opts.lineLength && !result.includes('\n')) { return result; } // Generate multi-line output. var padding = ' '.repeat(opts.indent); expr = '\n' + $.utils.string.prefixLines(entries.join(',\n'), padding) + ',\n'; } return prefix + expr + suffix; }; Object.setOwnerOf($.utils.code.expressionFor, $.physicals.Maximilian); Object.setOwnerOf($.utils.code.expressionFor.prototype, $.physicals.Maximilian); $.utils.code.blockComment = function blockComment(text) { /* Format text as a block comment. Any occurences of the closing * block comment delimiter in text will have a space inerted in them. * If text is undefined, an empty string will be returned instead. * * Arguments: * - text: string | undefined - the contents of the comment. * Returns: string - the block comment. */ return text ? '/* ' + text.replace(/\*\//g, '* /') + ' */' : ''; }; Object.setOwnerOf($.utils.code.blockComment, $.physicals.Maximilian); Object.setOwnerOf($.utils.code.blockComment.prototype, $.physicals.Maximilian); ================================================ FILE: core/core_13_$.Selector.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Selector implementation for Code City core. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.Selector = function Selector(s) { /* A Selector is a representation of a selector string in the form * of an array (of Selector.Parts) which happens to have * Selector.prototype (with various useful convenience methods) in * its prototype chain. */ var parts; if (typeof s === 'string') { // Parse selector text (but check in cache first). var cached = Selector.cache_[s]; // Copy and set owner? if (cached) return cached; parts = Selector.parse(s); } else if (Array.isArray(s)) { parts = []; // Validate & copy parts list. if (s.length < 1) throw new RangeError('Zero-length parts list??'); if (!$.utils.code.isIdentifier(s[0])) { throw new TypeError('parts array must begin with an identifier'); } parts[0] = s[0]; for (var i = 1; i < s.length; i++) { if (typeof s[i] === 'string' || s[i] === Selector.PROTOTYPE || s[i] === Selector.OWNER) { parts[i] = s[i]; } else if (s[i] instanceof Selector.SpecialPart) { throw new TypeError('Invalid SpecialPart in parts array'); } else if (typeof s[i] === 'object' && s[i].type) { // Handle normalisation of parts lists that have been roundtripped via JSON. switch(s[i].type) { case 'proto': parts[i] = Selector.PROTOTYPE; break; case 'owner': parts[i] = Selector.OWNER; break; default: throw new TypeError('Unknown SpecialPart type ' + s[i].type); } } else { throw new TypeError('Invalid part in parts array'); } } } else { throw new TypeError('Not a selector or parts array'); } Object.setPrototypeOf(parts, Selector.prototype); Object.freeze(parts); // Copy and set owner? Selector.cache_[parts.toString()] = parts; // Save. return parts; }; Object.setOwnerOf($.Selector, $.physicals.Maximilian); Object.setPrototypeOf($.Selector.prototype, Array.prototype); $.Selector.prototype.isOwner = function isOwner() { /* Returns true iff the selector represents an object owner binding. */ return this.length > 1 && this[this.length - 1] === this.constructor.OWNER; }; Object.setOwnerOf($.Selector.prototype.isOwner, $.physicals.Maximilian); $.Selector.prototype.isProp = function isProp() { /* Returns true iff the selector represents an object property binding. */ return this.length > 1 && typeof this[this.length - 1] === 'string'; }; Object.setOwnerOf($.Selector.prototype.isProp, $.physicals.Maximilian); $.Selector.prototype.isProto = function isProto() { /* Returns true iff the selector represents an object prototype binding. */ return this.length > 1 && this[this.length - 1] === this.constructor.PROTOTYPE; }; Object.setOwnerOf($.Selector.prototype.isProto, $.physicals.Maximilian); $.Selector.prototype.isVar = function isVar() { /* Returns true iff the selector represents a top-level variable binding. */ return this.length === 1 && typeof this[0] === 'string'; }; Object.setOwnerOf($.Selector.prototype.isVar, $.physicals.Maximilian); $.Selector.prototype.toExpr = function toExpr() { /* Return the selector as an evaluable expression yeilding the selected value. */ return this.toString(function(part, out) { if (part === $.Selector.PROTOTYPE) { out.unshift('Object.getPrototypeOf('); out.push(')'); } else if (part === $.Selector.OWNER) { out.unshift('Object.getOwnerOf('); out.push(')'); } else { throw new TypeError('Invalid part in parts array'); } }); }; Object.setOwnerOf($.Selector.prototype.toExpr, $.physicals.Maximilian); $.Selector.prototype.toSetExpr = function toSetExpr(valueExpr) { /* Return an expression setting the selected value to the value of the * supplied expression. * * The parameter valueExpr should be a string containing a JS expression that * evaluates to the new value to be assigned to the selected location. It * must not contain any non-parenthesized operators with lower precedence * than '=' - specifically, the yield and comma operators. */ var lastPart = this[this.length - 1]; if (!(lastPart instanceof this.constructor.SpecialPart)) { return this.toExpr() + ' = ' + valueExpr; } var objExpr = new this.constructor(this.slice(0, -1)).toExpr(); if (lastPart === this.constructor.PROTOTYPE) { return 'Object.setPrototypeOf(' + objExpr + ', ' + valueExpr + ')'; } else if (lastPart === this.constructor.OWNER) { return 'Object.setOwnerOf(' + objExpr + ', ' + valueExpr + ')'; } else { throw new TypeError('Invalid part in parts array'); } }; Object.setOwnerOf($.Selector.prototype.toSetExpr, $.physicals.Maximilian); $.Selector.prototype.toString = function toString(specialHandler) { /* Return the canonical selector string for this Selector. * * The specialHandler optional parameter, if supplied, should be callback * which accepts a Selector.SpecialPart instance and an Array of strings, and * pushes a string representation of the SpecialPart onto the array. (See * Selector.prototype.toExpr for an example of how to use this.) */ var out = [this[0]]; for (var i = 1; i < this.length; i++) { var part = this[i]; if (part instanceof this.constructor.SpecialPart) { if (specialHandler) { specialHandler(part, out); } else { out.push(String(part)); } } else if ($.utils.code.isIdentifierName(part)) { out.push('.', part); } else if (String(Number(part)) === part) { // String represents a number with same string representation. out.push('[', part, ']'); } else { out.push('[', $.utils.code.quote(part), ']'); } } return out.join(''); }; Object.setOwnerOf($.Selector.prototype.toString, $.physicals.Maximilian); $.Selector.prototype.toValue = function toValue(save, global) { /* Return value corresponding to this Selector, or throw EvalError if that is * not possible. This function basically does * * return eval(this.toExpr()) * * ...only slightly more safely. * * Added bonus features: * - If this selector evaluates to an object and save is true, the selector * will be added to the the reverse-lookup database. * - If global is specified, global variables will be evaluated by looking * them up as properties on that object. */ if (this.length === 0) throw RangeError('Invalid Selector'); var varname = this[0]; if (!$.utils.code.isIdentifier(varname)) { throw TypeError('invalid variable identifier'); } var v; if (global) { v = global[varname]; } else { try { var globalEval = eval; v = globalEval(varname); } catch (e) { v = undefined; } } for (var i = 1; i < this.length; i++) { if (!$.utils.isObject(v)) { var s = new this.constructor(this.slice(0, i)); throw TypeError(String(s) + ' is not an object'); } var part = this[i]; if (typeof part === 'string') { v = v[part]; } else if (part === this.constructor.PROTOTYPE) { v = Object.getPrototypeOf(v); } else if (part === this.constructor.OWNER) { v = Object.getOwnerOf(v); } else { throw new Error('Not implemented'); } } if (save) { this.constructor.db.set(v, this); } return v; }; Object.setOwnerOf($.Selector.prototype.toValue, $.physicals.Maximilian); $.Selector.prototype.badness = function badness() { /* Returns a "badness" score, inversely proportional to how * desirable a particular selector is amongst other selectors * referring to the same object. In general, longer selectors are * more bad, but selectors containing special parts are especially * bad. */ var penalties = 0; for (var i = 0; i < this.length; i++) { var part = this[i]; if (part instanceof this.constructor.SpecialPart) { penalties += 100; } else if ($.utils.code.isIdentifierName(part)) { penalties += 10; // We like identifiers. } else if (String(Number(part)) === part) { penalties += 25; // Numbers are OK. } else { penalties += 50; // Quoted strings are undesirable. } } if (this[0] === '$') penalties += 50; // Prefer builtins. return penalties + String(this).length; }; Object.setOwnerOf($.Selector.prototype.badness, $.physicals.Maximilian); $.Selector.SpecialPart = function SpecialPart(type) { // A SpecialPart is a class for all "special" selector parts (ones // which do not represent named variables / properties). this.type = type; Object.freeze(this); }; $.Selector.SpecialPart.prototype.toString = function toString() { return '{' + this.type + '}'; }; Object.setOwnerOf($.Selector.SpecialPart.prototype.toString, $.physicals.Maximilian); $.Selector.PROTOTYPE = (new 'Object.create')($.Selector.SpecialPart.prototype); $.Selector.PROTOTYPE.type = 'proto'; Object.defineProperty($.Selector.PROTOTYPE, 'type', {writable: false, configurable: false}); Object.preventExtensions($.Selector.PROTOTYPE); $.Selector.OWNER = (new 'Object.create')($.Selector.SpecialPart.prototype); $.Selector.OWNER.type = 'owner'; Object.defineProperty($.Selector.OWNER, 'type', {writable: false, configurable: false}); Object.preventExtensions($.Selector.OWNER); $.Selector.parse = function parse(selector) { // Parse a selector into an array of Parts. var tokens = this.parse.tokenize(selector); var parts = []; var State = { START: 0, GOOD: 1, DOT: 2, BRACKET: 3, BRACKET_DONE: 4, BRACE: 5, BRACE_DONE: 6 }; var state = State.START; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type === 'whitespace') continue; switch (state) { case State.START: if (token.type !== 'id') { throw new SyntaxError('Selector must start with an identifier'); } parts.push(token.raw); state = State.GOOD; break; case State.GOOD: if (token.type === '.') { state = State.DOT; } else if (token.type === '[') { state = State.BRACKET; } else if (token.type === '{') { state = State.BRACE; } else if (token.type === '^') { // State remains unchanged. parts.push(this.PROTOTYPE); } else { throw new SyntaxError('Invalid token ' + $.utils.code.quote(token.raw) + ' in selector'); } break; case State.DOT: if (token.type !== 'id') { throw new SyntaxError('"." must be followed by identifier in selector'); } parts.push(token.raw); state = State.GOOD; break; case State.BRACKET: if (token.type === 'number') { parts.push(String(token.raw)); } else if (token.type === 'str') { parts.push(String(token.value)); } else { throw new SyntaxError('"[" must be followed by numeric or string literal in selector'); } state = State.BRACKET_DONE; break; case State.BRACKET_DONE: if (token.type !== ']') { throw new SyntaxError('Invalid token ' + $.utils.code.quote(token.raw) + ' after subscript'); } state = State.GOOD; break; case State.BRACE: if (token.type === 'id' && token.raw === 'proto') { parts.push(this.PROTOTYPE); } else if (token.type === 'id' && token.raw === 'owner') { parts.push(this.OWNER); } else { throw new SyntaxError('"{" must be followed by "proto" or "owner"'); } state = State.BRACE_DONE; break; case State.BRACE_DONE: if (token.type !== '}') { throw new SyntaxError('Invalid token ' + $.utils.code.quote(token.raw) + ' after special'); } state = State.GOOD; break; default: throw new Error('Invalid State in parse??'); } } if (state !== State.GOOD) { throw new SyntaxError('Incomplete selector ' + selector); } return parts; }; Object.setOwnerOf($.Selector.parse, $.physicals.Maximilian); $.Selector.parse.tokenize = function tokenize(selector) { // Tokenizes a selector string. Throws a SyntaxError if any text is // found which does not form a valid token. var REs = { whitespace: /^\s+/g, '.': /^\./g, id: new RegExp('^' + $.utils.code.regexps.identifierName.source, 'g'), number: /^\d+/g, '[': /^\[/g, ']': /^\]/g, '{': /^\{/g, '}': /^\}/g, '^': /^\^/g, str: new RegExp('^' + $.utils.code.regexps.string.source, 'g'), }; var tokens = []; NEXT_TOKEN: for (var index = 0; index < selector.length; ) { for (var tokenType in REs) { if (!REs.hasOwnProperty(tokenType)) continue; var re = REs[tokenType]; re.lastIndex = 0; var m = re.exec(selector.slice(index)); if (!m) continue; // No match. Try next regexp. tokens.push({ type: tokenType, raw: m[0], valid: true, index: index, }); index += re.lastIndex; continue NEXT_TOKEN; } // No token matched. throw new SyntaxError('invalid selector ' + selector); } // Postprocess token list to get values. for(var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type === 'number') { token.value = Number(token.raw); } else if (token.type === 'str') { token.value = $.utils.code.parseString(token.raw); } } return tokens; }; Object.setOwnerOf($.Selector.parse.tokenize, $.physicals.Maximilian); $.Selector.for = function Selector_for(object) { /* Return a Selector for object, or undefined if none known. */ return this.db.get(object); }; Object.setOwnerOf($.Selector.for, $.physicals.Maximilian); $.Selector.db = {}; $.Selector.db.map_ = new WeakMap(); $.Selector.db.set = function set(object, selector) { if (!$.utils.isObject(object)) return; // Ignore non-object values. if (!(selector instanceof $.Selector)) { throw new TypeError('Second argument must be a Selector'); } var selectorString = selector.toString(); var known = this.map_.get(object) || []; // See if this selector is already known. if (known.includes(selectorString)) return; // Already known. Ignore. // Add new entry. known.push(selectorString); // Sort by badness, trim to length and save. $.Selector.sortByBadness(known); this.map_.set(object, known.slice(0, this.diversityLimit)); }; Object.setOwnerOf($.Selector.db.set, $.physicals.Maximilian); $.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).'; $.Selector.db.diversityLimit = 5; $.Selector.db.get = function get(object) { if (!$.utils.isObject(object)) return undefined; var known = this.map_.get(object); while (known && known.length) { var selector = new $.Selector(known[0]); var value = null; try { value = selector.toValue(); } catch (e) {} if (value === object) { return selector; } else { known.shift(); // Remove 0th item. } } return undefined; // Ran out of known, valid selectors. }; Object.setOwnerOf($.Selector.db.get, $.physicals.Maximilian); $.Selector.db.populate = function populate() { /* Spider the object graph, starting from the global scope, to * (re)build the reverse-lookup database. * * We apply a version of Dijkstra's algorithm, specifically a BFS * over valid Selectors, where we reenqueue children of previously- * -visited objects if we find a better Selector for the parent * object. */ // Prevent this function from running more than once at a time. if (populate.thread_) throw new Error('already running'); try { populate.thread_ = Thread.current(); var queue = Object.getOwnPropertyNames($.utils.code.getGlobal()).map( function (ss) {return new $.Selector(ss);}); var seen = new WeakMap(); for (var i = 0; i < queue.length; i++) { suspend(); var s = queue[i]; var v = s.toValue(/*save:*/true); if (!$.utils.isObject(v)) continue; // Skip primitives completely. var best = $.Selector.for(v); if (seen.has(v) && s !== best) continue; seen.set(v, true); var parts = [$.Selector.PROTOTYPE, $.Selector.OWNER].concat(Object.getOwnPropertyNames(v)); for (var j = 0; j < parts.length; j++) { var part = parts[j]; if (part === 'cache_') continue; // Skip .cache_ properties. queue.push(new $.Selector(s.concat(part))); } } } finally { populate.thread_ = null; } }; Object.setOwnerOf($.Selector.db.populate, $.physicals.Maximilian); Object.setOwnerOf($.Selector.db.populate.prototype, $.physicals.Maximilian); $.Selector.db.populate.thread_ = null; $.Selector.sortByBadness = function sortByBadness(selectors) { // Sort an array (or arraylike), which may contain Selectors, // (valid) selector strings, or a mix of the two, according to their // score, as returned by Selector.prototype.badness(), with the the // lowest-badness ones sorted first. if (!$.utils.isObject(selectors) || typeof selectors.length != 'number') { throw new TypeError('argument must be an arraylike'); } // Begin by populating a badness cache, for quick lookups. var cache = sortByBadness.cache_; for (var i = 0; i < selectors.length; i++) { var s, ss = selectors[i]; if (typeof ss === 'string') { s = new $.Selector(ss); } else if (ss instanceof $.Selector) { s = ss; ss = ss.toString(); } if (ss in cache) continue; cache[ss] = s.badness(); } // Do sort. Optimised for sorting selector strings, since // that's what's needed by $.Selector.db.put. Array.prototype.sort.call(selectors, function compare(a, b) { if (typeof a !== 'string') a = String(a); if (typeof b !== 'string') b = String(b); return cache[a] - cache[b]; }); return selectors; }; Object.setOwnerOf($.Selector.sortByBadness, $.physicals.Maximilian); $.utils.Binding = function Binding(object, part) { /* A binding is essentially just an (object, part) tuple, where part * is a string or a Selector.SpecialPart. * * If object is null, part must be a string conforming to the * syntax of an identifier; in this case the binding represents * a variable in the global scope. */ if (object === null) { if (!$.utils.code.isIdentifier(part)) { throw TypeError('Invalid variable name'); } } else if (!$.utils.isObject(object)) { throw TypeError('Invalid object'); } else if (typeof part !== 'string' && part !== $.Selector.PROTOTYPE && part !== $.Selector.OWNER) { throw TypeError('Invalid part'); } this.object = object; this.part = part; }; Object.setOwnerOf($.utils.Binding, $.physicals.Maximilian); $.utils.Binding.prototype.set = function set(value) { /* Set the value of the binding. Throws TypeError if unable. */ if (this.object === null) { if (!Object.prototype.hasOwnProperty.call($.utils.code.getGlobal(), this.part)) { throw new TypeError("Can't create new global variable"); } // Use a temporary property and an eval in the global scope (eval // by any other name, literally) to set the global variable // "safely". The temporary property is placed on $ rather than // using $.db.tempId to avoid the possibility of the eval // somehow being subverted to access a different value than // expected due to one of the intervening objects being // compromised (by a getter, say). var tmpId; do { tmpId = 'tmp' + Math.floor(Math.random() * 0xFFFFFFFF); } while (tmpId in $); var evalGlobal = eval; try { $[tmpId] = value; evalGlobal(this.part + ' = $.' + tmpId); } finally { delete $[tmpId]; } } else if(this.part === $.Selector.PROTOTYPE) { Object.setPrototypeOf(this.object, value); } else if(this.part === $.Selector.OWNER) { Object.setOwnerOf(this.object, value); } else { // BUG: doesn't handle non-writable properties. this.object[this.part] = value; } }; Object.setOwnerOf($.utils.Binding.prototype.set, $.physicals.Maximilian); $.utils.Binding.prototype.get = function get(inherited) { /* Return the current value of the binding, or undefined if the * binding does not exist. * * If inherited is true and the binding is a property binding that * does not exist on the object, any inherited value will be returned * instead. */ var part = this.part; if (this.object === null) { if (!$.utils.code.isIdentifier(part)) { throw new TypeError('invalid variable identifier'); } var evalGlobal = eval; return evalGlobal(part); } else if(part === $.Selector.PROTOTYPE) { return Object.getPrototypeOf(this.object); } else if(part === $.Selector.OWNER) { return Object.getOwnerOf(this.object); } if (inherited || Object.prototype.hasOwnProperty.call(this.object, part)) { return this.object[part]; } else { return undefined; } }; Object.setOwnerOf($.utils.Binding.prototype.get, $.physicals.Maximilian); $.utils.Binding.prototype.isOwner = function isOwner() { /* Returns true iff the binding is an bject owner binding. */ return this.part === $.Selector.OWNER; }; Object.setOwnerOf($.utils.Binding.prototype.isOwner, $.physicals.Maximilian); $.utils.Binding.prototype.isProp = function isProp() { /* Returns true iff the binding is an object property binding. */ return this.object !== null && typeof this.part === 'string'; }; Object.setOwnerOf($.utils.Binding.prototype.isProp, $.physicals.Maximilian); $.utils.Binding.prototype.isProto = function isProto() { /* Returns true iff the binding is an object prototype binding. */ return this.part === $.Selector.PROTOTYPE; }; Object.setOwnerOf($.utils.Binding.prototype.isProto, $.physicals.Maximilian); $.utils.Binding.prototype.isVar = function isVar() { /* Returns true iff the binding is a top-level variable binding. */ return this.object === null; }; Object.setOwnerOf($.utils.Binding.prototype.isVar, $.physicals.Maximilian); $.utils.Binding.prototype.exists = function exists() { /* Returns true iff the binding exists. */ var part = this.part; if (this.object === null) { if (!$.utils.code.isIdentifier(part)) { throw new TypeError('invalid variable identifier'); } var evalGlobal = eval; try { globalEval(varName); return true; } catch (e) { return false; } } else if(part === $.Selector.PROTOTYPE || part === $.Selector.OWNER) { return true; } return Object.prototype.hasOwnProperty.call(this.object, part); }; Object.setOwnerOf($.utils.Binding.prototype.exists, $.physicals.Maximilian); Object.setOwnerOf($.utils.Binding.prototype.exists.prototype, $.physicals.Maximilian); $.utils.Binding.from = function from(selector) { /* Create and return a Binding for the given selector - that is, * such that Binding.from(s).get() === s.toValue(). */ var part = selector[selector.length - 1]; if (selector.isVar()) { // Global variable; no parent object. return new this(null, part); } var parent = new $.Selector(selector); parent.pop(); var object = parent.toValue(); if (!$.utils.isObject(object)) { throw new TypeError(String(parent) + ' is not an object'); } return new this(object, part); }; Object.setOwnerOf($.utils.Binding.from, $.physicals.Maximilian); $.Selector.cache_ = (new 'Object.create')(null); $.Selector.sortByBadness.cache_ = (new 'Object.create')(null); ================================================ FILE: core/core_20_$.utils.html.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview HTML utilities for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.utils.html = {}; $.utils.html.escape = function escape(text) { // Escape text so that it is safe to print as HTML. return String(text).replace(/&/g, '&').replace(/"/g, '"') .replace(//g, '>'); }; Object.setOwnerOf($.utils.html.escape, $.physicals.Maximilian); $.utils.html.preserveWhitespace = function preserveWhitespace(text) { // Escape text so that it is safe and preserves whitespace formatting as HTML. // Runs of three spaces (' ') need to be escaped twice ('_ ', '__ '). return $.utils.html.escape(text) .replace(/\t/g, '\u00A0 \u00A0 ') .replace(/ /g, '\u00A0 ').replace(/ /g, '\u00A0 ') // Escape twice. .replace(/^ /gm, '\u00A0') .replace(/\n/g, '
'); }; Object.setOwnerOf($.utils.html.preserveWhitespace, $.physicals.Maximilian); ================================================ FILE: core/core_21_$.jssp.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview JavaScript Server Pages for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.jssp = {}; Object.setOwnerOf($.jssp, $.physicals.Neil); $.jssp.OutputBuffer = function OutputBuffer() { /* An OutputBuffer is a mock $.servers.http.Response, used wheen we * want a Jssp to produce a string rather than write to an HTTP * client. */ this.buffer_ = ''; }; Object.setOwnerOf($.jssp.OutputBuffer, $.physicals.Maximilian); $.jssp.OutputBuffer.prototype.write = function write(text) { this.buffer_ += String(text); }; Object.setOwnerOf($.jssp.OutputBuffer.prototype.write, $.physicals.Neil); $.jssp.OutputBuffer.prototype.toString = function toString() { return this.buffer_; }; Object.setOwnerOf($.jssp.OutputBuffer.prototype.toString, $.physicals.Neil); $.jssp.OutputBuffer.prototype.writeEscaped = function writeEscaped(text) { // Same as .write, but HTML-escape the text first. this.write($.utils.html.escape(text)); }; Object.setOwnerOf($.jssp.OutputBuffer.prototype.writeEscaped, $.physicals.Neil); Object.setOwnerOf($.jssp.OutputBuffer.prototype.writeEscaped.prototype, $.physicals.Neil); $.jssp.eval = function $_jssp_eval(obj, prop, opt_request, opt_response) { /* Compile and run a JavaScript Server Page. * * The specified property on the given object will, if it is a string, * be compiled to a function and then called. * * TODO: cache the compiled JSSP. Separate copy per owner? * * Arguments: * - obj: Object - an object containing a property which is a JSSP source * string, and which will be used as the value of 'this' when the * the resulting function is called. * - prop: string - name of the property on obj that contains the JSSP source. * - opt_request: any - a value to be passed as the first argument to the * compiled function. Most typically an instnace of $.servers.http.Request * or some kind of options object. * - opt_response: {write: function(string)} | undefined - an object to * accumulate generated output. Most typically an instance of * $.servers.http.Response. If omitted, a $.jssp.OutputBuffer will be * supplied, and the accumulated output returned by eval as a string. * * Returns: any - if opt_response was omitted, this will be the generated * string; otherwise, it will be the actual return value of the compiled * function (typically undefined). */ if (!$.utils.isObject(obj)) { throw new TypeError('first argument must be an object'); } else if (!(prop in obj)) { throw new RangeError('"' + prop + '" not on object.'); } var source = obj[prop]; if (typeof source !== 'string') { throw TypeError('source property "' + prop + '" must be a string'); } // Switch to the JSSP owner's permissions. The owner of the JSSP might // not be the object's owner if the property is inherited. var locationObj = $.utils.object.getPropertyLocation(obj, prop); setPerms(Object.getOwnerOf(locationObj)); var request = opt_request; var response = opt_response || new $.jssp.OutputBuffer(); // Compile source into a function. var code = this.compile_(source); code = '\n' + 'var this_ = this;\n' + 'function include(prop) {return $.jssp.eval(this_, prop, request, response);}\n' + code; var func; try { func = new Function('request, response', code); } catch (e) { suspend(); $.system.log('JSSP compilation error. ' + String(e) + '. Code was:\n' + code.split('\n') .map(function (line, lineNumber) { return String(lineNumber) + ': ' + line;}) .join('\n')); throw e; } // Create a .name for this function. var selector = $.Selector.for(locationObj); if (selector) { selector = new $.Selector(selector.concat(prop)); Object.defineProperty(func, 'name', {value: selector.toString(), configurable: true}); } var result = func.call(obj, request, response); return opt_response ? result : response.toString(); }; Object.setOwnerOf($.jssp.eval, $.physicals.Maximilian); Object.setOwnerOf($.jssp.eval.prototype, $.physicals.Neil); $.jssp.compile_ = function compile_(src) { /* Compile JavaScript Server Page srouce and return the translated source * if successful. It is left to the caller to pass the resulting source * code to the Function constructor. * * Arguments: * - src: string - the JSSP source code. * Returns: string - the JavaScript generated from src. */ if (typeof src !== 'string') { throw new TypeError('src must be a string'); } var tokens = src.trim().split(/(<%(?:--|:|=)?|(?:--)?%>)/); var code = [ '// DO NOT EDIT THIS CODE: AUTOMATICALLY GENERATED BY JSSP ' + compile_.lastModifiedTime + '.', ]; var STATES = { LITERAL: 0, STATEMENT: 1, EXPRESSION: 2, EXPRESSION_ESCAPED: 3, COMMENT: 4 }; var state = STATES.LITERAL; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (!token) { continue; // Empty string caused by splitting adjacent tags. } switch (state) { case STATES.LITERAL: if (token === '<%') { state = STATES.STATEMENT; } else if (token === '<%=') { state = STATES.EXPRESSION; } else if (token === '<%:') { state = STATES.EXPRESSION_ESCAPED; } else if (token === '<%--') { state = STATES.COMMENT; } else { code.push('response.write(' + JSON.stringify(token) + ');'); } break; case STATES.STATEMENT: if (token === '%>') { state = STATES.LITERAL; } else { code.push(token); } break; case STATES.EXPRESSION: case STATES.EXPRESSION_ESCAPED: if (token === '%>') { state = STATES.LITERAL; } else { token = token.trim(); if (token) { code.push(); if (state === STATES.EXPRESSION_ESCAPED) { code.push('response.writeEscaped(' + token + ');'); } else { code.push('response.write(' + token + ');'); } } } break; case STATES.COMMENT: if (token === '--%>') { state = STATES.LITERAL; } break; } } if (state !== STATES.LITERAL) { throw new SyntaxError('unclosed JSSP tag'); } return code.join('\n') + '\n'; }; Object.setOwnerOf($.jssp.compile_, $.physicals.Neil); Object.setOwnerOf($.jssp.compile_.prototype, $.physicals.Maximilian); ================================================ FILE: core/core_22_$.connection.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Connection object for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.connection = {}; $.connection.onConnect = function onConnect() { this.connectTime = Date.now(); this.user = null; this.buffer = ''; this.connected = true; }; Object.setOwnerOf($.connection.onConnect, $.physicals.Maximilian); Object.setOwnerOf($.connection.onConnect.prototype, $.physicals.Maximilian); $.connection.onReceive = function onReceive(text) { this.buffer += text.replace(/\r/g, ''); var lf; while ((lf = this.buffer.indexOf('\n')) !== -1) { var line = this.buffer.substring(0, lf); this.buffer = this.buffer.substring(lf + 1); this.onReceiveLine(line); } }; Object.setOwnerOf($.connection.onReceive, $.physicals.Maximilian); $.connection.onReceiveLine = function onReceiveLine(text) { // Override this on child classes. }; Object.setOwnerOf($.connection.onReceiveLine, $.physicals.Maximilian); $.connection.onEnd = function onEnd() { this.connected = false; this.disconnectTime = Date.now(); this.close(); }; Object.setOwnerOf($.connection.onEnd, $.physicals.Maximilian); $.connection.write = function write(text) { $.system.connectionWrite(this, text); }; Object.setOwnerOf($.connection.write, $.physicals.Maximilian); $.connection.close = function close() { $.system.connectionClose(this); }; Object.setOwnerOf($.connection.close, $.physicals.Maximilian); $.connection.onError = function onError(error) { // TODO: add check for error that occurs when relistening // fails when restarting server from checkpoint. if (error.message === 'write after end' || error.message === 'This socket has been ended by the other party') { this.connected = false; } }; Object.setOwnerOf($.connection.onError, $.physicals.Maximilian); ================================================ FILE: core/core_23_$.servers.http.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Webserver for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.utils.url = {}; Object.setOwnerOf($.utils.url, $.physicals.Maximilian); $.utils.url.regexps = {}; $.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.'; $.utils.url.regexps._generate = function _generate() { /* Generate some RegExps that match various parts of URLs. The * intention is that these regular expressions conform to the * grammar given in RFC 3986, "Uniform Resource Identifier (URI): * Generic Syntax" (https://tools.ietf.org/html/rfc3986). * * TODO: add tests for generated RegExps. */ //////////////////////////////////////////////////////////////////// // IPv4 Addresses. // Based on https://stackoverflow.com/a/14453696/4969945 // Matches an octet, optionally with leading zeros. var octet = '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})'; // Matches an octet without no leading zeros. var octetStrict = '(?:25[0-5]|(?:2[0-4]|1[0-9]|[1-9])?[0-9])'; // Globally matches IPv4 addresses, optionally with leading zeros. this.ipv4Address = new RegExp(octet + '(?:\\.' + octet + '){3}', 'g'); // Globally matches IPv4 addresses with no leading zeros. this.ipv4AddressStrict = new RegExp(octetStrict + '(?:\\.' + octetStrict + '){3}', 'g'); //////////////////////////////////////////////////////////////////// // IPv6 Addresses. // Based on https://stackoverflow.com/a/17871737/4969945 but modified // to reduce ambiguity match more greedily when unanchored. // Matches a 32-bit hex value as it can appear in an IPv6 address. var word = '[0-9a-fA-F]{1,4}'; // Matches an IPv4 address as it can appear in an IPv6 address. var ipv4 = this.ipv4AddressStrict.source; // Globally matches a valid IPv6 address. this.ipv6Address = new RegExp( '(?:' + '[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) '(?:' + word + ':){1,4}:' + ipv4 + '|' + // 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 (IPv4-Embedded IPv6 Address) '(?:' + word + ':){7}' + word + '|' + // 1:2:3:4:5:6:7:8 '(?:' + word + ':){6}(?::' + word + '){1,1}|' + // 1:2:3:4:5:6::8 ... 1:2:3:4:5:6::8 '(?:' + word + ':){5}(?::' + word + '){1,2}|' + // 1:2:3:4:5::8 ... 1:2:3:4:5::7:8 '(?:' + word + ':){4}(?::' + word + '){1,3}|' + // 1:2:3:4::8 ... 1:2:3:4::6:7:8 '(?:' + word + ':){3}(?::' + word + '){1,4}|' + // 1:2:3::8 ... 1:2:3::5:6:7:8 '(?:' + word + ':){2}(?::' + word + '){1,5}|' + // 1:2::8 ... 1:2::4:5:6:7:8 '(?:' + word + ':){1}(?::' + word + '){1,6}|' + // 1::8 ... 1::3:4:5:6:7:8 '(?:' + word + ':){1,7}:|' + // 1:: ... 1:2:3:4:5:6:7:: '::(?:[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) ':(?::' + word + '){1,7}|' + // ::8 ... ::2:3:4:5:6:7:8 '::' + // :: ')', 'g'); //////////////////////////////////////////////////////////////////// // DNS Domain Names. // Matches a label (per RFC 952, updated by RFC 1123 to allow a // it to begin with a digit), limited to 63 charcters (per RFC 1035). var label = '[a-zA-Z0-9][a-zA-Z0-9-]{0,62}'; // Globally matches a legal (but not necessary valid!) DNS name. // See also https://stackoverflow.com/q/106179/4969945 . // BUG: does not limit length of name to ca. 253 characters (see // https://devblogs.microsoft.com/oldnewthing/20120412-00/?p=7873 // for gory details). this.dnsAddress = new RegExp(label + '(?:\\.' + label + ')*', 'g'); //////////////////////////////////////////////////////////////////// // Authority section // Globally matches a valid IP address (v4 or v6). this.ipAddress = new RegExp( this.ipv4Address.source + '|\\[' + this.ipv6Address.source + '\\]', 'g'); // Globally matches a valid URL authority section (e.g. domain name // and port); this is (not coincidentally) also the same as a valid // HTTP Host: header value. // // The RegExp includes capture groups for an IP address [1] *or* a // DNS address [2], and (optionally) a port number [3]. this.authority = new RegExp( '(?:(' + this.ipAddress.source + ')|' + '(' + this.dnsAddress.source + '))' + '(?::([0-9]+))?', 'g'); // Optional port number. //////////////////////////////////////////////////////////////////// // Exact forms of the above. These do not get the global flag. var keys = ['ipv4Address', 'ipv4AddressStrict', 'ipv6Address', 'dnsAddress', 'ipAddress', 'authority']; for (var key, i = 0; (key = keys[i]); i++) { this[key + 'Exact'] = new RegExp('^' + this[key].source + '$'); } }; Object.setOwnerOf($.utils.url.regexps._generate.prototype, $.physicals.Maximilian); $.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; $.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; $.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; $.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; $.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; $.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; $.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}$/; $.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}$/; $.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}|::)$/; $.utils.url.regexps.dnsAddressExact = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,62}(?:\.[a-zA-Z0-9][a-zA-Z0-9-]{0,62})*$/; $.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}|::)\]$/; $.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]+))?$/; $.servers.http = {}; $.servers.http.STATUS_CODES = (new 'Object.create')(null); $.servers.http.STATUS_CODES[100] = 'Continue'; $.servers.http.STATUS_CODES[101] = 'Switching Protocols'; $.servers.http.STATUS_CODES[102] = 'Processing'; $.servers.http.STATUS_CODES[200] = 'OK'; $.servers.http.STATUS_CODES[201] = 'Created'; $.servers.http.STATUS_CODES[202] = 'Accepted'; $.servers.http.STATUS_CODES[203] = 'Non-Authoritative Information'; $.servers.http.STATUS_CODES[204] = 'No Content'; $.servers.http.STATUS_CODES[205] = 'Reset Content'; $.servers.http.STATUS_CODES[206] = 'Partial Content'; $.servers.http.STATUS_CODES[207] = 'Multi-Status'; $.servers.http.STATUS_CODES[208] = 'Already Reported'; $.servers.http.STATUS_CODES[226] = 'IM Used'; $.servers.http.STATUS_CODES[300] = 'Multiple Choices'; $.servers.http.STATUS_CODES[301] = 'Moved Permanently'; $.servers.http.STATUS_CODES[302] = 'Found'; $.servers.http.STATUS_CODES[303] = 'See Other'; $.servers.http.STATUS_CODES[304] = 'Not Modified'; $.servers.http.STATUS_CODES[305] = 'Use Proxy'; $.servers.http.STATUS_CODES[306] = 'Switch Proxy'; $.servers.http.STATUS_CODES[307] = 'Temporary Redirect'; $.servers.http.STATUS_CODES[308] = 'Permanent Redirect'; $.servers.http.STATUS_CODES[400] = 'Bad Request'; $.servers.http.STATUS_CODES[401] = 'Unauthorized'; $.servers.http.STATUS_CODES[402] = 'Payment Required'; $.servers.http.STATUS_CODES[403] = 'Forbidden'; $.servers.http.STATUS_CODES[404] = 'Not Found'; $.servers.http.STATUS_CODES[405] = 'Method Not Allowed'; $.servers.http.STATUS_CODES[406] = 'Not Acceptable'; $.servers.http.STATUS_CODES[407] = 'Proxy Authentication Required'; $.servers.http.STATUS_CODES[408] = 'Request Timeout'; $.servers.http.STATUS_CODES[409] = 'Conflict'; $.servers.http.STATUS_CODES[410] = 'Gone'; $.servers.http.STATUS_CODES[411] = 'Length Required'; $.servers.http.STATUS_CODES[412] = 'Precondition Failed'; $.servers.http.STATUS_CODES[413] = 'Payload Too Large'; $.servers.http.STATUS_CODES[414] = 'URI Too Long'; $.servers.http.STATUS_CODES[415] = 'Unsupported Media Type'; $.servers.http.STATUS_CODES[416] = 'Range Not Satisfiable'; $.servers.http.STATUS_CODES[417] = 'Expectation Failed'; $.servers.http.STATUS_CODES[418] = "I'm a teapot"; $.servers.http.STATUS_CODES[421] = 'Misdirected Request'; $.servers.http.STATUS_CODES[422] = 'Unprocessable Entity'; $.servers.http.STATUS_CODES[423] = 'Locked'; $.servers.http.STATUS_CODES[424] = 'Failed Dependency'; $.servers.http.STATUS_CODES[426] = 'Upgrade Required'; $.servers.http.STATUS_CODES[428] = 'Precondition Required'; $.servers.http.STATUS_CODES[429] = 'Too Many Requests'; $.servers.http.STATUS_CODES[431] = 'Request Header Fields Too Large'; $.servers.http.STATUS_CODES[451] = 'Unavailable For Legal Reasons'; $.servers.http.STATUS_CODES[500] = 'Internal Server Error'; $.servers.http.STATUS_CODES[501] = 'Not Implemented'; $.servers.http.STATUS_CODES[502] = 'Bad Gateway'; $.servers.http.STATUS_CODES[503] = 'Service Unavailable'; $.servers.http.STATUS_CODES[504] = 'Gateway Timeout'; $.servers.http.STATUS_CODES[505] = 'HTTP Version Not Supported'; $.servers.http.STATUS_CODES[506] = 'Variant Also Negotiates'; $.servers.http.STATUS_CODES[507] = 'Insufficient Storage'; $.servers.http.STATUS_CODES[508] = 'Loop Detected'; $.servers.http.STATUS_CODES[510] = 'Not Extended'; $.servers.http.STATUS_CODES[511] = 'Network Authentication Required'; $.servers.http.connection = (new 'Object.create')($.connection); $.servers.http.connection.onConnect = function onConnect() { $.connection.onConnect.apply(this, arguments); this.timeout = setTimeout(this.close.bind(this), 60 * 1000); this.request = new $.servers.http.Request(); this.response = new $.servers.http.Response(this); }; Object.setOwnerOf($.servers.http.connection.onConnect, $.physicals.Maximilian); $.servers.http.connection.onReceive = function onReceive(data) { this.buffer += data; var lf; // Start in line-delimited mode, parsing HTTP headers. while ((lf = this.buffer.indexOf('\n')) !== -1) { try { this.onReceiveChunk(this.buffer.substring(0, lf + 1)); } finally { this.buffer = this.buffer.substring(lf + 1); } } if (this.request.state_ === 'body') { // Waiting for POST data, not line-delimited. this.onReceiveChunk(this.buffer); this.buffer = ''; } }; Object.setOwnerOf($.servers.http.connection.onReceive, $.physicals.Neil); $.servers.http.connection.onReceiveChunk = function onReceiveChunk(chunk) { if (this.request.parse(chunk)) { $.servers.http.onRequest(this); } // Otherwise wait for more lines to arrive. }; Object.setOwnerOf($.servers.http.connection.onReceiveChunk, $.physicals.Maximilian); $.servers.http.connection.onEnd = function onEnd() { clearTimeout(this.timeout); $.connection.onEnd.apply(this, arguments); }; Object.setOwnerOf($.servers.http.connection.onEnd, $.physicals.Neil); $.servers.http.Request = function Request() { this.headers = Object.create(null); this.headers.cookie = Object.create(null); this.parameters = Object.create(null); // One of 'invalid', 'request', 'headers', 'body', 'done'. this.state_ = 'request'; }; Object.setOwnerOf($.servers.http.Request, $.physicals.Maximilian); $.servers.http.Request.prototype.parse = function parse(line) { // Returns true if parsing is complete, false if more lines are needed. if (this.state_ === 'request') { // Match "GET /images/logo.png HTTP/1.1" line = line.trim(); var m = line.match(/^(GET|POST) +(\S+)/); if (!m) { $.system.log('Unrecognized WWW request line:', line); this.state_ = 'invalid'; return true; } this.method = m[1]; this.url = m[2]; this.parseUrl_(this.url); this.state_ = 'headers'; return false; } if (this.state_ === 'headers') { line = line.trim(); if (!line) { // Done parsing headers. if (this.method === 'POST') { this.state_ = 'body'; this.data = ''; return false; } else { this.parseParameters_(this.query); this.state_ = 'done'; this.data = undefined; return true; } } var m = line.match(/^([-\w]+): +(.+)$/); if (!m) { $.system.log('Unrecognized WWW header line:', line); return false; } var name = m[1].toLowerCase(); var value = m[2]; var existing = this.headers[name]; if (name === 'cookie') { // Cookies are processed and presented as: request.headers.cookie.foo var cookies = value.split(/\s*;\s*/); for (var i = 0; i < cookies.length; i++) { var eqIndex = cookies[i].indexOf('='); if (eqIndex !== -1) { var cookieName = cookies[i].substring(0, eqIndex); var cookieValue = cookies[i].substring(eqIndex + 1); if (cookieName === 'ID') { // Special-case the 'ID' cookie for user login. // Do not expose this ID string to anyone. this.user = $.userDatabase.get(cookieValue); } else { // Regular cookie. existing[cookieName] = cookieValue; } } } value = existing; } else if (name in this.headers) { if ($.servers.http.IncomingMessage.discardDuplicates.includes(name)) { // Discard this duplicate. value = existing; } else { // Append this header onto previously defined header. value = existing + ', ' + value; } } this.headers[name] = value; return false; } if (this.state_ === 'body') { // POST data. this.data += line; if (this.data.length >= this.headers['content-length']) { this.parseParameters_(this.data); this.state_ = 'done'; return true; } return false; } // Invalid state? Extra lines? Ignore. return true; }; Object.setOwnerOf($.servers.http.Request.prototype.parse, $.physicals.Neil); $.servers.http.Request.prototype.parseUrl_ = function parseUrl_(url) { /* Parse a URL and set this.path and this.query as appropriate: * * E.g. given url = '/bar/baz?data', set: * - this.path = '/bar/baz' * - this.query = 'data' * * Arguments: * - url: string - the URL to parse. * * TODO(cpcallen): add check for leading "/"? */ var qIndex = url.indexOf('?'); if (qIndex === -1) { this.path = url; } else { this.path = url.substring(0, qIndex); this.query = url.substring(qIndex + 1); } }; Object.setOwnerOf($.servers.http.Request.prototype.parseUrl_, $.physicals.Maximilian); $.servers.http.Request.prototype.parseParameters_ = function parseParameters_(data) { if (!data) { return; } var vars = data.split('&'); var name, value; for (var i = 0; i < vars.length; i++) { var eqIndex = vars[i].indexOf('='); if (eqIndex === -1) { name = vars[i]; value = true; } else { name = vars[i].substring(0, eqIndex); value = vars[i].substring(eqIndex + 1); value = decodeURIComponent(value.replace(/\+/g, ' ')); } if (name in this.parameters) { // ?foo=1&foo=2&foo=3 var array = this.parameters[name]; if (!Array.isArray(array)) { array = [array]; } array.push(value); value = array; } this.parameters[name] = value; } }; Object.setOwnerOf($.servers.http.Request.prototype.parseParameters_, $.physicals.Neil); $.servers.http.Request.prototype.fromSameOrigin = function fromSameOrigin() { /* Determines if the previous page and the requested page are from the same * origin. Normally this means that they are from the same subdomain. * However, if pathToSubdomain is enabled then the first directory name * is used for comparison. * * Return: boolean | undefined - true if from the same origin, false if * from different origins, and undefined if missing headers prevent a * firm conclusion one way or the other. * * Callers should choose whether to fail-safe or fail-deadly when the * user's proxy strips the referer header, resulting in undefined. * * BUG: if referer was for subdomain routed via a root Host with * .pathToSubdomain enabled, but .origin is for the root domain, * fromSameOrigin will return true. This is not intended and possibly * insecure - but probably mostly harmless: if .pathToSubdomain is * enabled subdomains are not really secure against each other anyway. */ var referer = this.headers.referer; // https://foo.example.codecity.world/bar if (!referer || !this.info) { // Missing headers. Not enough information to know. return undefined; } var origin = this.info.origin; // foo.example.codecity.world var regexp = new RegExp('^https?://' + $.utils.regexp.escape(origin) + '/'); return regexp.test(referer); }; Object.setOwnerOf($.servers.http.Request.prototype.fromSameOrigin, $.physicals.Maximilian); $.servers.http.Request.prototype.hostUrl = function hostUrl(varArgs) { /* Return the base URL for the host that handled this Request, or * a subdomain (omitting scheme). This is derived from .headers.host, * but with some extra magic: * * - Absent any argument, it will be the URL which routes to the root * Host object serving this Request - e.g., //example.codecity.world/ * The "root" host is ordinarily just first of $.servers.http.hosts[] * to accept the request (as opposed to one of its .subdomains). * - If an argument is supplied, the returned URL will instead be for * the named subdomain. * - Multiple arguments can be supplied if there are nested subdomains. * * E.g.: * request.hostUrl() => '//example.codecity.world/' * request.hostUrl('code') => '//code.example.codecity.world/' * request.hostUrl('foo', 'bar') => '//foo.bar.example.codecity.world/' * * If .pathToSubdomain is enabled on one or more Host object(s): * request.hostUrl('code') => '//example.codecity.world/code/' * request.hostUrl('foo', 'bar') => '//example.codecity.world/foo/bar/' * or: '//bar.example.codecity.world/foo/' * * Barring bugs, the returned URL should always end with a '/'. * * See also $.servers.http.Host.prototype.url for cases where you need * to generate a host URL without an incoming Request to use as reference. * * Arguments: * - subdomain: string - a string denoting a subdomain of interest. * Multiple arguments are allowed. RangeError is thrown if no such * subdomain exists. * Returns: string - the URL for the desired domain/subdomain. */ // No routing information is available? Fallback to $hosts.root.url(). if (!this.info) { var rootHost = $.hosts.root; return rootHost.url.apply(rootHost, arguments); } // Walk the tree of Hosts rooted at the root Host via which this // Request was served. var host = this.info.rootHost; var authority = this.info.rootAuthority; // Did nginx request pathToSubdomain, because it knows that it is not // configured for real wildcard subdomains? (N.B.: header uses the // RFC 8941 convention of "?1" for true, "?0" for false.) var pathToSubdomainHeader = (this.headers['codecity-pathtosubdomain'] === '?1'); for (var subdomain, i = 0; (subdomain = arguments[i]); i++) { authority = host.urlForSubdomain(authority, subdomain, pathToSubdomainHeader); host = host.subdomains[subdomain]; } return '//' + authority + '/'; }; Object.setOwnerOf($.servers.http.Request.prototype.hostUrl, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Request.prototype.hostUrl.prototype, $.physicals.Maximilian); $.servers.http.Request.discardDuplicates = []; $.servers.http.Request.discardDuplicates[0] = 'authorization'; $.servers.http.Request.discardDuplicates[1] = 'content-length'; $.servers.http.Request.discardDuplicates[2] = 'content-type'; $.servers.http.Request.discardDuplicates[3] = 'from'; $.servers.http.Request.discardDuplicates[4] = 'host'; $.servers.http.Request.discardDuplicates[5] = 'if-modified-since'; $.servers.http.Request.discardDuplicates[6] = 'if-unmodified-since'; $.servers.http.Request.discardDuplicates[7] = 'max-forwards'; $.servers.http.Request.discardDuplicates[8] = 'proxy-authorization'; $.servers.http.Request.discardDuplicates[9] = 'referer'; $.servers.http.Request.discardDuplicates[10] = 'user-agent'; $.servers.http.Response = function Response(connection) { this.headersSent = false; this.statusCode = 200; this.headers_ = Object.create(Response.defaultHeaders); this.cookies = []; this.setHeader('content-type', 'text/html; charset=utf-8'); this.connection_ = connection; }; Object.setOwnerOf($.servers.http.Response, $.physicals.Maximilian); $.servers.http.Response.prototype.setHeader = function setHeader(name, value) { if (this.headersSent) { throw new Error('header already sent'); } value = String(value).trim(); if (value.includes('\n') || value.includes('\r')) { throw new RangeError('invalid header value'); } // Normalize all header names as lowercase. name = String(name).toLowerCase(name); if (name === 'set-cookie') { if (/^\s*ID\s*=/.test(value)) { throw new PermissionError('not allowed to set ID cookie'); } this.cookies.push(value); } else { var existing = Object.getOwnPropertyDescriptor(this.headers_, name); if (existing) { // Header already set for this Response specifically. if ($.servers.http.Response.discardDuplicates.includes(name)) { // Overwrite existing value. } else { // Append this header onto previously defined header. value = existing.value + ', ' + value; } } this.headers_[name] = value; } }; Object.setOwnerOf($.servers.http.Response.prototype.setHeader, $.physicals.Maximilian); $.servers.http.Response.prototype.writeHead = function writeHead() { if (this.headersSent) { throw new Error('Header already sent.'); } this.headersSent = true; var statusMessage = $.servers.http.STATUS_CODES[this.statusCode] || 'Unknown'; this.connection_.write('HTTP/1.0 ' + this.statusCode + ' ' + statusMessage + '\r\n'); for (var name in this.headers_) { // Print all header names as Title-Case. var title = name.replace(/\w+/g, $.utils.string.capitalize); this.connection_.write(title + ': ' + this.headers_[name] + '\r\n'); } for (var i = 0; i < this.cookies.length; i++) { // Print all cookies. this.connection_.write('Set-Cookie: ' + this.cookies[i] + '\r\n'); } this.connection_.write('\r\n'); }; Object.setOwnerOf($.servers.http.Response.prototype.writeHead, $.physicals.Maximilian); $.servers.http.Response.prototype.setStatus = function setStatus(statusCode) { /* Set the status code for this Response. * Must be called before .writeHead(). * * - statusCode: number - the HTTP status code to return. */ if (!(statusCode in $.servers.http.STATUS_CODES)) { throw new RangeError('invalid HTTP status code ' + statusCode); } if (this.headersSent) { throw new Error('header already sent.'); } this.statusCode = statusCode; }; Object.setOwnerOf($.servers.http.Response.prototype.setStatus, $.physicals.Maximilian); $.servers.http.Response.prototype.write = function write(text) { text = String(text); if (text !== '') { if (!this.headersSent) { this.writeHead(); } this.connection_.write(text); } }; Object.setOwnerOf($.servers.http.Response.prototype.write, $.physicals.Neil); $.servers.http.Response.prototype.clearIdCookie = function clearIdCookie() { // TODO: Security check goes here. Should be only callable by logout. if (this.headersSent) { throw new Error('Header already sent'); } var request = this.connection_.request; // Guess cookie domain. var rootHost = (request.info && request.info.rootAuthority) || // Request rootAuthority. request.headers.host || // Actual Host: header value for the request. $.hosts.root.hostname; // Configuerd hostname var domain = rootHost ? ' Domain=' + rootHost.replace(/:\d+$/, '') : ''; // Remove port number. var value = 'ID=; HttpOnly;' + domain + '; Path=/; Max-Age=0;'; this.cookies.push(value); }; Object.setOwnerOf($.servers.http.Response.prototype.clearIdCookie, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Response.prototype.clearIdCookie.prototype, $.physicals.Neil); $.servers.http.Response.prototype.sendRedirect = function sendRedirect(url, statusCode) { /* Write a redirect as the response. * * Must be called before writeHeader has been called. * * Arguments: * - url: string - the destination URL for the redirect. * - statusCode?: number - optional HTTP status code (default: 303 See Other). */ if (!statusCode) statusCode = 303; this.setStatus(statusCode); this.setHeader('Location', url); this.writeHead(); }; Object.setOwnerOf($.servers.http.Response.prototype.sendRedirect, $.physicals.Neil); Object.setOwnerOf($.servers.http.Response.prototype.sendRedirect.prototype, $.physicals.Maximilian); $.servers.http.Response.prototype.sendError = function sendError(statusCode, message) { /* Send an error status and page as the response. * * Must be called before writeHeader has been called. Writes a complete HTML * document to the connection, but doesn't close the connection. * * Arguments: * - statusCode: number - an HTTP status code. * - message?: string | Error - optional status message or Error instance. */ this.setStatus(statusCode); if (message instanceof Error) { this.errorMessage_ = $.utils.html.escape(String(message)) + '
' + $.utils.html.escape(message.stack) + '
'; } else if (message !== undefined) { this.errorMessage_ = $.utils.html.escape(message); } else { this.errorMessage_ = ''; } $.jssp.eval(this, 'sendErrorJssp', this.connection_.request, this); }; Object.setOwnerOf($.servers.http.Response.prototype.sendError, $.physicals.Neil); Object.setOwnerOf($.servers.http.Response.prototype.sendError.prototype, $.physicals.Maximilian); $.servers.http.Response.prototype.sendErrorJssp = '<% try {var staticUrl = request.hostUrl(\'static\');} catch(e) {staticUrl = \'\';} %>\n\n\n <%= response.statusCode %> - Code City\n \n \n \n\n\n

\n \n <%= response.statusCode %> <%= $.servers.http.STATUS_CODES[response.statusCode] %>\n

\n
Host: <%: request.headers.host %>\n<%= request.method %> <%: request.url %>
\n <%= response.errorMessage_ %>\n\n'; $.servers.http.Response.prototype.writeEscaped = $.jssp.OutputBuffer.prototype.writeEscaped; $.servers.http.Response.discardDuplicates = []; $.servers.http.Response.discardDuplicates[0] = 'age'; $.servers.http.Response.discardDuplicates[1] = 'content-length'; $.servers.http.Response.discardDuplicates[2] = 'content-type'; $.servers.http.Response.discardDuplicates[3] = 'etag'; $.servers.http.Response.discardDuplicates[4] = 'expires'; $.servers.http.Response.discardDuplicates[5] = 'last-modified'; $.servers.http.Response.discardDuplicates[6] = 'location'; $.servers.http.Response.discardDuplicates[7] = 'retry-after'; $.servers.http.Response.defaultHeaders = (new 'Object.create')(null); $.servers.http.Response.defaultHeaders['cache-control'] = 'no-store'; $.servers.http.Response.defaultHeaders.server = 'CodeCity/0.0 ($.servers.http)'; $.servers.http.Host = function Host() { /* A Host object represents a domain or subdomain served by the * web server. It is expected that most Host instances will be * the values of properties of $.hosts. * * Methods on Host.prototype (see individual methodd documentation * for details): * * - .addSubdomain() - add a new subdomain to .subdomains. * - .handle() - try to have this host handle an incoming request. * - .url() - return the URL for this host. * - .urlForSubdomain() - a helper method for .url(). * * Instance properties of Host objects (by default these all * inherit their default values from Host.prototype): * * - access: string - Access control switch. It has the following * possible values: * * - 'public': The host will by default serve pages to any client * unless the handler object has .wwwAccess === 'private', in * which case it will only be served to logged-in users. * Unauthenticated clients will get 403 forbidden and be * directed to login. * * - 'private': The host will by default only serve pages to * logged-in users unless the hander object has .wwwAccess === * 'public'. * * - 'hidden': The host will only serve pages to logged-in users; * any unauthenticated client will be declined (by .handle * returning false) which will normally result in them recieving * a 400 Unknown Host error. * * - hostname: string | undefined - the canonical hostname for * this Host object. Should include the port number, if non-default. * * If .hostRegExp (see below) is undefined, .hostname will be used to * decide which Requests to handle: * * - This host object will serve requests whose Host: header exactly * matches .hostname itself. * - It will pass requests whose Host: header ends with .hostname to * the corresponding subdomain, if it exists. * * E.g., if .hostname = 'bar.baz', this host will serve requests for * bar.baz and will pass requests for foo.bar.baz to .subdomains.foo * but will reject requests for bar.baz:8080. * * If both .hostname and .hostRegExp are undefined, all requests will * be served by this host or automagically passed along to a suitable * subdomain. * * - hostRegExp: RegExp | undefined - a RegExp matching Host: header * values this host should respond to. If undefined (the default), * this .hostname (see above) will be used instead. * * Note that when the Host is deciding whether to serve a Request * itself, this regexp will be treated as if it begins with /^/, * while when the Host is trying to determine if it should be passed * off to a subdomain it will treat it as if it begins with /(?<=\.)/ * (despite ES5.1 not supporting such look-behind assertions). * * This means that .hostRegExp = /bar.baz$/ will cause this Host object * to serve 'bar.baz' and try to pass 'foo.bar.baz' to .subdomains.foo, * but will always reject 'foobar.baz'. Anchoring with /^/ will * prevent subdomain matching, so don't do that if you don't mean to! * * It's recommended that .hostRegExp be anchored with /$/, but note * that if you want to serve pages on a non-standard ports you must * match the port as well - e.g.: /example\.codecity\.\w+(?::\d+)$/ * will match example.codecity. with or without a port number. * * - pathToSubdomain: boolean | undefined - enable (or disable) mapping * the first element (directory) of request paths to a subdomain. * * If set to undefined, the CodeCity-pathToSubdomain header will be * used to determine decide whether to do this mapping on a * per-request basis (but normally this header will be configured * staticaly in the nginx reverse-proxy configuration). * * The CodeCity-pathToSubdomain header will be interpreted according * to the RFC 8941 Structure Field Values convention, with '?1' * meaning true and '?0' meaning false. Any other value will be * treated as false. * * - subdomains: Object | null - a null-prototype * object mapping subdomain names to their respective Host objects, * or just null if there are no subdomains. Use .addSubdomain to * add entries to this mapping. (Default: null.) */ }; Object.setOwnerOf($.servers.http.Host, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype, $.physicals.Maximilian); $.servers.http.Host.prototype.handle = function handle(request, response, info) { /* Attempt to handle an http(s) request. First tries to see if the * request can be served by the Host object of a direct subdomain * of this Host, then tries to handle itself, then, if * this.pseudoSubdomains is enabled, attempts to route the request * to a subdomain Host based on the first component of the path. * * Arguments: * - request: $.servers.http.Request - the incoming request to handle. * - response: $.servers.http.Response - the response to write to. * - info: Object | undefined - some information used by recursive calls to * this function. * Returns: boolean - true iff request was for this host. */ if (!info) { // Extact detailed routing info from request. var hostHeader = request.headers.host; info = { origin: hostHeader, // For Request.prototype.fromSameOrigin. path: request.path, rootHost: this, }; // The authorityExact RegExp gives submatches [ipAddress, dnsAddress, // port]. Only one of the addresses capture groups will match. var m = $.utils.url.regexps.authorityExact.exec(hostHeader); if (!m) { // Invalid Host header. response.sendError(400, 'Invalid Host header.'); return true; // We don't want it, but no one else should either. } else if (m[1]) { // It's an IP address. No (real) subdomains possible. info.rootAuthority = info.authority = hostHeader; } else if (this.hostRegExp || this.hostname) { var hostRegExp = this.hostRegExp ? this.hostRegExp : new RegExp($.utils.regexp.escape(this.hostname) + '$') // We have a .hostname or .hostRegExp, and can work out if there is a // subdomain prefixed to request.headers.host from that. m = hostRegExp.exec(hostHeader); if (!m) return false; // Did not match. Not for us. // Apply a check equivalent to a /(?<=^|\.)/ look-behind assertion. if (m.index > 0) { if (hostHeader[m.index - 1] !== '.') return false; // Lookbehind failed. // Record subdomain(s) that need to be matched. info.subdomains = hostHeader.slice(0, m.index - 1).split('.'); } info.rootAuthority = info.authority = hostHeader.slice(m.index); } else { // Try to guess where the subdomain(s) end and the root hostname begins. // To deal correclty with cases like x.x.y.z and x.y.x.y.z, be // pessimistic and assume they're all subdomains to start with. var potentialSubdomains = hostHeader.split('.'); info.rootAuthority = info.authority = potentialSubdomains.pop(); // TLD can't be subdomain! for (var i = potentialSubdomains.length; i >= 0; i--) { info.subdomains = potentialSubdomains.slice(0, i); var r = this.handle(request, response, info); if (r) return r; info.rootAuthority = info.authority = potentialSubdomains[i - 1] + '.' + info.authority; } return false; } } // Is this request for us or a subdomain of us? if (!this.matchHostname_(info.authority)) return false; // This request is for us or a subdomain. // Do we need to try to find a subdomain for this request? if (info.subdomains && info.subdomains.length) { var subdomain = info.subdomains.pop(); if (!(subdomain in this.subdomains)) return false; info.authority = subdomain + '.' + info.authority; return this.subdomains[subdomain].handle(request, response, info); } // No, it's for us. Should we hide from unauthenticated clients? if (this.access === 'hidden' && !($.user.isPrototypeOf(request.user))) { return false; } // No. Serve reqeust. this.route_(request, response, info); return true; }; Object.setOwnerOf($.servers.http.Host.prototype.handle, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype.handle.prototype, $.physicals.Maximilian); $.servers.http.Host.prototype.route_ = function route_(request, response, info) { /* Attempt to route an http(s) request for this host to the correct * handler. If a handler is found, call it. * * If no handler is found, but this host has .pathToSubdomain set, * or .pathToSubdomain is undefined but request contains a * CodeCity-pathToSubdomain header with value '?1' (true, in RFC 8941 * Structured Field Value notation) then attempt to map the first * element (directory name) of info.path to one of .subdomains and, * if successful, call the corresponding subdomain host's .handle * method. * * Otherwise generate a 404 error. * * Arguments: * - request: $.servers.http.Request - the incoming request to handle. * - response: $.servers.http.Response - the response to write to. * - info: Object - some additional information generated by * Host.prototype.handle (see that method for details). */ var path = info.path; if (typeof path !== 'string' || path[0] !== '/') { response.sendError(400, 'Invalid path "' + path + '"'); } else if (path in this) { // Get handler object. var obj = this[path]; if (!$.utils.isObject(obj)) { response.sendError(500, "Handler is not an object."); return; } // Check access control. if (!($.user.isPrototypeOf(request.user)) && // Not logged in. ((this.access !== 'public' && obj.wwwAccess !== 'public') || obj.wwwAccess === 'private')) { response.sendError(403); return; } // Record routing info on Request object and serve page. request.info = info; if (typeof obj.www === 'string') { $.jssp.eval(obj, 'www', request, response); } else if (typeof obj.www === 'function') { obj.www(request, response); } else { response.sendError(500, "Handler .www is neither a function nor a JSSP."); } } else if (this.subdomains && (this.pathToSubdomain || (this.pathToSubdomain === undefined && request.headers['codecity-pathtosubdomain'] === '?1'))) { // Try to route to a subdomain based on top-level directory. // E.g. https://example.codecity.world/foo/bar -> foo var m = path.match(/^\/([-A-Za-z0-9]+)(\/.*)?$/); var subdomain = ''; // Empty string gives good 404 message if .match fails. if (m && (subdomain = m[1]) in this.subdomains) { // Subdomain matched. Do we need to redirect to add a trailing '/'? if (!m[2]) { response.sendRedirect(subdomain + '/', 308); return; } // Route to the subdomain. Modify info.path and info.origin as appropriate info.path = m[2]; info.origin += '/' + subdomain; if (!this.subdomains[subdomain].handle(request, response, info)) { response.sendError(500, 'Host for pseudo-subdomain /' + subdomain + '/ rejected request.'); return; } } else { response.sendError(404, 'Not Found (and /' + subdomain + '/ does not map to a subdomain).'); } } else { response.sendError(404); } }; Object.setOwnerOf($.servers.http.Host.prototype.route_, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype.route_.prototype, $.physicals.Maximilian); $.servers.http.Host.prototype.matchHostname_ = function matchHostname_(hostname) { /* Returns: boolean - true if hostname exactly matches this.hostRegExp or, * if that is undefined, this.hostname. */ if (this.hostRegExp) { if (!(this.hostRegExp instanceof RegExp)) { throw new TypeError('invalid .hostRegExp'); } var m = this.hostRegExp.exec(hostname); return (m && m.index === 0); // Match only accepted if at start. } else if (this.hostname) { if (typeof this.hostname !== 'string') { throw new TypeError('invalid .hostname'); } return this.hostname === hostname; // Only exact matches. } else { return true; } }; Object.setOwnerOf($.servers.http.Host.prototype.matchHostname_, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype.matchHostname_.prototype, $.physicals.Maximilian); $.servers.http.Host.prototype.hostname = undefined; $.servers.http.Host.prototype.subdomains = null; $.servers.http.Host.prototype.addSubdomain = function addSubdomain(name, host) { /* Add the given Host as a subdomain of this Host. * * Arguments: * - name: string - the subdomain name. * - host: $.servers.http.Host - the Host to serve the subdomain. */ name = String(name); if (!(host instanceof $.servers.http.Host)) { throw new TypeError('host must be a Host'); } if (!this.hasOwnProperty('subdomains')) { this.subdomains = Object.create(null); } this.subdomains[name] = host; }; Object.setOwnerOf($.servers.http.Host.prototype.addSubdomain, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype.addSubdomain.prototype, $.physicals.Maximilian); $.servers.http.Host.prototype.url = function url(varArgs) { /* Return the base URL for this host (omitting scheme). * * Generally prefer $.servers.http.Request.prototype.hostUrl (q.v.) * instead of method - but in some cases it is necessary to generate * a URL for the webserver without an existing inbound Request to use * as reference, so this method allows one to be generated in the * obvious way from this.hostname. As with .hostUrl: * * - Absent any argument, the returned URL will routes to this * Host object. * - If an argument is supplied, the returned URL will instead be for * the named subdomain. * - Multiple arguments can be supplied if there are nested subdomains. * * E.g.: * rootHost.url() => '//example.codecity.world/' * rootHost.url('code') => '//code.example.codecity.world/' * rootHost.url('foo', 'bar') => '//foo.bar.example.codecity.world/' * * If .pathToSubdomain is enabled on one or more Host object(s): * rootHost.url('code') => '//example.codecity.world/code/' * rootHost.url('foo', 'bar') => '//example.codecity.world/foo/bar/' * or: '//bar.example.codecity.world/foo/' * * Barring bugs, the returned URL should always end with a '/'. * Arguments: * - subdomain: string - a string denoting a subdomain of interest. * Multiple arguments are allowed. RangeError is thrown if no such * subdomain exists. * Returns: string - the URL for the desired domain/subdomain. */ if (typeof this.hostname !== 'string') { throw new Error('canonical hostname not set'); } var hostname = this.hostname; var host = this; for (var subdomain, i = 0; (subdomain = arguments[i]); i++) { hostname = host.urlForSubdomain(hostname, subdomain); } return '//' + hostname + '/'; }; Object.setOwnerOf($.servers.http.Host.prototype.url, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype.url.prototype, $.physicals.Maximilian); $.servers.http.Host.prototype.pathToSubdomain = undefined; $.servers.http.Host.prototype.urlForSubdomain = function urlForSubdomain(hostname, subdomain, pathToSubdomainHeader) { /* A helper function for the .url method. * * Given a hostname for this host, add the specified subdomain * if it exists, or throw RangeError if not. * * If this.pathToSubdomain is true, or this.pathToSubdomain is undefined * and pathToSubdomainHeader is true, then the subdomain will be added as * a directory name suffix rather than a hostname pefix. * * E.g.: * rootHost.pathToSubdomain = false; * rootHost.urlForSubdomain('example.codecity.world', 'code') * => 'code.example.codecity.world' * * rootHost.pathToSubdomain = undefined; * rootHost.urlForSubdomain('example', 'code', true) * => 'example.codecity.world/code' * rootHost.urlForSubdomain('example', 'code', false) * => 'code.example.codecity.world' * rootHost.pathToSubdomain = true; * rootHost.urlForSubdomain('example', 'code', false) * => 'example.codecity.world/code' * * Arguments: * - hostname: string - the base hostname for this Host. * - subdomain: string - the desired subdomain. * - pathToSubdomainHeader: boolean | undefined - value of the * CodeCity-pathToSubdomain header for the current request (if there * is one). * * TODO: Give this function a better name, because what it returns * is not actually a valid URL. */ if (!(this.subdomains && subdomain in this.subdomains)) { throw new RangeError('nonexistent subdomain "' + subdomain + '"'); } if (this.pathToSubdomain || this.pathToSubdomain === undefined && pathToSubdomainHeader) { return hostname + '/' + subdomain; } else { return subdomain + '.' + hostname; } }; Object.setOwnerOf($.servers.http.Host.prototype.urlForSubdomain, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype.urlForSubdomain.prototype, $.physicals.Maximilian); $.servers.http.Host.prototype.deleteSubdomain = function deleteSubdomain(subdomain) { /* Delete a subdomain, or all subdomains served by a particular * Host object. * * Arguments: * - subdomain: string | $.servers.http.Host - the name of the subdomain * to be deleted, or the Host object serving it. */ if (!this.subdomains) return; if (typeof subdomain === 'string') { delete this.subdomains[subdomain]; } else if (subdomain instanceof $.servers.http.Host) { for (var key in this.subdomains) { if (this.subdomains[key] === subdomain) { delete this.subdomains[key]; } } } else { throw new TypeError('argument must be subdomain name or Host object'); } if (Object.getOwnPropertyNames(this.subdomains).length === 0) { delete this.subdomains; } }; Object.setOwnerOf($.servers.http.Host.prototype.deleteSubdomain, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.Host.prototype.deleteSubdomain.prototype, $.physicals.Maximilian); $.servers.http.onRequest = function onRequest(connection) { /* Called from $.servers.http.connection.onReceiveChunk when the * connection.request has been fully parsed and is ready to be handled. * * Arguments: * - conenction: Object with prototype $.servers.http.connection - the * connection to be handle. */ var request = connection.request; var response = connection.response; try { // Call .handle(request, response) on each Host object in // $.servers.http.hosts in order until one returns true to indicate // that it handled the request. for (var host, i = 0; (host = this.hosts[i]); i++) { if (host.handle(request, response)) return; } // No host responded to request. response.sendError(400, 'Unknown Host'); } catch (e) { suspend(); $.system.log(String(e) + '\n' + e.stack); if (response.headersSent) { // Too late to return a proper error page. Oh well. response.write('
' + $.utils.html.escape(String(e) + '\n' + e.stack) +
                     '
'); } else { response.sendError(500, e); } } finally { suspend(); connection.close(); } }; Object.setOwnerOf($.servers.http.onRequest, $.physicals.Maximilian); Object.setOwnerOf($.servers.http.onRequest.prototype, $.physicals.Maximilian); $.servers.http.hosts = []; ================================================ FILE: core/core_24_$.hosts.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Host objects for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.hosts = {}; $.hosts.root = (new 'Object.create')($.servers.http.Host.prototype); $.hosts.root.subdomains = (new 'Object.create')(null); $.hosts.root['/'] = {}; $.hosts.root['/'].www = '\n<% var staticUrl = request.hostUrl(\'static\'); %>\n\n\n Code City\n \n \n \n\n\n

\n \n Code City\n

\n

A community of inquisitive programmers.

\n \n\n'; $.hosts.root['/'].wwwAccess = 'public'; $.hosts.root['/mirror'] = {}; Object.setOwnerOf($.hosts.root['/mirror'], $.physicals.Maximilian); $.hosts.root['/mirror'].www = "\n<% var staticUrl = request.hostUrl('static'); %>\n\n \n Code City Browser Mirror\n \n \n favicon.ico\" rel=\"shortcut icon\">\n \n \n

\n logo.svg\" alt=\"\" width=\"47.5\" height=\"50\">\n Code City Browser Mirror\n

\n<%\nfor (var key in request) {\n if (!request.hasOwnProperty(key)) continue;\n var value = request[key];\n \n response.write('

request.' + $.utils.html.escape(key) + ':

\\n');\n response.write('
');\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('
');\n}\n%>\n

request.fromSameOrigin(): [mirror\">test]

\n
<%= request.fromSameOrigin() %>
\n

request.hostUrl('system'):

\n
<%= $.utils.html.escape($.utils.code.quote(request.hostUrl('system'))) %>
\n

Done

\n \n"; $.hosts.root['/mirror'].wwwAccess = 'public'; $.hosts.root['/robots.txt'] = {}; $.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: /"; $.hosts.root['/robots.txt'].wwwAccess = 'public'; $.hosts.system = (new 'Object.create')($.servers.http.Host.prototype); $.hosts.system['/logout'] = {}; Object.setOwnerOf($.hosts.system['/logout'], $.physicals.Neil); $.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\n\n\n Code City Logout\n \n \n \n \n\n \n\n

\n \n Code City\n

\n

<%= request.info.rootAuthority || request.info.host.hostname || \'\' %>

\n<% if (doLogout) { %>\n

You have been signed out.

\n \n<% } else { %>\n
\n Sign out\n
\n \n<% } %>\n\n'; $.hosts.dummy = (new 'Object.create')($.servers.http.Host.prototype); Object.setOwnerOf($.hosts.dummy, $.physicals.Maximilian); $.hosts.dummy.handle = function handle(request, response, info) { /* Report the mishandling of an http(s) request which should have * been intercepted by the nginx front-end and proxied to one * of the other servers. * * This Host object is a singleton placeholer to mark (in * $.hosts.root.subdomains) the subdomains that should be directed * to loginServer, connectServer, etc., or served from the /static/ * directory. As such, no requests should ever be able to reach * this Host object except due to a misconfiguration of nginx. * * Arguments: * - request: $.servers.http.Request - the incoming request to handle. * - response: $.servers.http.Response - the response to write to. * - info: Object - some information used by recursive calls to this function. * Returns: boolean - always true as all requests successfully generate * an error message. */ response.sendError(500, 'This request should have been intercepted by ' + 'the reverse proxy. Check nginx configuration!'); return true; }; Object.setOwnerOf($.hosts.dummy.handle, $.physicals.Maximilian); Object.setOwnerOf($.hosts.dummy.handle.prototype, $.physicals.Maximilian); $.hosts.root.subdomains.system = $.hosts.system; $.hosts.root.subdomains.connect = $.hosts.dummy; $.hosts.root.subdomains.login = $.hosts.dummy; $.hosts.root.subdomains.mobwrite = $.hosts.dummy; $.hosts.root.subdomains.static = $.hosts.dummy; $.servers.http.hosts[0] = $.hosts.root; ================================================ FILE: core/core_25_$.db.tempId.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Temporary ID database for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.db = {}; $.db.tempId = {}; $.db.tempId.getObjById = function getObjById(id) { /* Find object temporarily stored with the given ID. */ var record = this.tempIds_[id]; if (record) { record.time = Date.now(); return record.obj; } return undefined; }; Object.setOwnerOf($.db.tempId.getObjById, $.physicals.Maximilian); $.db.tempId.storeObj = function storeObj(obj) { /* Find temporary ID for obj in this.tempIds_, * adding it if it's not already there. */ var records = this.tempIds_; for (var id in records) { if (Object.is(records[id].obj, obj)) { records[id].time = Date.now(); return id; } } do { var id = Math.floor(Math.random() * 0xFFFFFFFF); } while (records[id]); records[id] = {obj: obj, time: Date.now()}; // Lazy call of cleanup. this.cleanSoon(); return id; }; Object.setOwnerOf($.db.tempId.storeObj, $.physicals.Maximilian); $.db.tempId.cleanSoon = function cleanSoon() { // Schedule a cleanup to happen in a minute. // Allows multiple calls to be batched together. if (!this.cleanThread_) { this.cleanThread_ = setTimeout(this.cleanNow.bind(this), 60 * 1000); } }; Object.setOwnerOf($.db.tempId.cleanSoon, $.physicals.Neil); $.db.tempId.cleanNow = function cleanNow() { // Cleanup IDs/objects that have not been accessed in an hour. clearTimeout(this.cleanThread_); this.cleanThread_ = null; var ttl = Date.now() - this.timeoutMs; var records = this.tempIds_; for (var id in records) { if (records[id].time < ttl) { delete records[id]; } } }; Object.setOwnerOf($.db.tempId.cleanNow, $.physicals.Neil); $.db.tempId.timeoutMs = 3600000; $.db.tempId.tempIds_ = (new 'Object.create')(null); $.db.tempId.cleanThread_ = undefined; ================================================ FILE: core/core_25_$.userDatabase.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview User database for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.userDatabase = {}; Object.setOwnerOf($.userDatabase, $.physicals.Maximilian); $.userDatabase.get = function get(id) { // Returns the user, or undefined. var hash = $.utils.string.hash('md5', this.salt_ + id); var table = this.byMd5; var value = table[hash]; if (!($.user.isPrototypeOf(value))) { delete table[hash]; return undefined; } return value; }; Object.setOwnerOf($.userDatabase.get, $.physicals.Neil); Object.setOwnerOf($.userDatabase.get.prototype, $.physicals.Maximilian); $.userDatabase.set = function set(id, user) { if (!$.user.isPrototypeOf(user)) { throw new TypeError('userDatabase only accepts $.user values'); } var hash = $.utils.string.hash('md5', this.salt_ + id); this.byMd5[hash] = user; }; Object.setOwnerOf($.userDatabase.set, $.physicals.Maximilian); Object.setOwnerOf($.userDatabase.set.prototype, $.physicals.Maximilian); $.userDatabase.validate = function validate() { var table = this.byMd5 for (var key in table) { if (!($.user.isPrototypeOf(table[key]))) { delete table[key]; } } }; Object.setOwnerOf($.userDatabase.validate, $.physicals.Maximilian); Object.setOwnerOf($.userDatabase.validate.prototype, $.physicals.Maximilian); $.userDatabase.salt_ = 'v2OU0LHchCl84mhu'; $.userDatabase.byMd5 = (new 'Object.create')(null); ================================================ FILE: core/core_26_inline_editor.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Inline code editor for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.hosts.code = (new 'Object.create')($.servers.http.Host.prototype); $.hosts.code['/inlineEdit'] = {}; $.hosts.code['/inlineEdit'].edit = function edit(obj, name, key) { /* Return a (valid) URL for a web editing session editing obj[key], * where obj might more commonly be known as name. */ if (!$.utils.isObject(obj)) throw new TypeError('obj must be an object'); if (typeof(key) !== 'string') throw new TypeError('key must be a string'); var objId = $.db.tempId.storeObj(obj); var url = $.hosts.root.url('code') + 'inlineEdit?objId=' + objId; if (name) { url += '&name=' + encodeURIComponent(name); } if (key) { url += '&key=' + encodeURIComponent(key); } return url; }; Object.setOwnerOf($.hosts.code['/inlineEdit'].edit, $.physicals.Maximilian); $.hosts.code['/inlineEdit'].load = function load(obj, key) { /* Return string containing initial editor contents for editing * obj[key]. */ var pd = Object.getOwnPropertyDescriptor(obj, key); var value = pd ? pd.value : undefined; if (typeof value === 'function') { return Function.prototype.toString.apply(value); } else { return $.utils.code.expressionFor(value, {depth: 1}); } }; Object.setOwnerOf($.hosts.code['/inlineEdit'].load, $.physicals.Maximilian); $.hosts.code['/inlineEdit'].save = function save(obj, key, src) { /* Eval the string src and (if successful) save the resulting value * as obj[key]. If the value produced from src and the existing * value of obj[key] are both objects, then an attempt will be made * to copy any properties from the old value to the new one. */ var old = obj[key]; src = $.utils.code.rewriteForEval(src, /* forceExpression= */ true); // Evaluate src in global scope (eval by any other name, literally). // TODO: don't use eval - prefer Function constructor for // functions; generate other values from an Acorn parse tree. var evalGlobal = eval; var val = evalGlobal(src); if (typeof old === 'function' && typeof val === 'function') { $.utils.object.transplantProperties(old, val); } if (typeof val === 'function') { val.lastModifiedTime = Date.now(); // TODO: Add user. //val.lastModifiedUser = ...; } obj[key] = val; return this.load(obj, key); }; Object.setOwnerOf($.hosts.code['/inlineEdit'].save, $.physicals.Maximilian); $.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\n\n Code Editor for <%= name %>.<%= key %>\n \n \n\n \n \n \n\n
\n \n

Editing <%= name %>.<%= key %>\n <%= status %>

\n \n \n \n
onclick="updateDisabled(); changed()">\n \n \n \n \n \n
\n \n
\n \n'; $.hosts.root.subdomains.code = $.hosts.code; ================================================ FILE: core/core_27_editor.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Web-based code explorer/editor for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.hosts.code['/'] = {}; $.hosts.code['/'].www = '\n<% var staticUrl = request.hostUrl(\'static\'); %>\n\n\n Code City: Code\n \n \n \n\n\n \n \n\nSorry, your browser does not support frames!\n'; $.hosts.code['/editor'] = {}; $.hosts.code['/editor'].www = '\n<% var staticUrl = request.hostUrl(\'static\'); %>\n\n \n \n Code City: Code Editor\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

Do you want to save changes?

\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'; $.hosts.code['/explorer'] = {}; $.hosts.code['/explorer'].www = '\n<% var staticUrl = request.hostUrl(\'static\'); %>\n\n \n \n Code City: Code Explorer\n \n \n \n \n \n \n \n
\n
\n \n\n'; $.hosts.code['/diff'] = {}; $.hosts.code['/diff'].www = '<% var staticUrl = request.hostUrl(\'static\'); %>\n\n \n Code City Diff Editor\n \n \n \n \n\n \n \n\n'; $.hosts.code['/objectPanel'] = {}; $.hosts.code['/objectPanel'].www = '\n<% var staticUrl = request.hostUrl(\'static\'); %>\n\n \n \n Code City: Code Object Panel\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
Server Error
Check your console…
\n \n \n \n \n\n'; $.hosts.code['/objectPanel'].getType = function getType(value) { // Return a type string for a value. // E.g. 'string', 'object', 'array', 'boolean'. if (value === null) { return 'null'; } if (Array.isArray(value)) { return 'array'; } if ((typeof value === 'function') && value.verb) { return 'verb'; } return typeof value; }; Object.setOwnerOf($.hosts.code['/objectPanel'].getType, $.physicals.Neil); $.hosts.code['/objectPanel'].buildData = function buildData(query) { // Provide data for the IDE's object panels. // Takes one input: a JSON-encoded list of parts from the 'parts' parameter. // Returns a browser-executed JavaScript data assignment. var data = {}; if (query) { var parts = new $.Selector(decodeURIComponent(query)); try { var value = (new $.Selector(parts)).toValue(); } catch (e) { // Parts don't match a valid path. $.system.log(String(e) + '\n' + e.stack); // TODO(fraser): Send an informative error message. data = null; } if (data) { // For simplicity, don't provide completions for primitives (despite // the fact that (for example) numbers inherit a '.toFixed' function). if (value && (typeof value === 'object' || typeof value === 'function')) { data.properties = []; while (value !== null && value !== undefined) { var ownProps = Object.getOwnPropertyNames(value); // Add typeof information. for (var i = 0; i < ownProps.length; i++) { var prop = ownProps[i]; var type = this.getType(value[prop]); ownProps[i] = {name: prop, type: type}; } data.properties.push(ownProps); value = Object.getPrototypeOf(value); } data.keywords = ['{proto}', '{owner}']; // Uncomment once Set, Map, WeakSet and WeakMap exist. //if (value instanceOf Set || value instanceOf WeakSet) { // data.keywords.push('{keys}'); //} //if (value instanceOf Map || value instanceOf WeakMap) { // data.keywords.push('{keys}', '{values}'); //} } } } else { data.roots = []; // Add typeof information. var global = $.utils.code.getGlobal(); for (var name in global) { data.roots.push({name: name, type: this.getType(global[name])}); } } return data; }; Object.setOwnerOf($.hosts.code['/objectPanel'].buildData, $.physicals.Neil); Object.setOwnerOf($.hosts.code['/objectPanel'].buildData.prototype, $.physicals.Neil); $.hosts.code['/editorXhr'] = {}; Object.setOwnerOf($.hosts.code['/editorXhr'], $.physicals.Neil); $.hosts.code['/editorXhr'].www = function code_editorXhr_www(request, response) { /* HTTP handler for /editorXhr * Provide data for the IDE's editors. * Takes several inputs: * - selector: a selector to the origin object * - key: a temporary key to the origin object * - src: JavaScript source representation of new value, * implies request to save * Writes JSON-encoded information about what is to be edited: * - key: a temporary key to the origin object * - src: JavaScript source representation of current value * - butter: short status message to be displayed to user * - saved: boolean indicating if a save was successful, * only present if save was requested * - login: boolean indicating if the user is logged in */ var data = {login: !!request.user}; try { // ends with ... finally {response.write(JSON.stringify(data));} if (!request.fromSameOrigin()) { // Security check to ensure this is being loaded by the code editor. data.butter = 'Cross-origin referer: ' + String(request.headers.referer); return; } var selector; try { selector = new $.Selector(decodeURIComponent(request.parameters.selector)); } catch (e) { data.butter = 'Invalid selector: ' + String(e); return; } // Get Binding being edited. var object; var part = selector[selector.length - 1]; if (selector.isVar()) { // Global variable; no parent object. object = null; } else if (request.parameters.key && (object = $.db.tempId.getObjById(request.parameters.key))) { // Successfully retrieved parent object from tempID DB. } else { // Get parent object via selector. var parent = new $.Selector(selector.slice(0, -1)); try { // Get parent object and populate the reverse-lookup db. object = parent.toValue(/*save:*/true); } catch (e) { data.butter = e.message; return; } if (!$.utils.isObject(object)) { data.butter = String(parent) + ' is not an object'; return; } // Save parent object in tempId DB; send key to client. data.key = $.db.tempId.storeObj(object); } var binding = new $.utils.Binding(object, part); // Save changes. if (request.parameters.src) { data.saved = false; this.save(request.parameters.src, binding, data, request.user); } // Populate the new value object in the reverse-lookup db. selector.toValue(/*save:*/true); // Load revised source. this.load(binding, data); } finally { suspend(); response.write(JSON.stringify(data)); } }; Object.setOwnerOf($.hosts.code['/editorXhr'].www, $.physicals.Maximilian); $.hosts.code['/editorXhr'].load = function load(binding, data) { /* The complement of save: render the current value of binding as a * string, prefixed with metadata, postfixed with type information. * * This should set data.src to a string which, when passed eval, will be (in * order of preference): * * - Identical to (as determined by Object.is) the current value, * - A shallow-copy of the current value, or * - Unparsable, such that eval will throw SyntaxError. * * The intention should be that it should be safe to save witout * having made any changes and be reasonably confident nothing will * break. * * Args: * - binding: $.utils.Binding - the binding being edited. * - data: {src: string, butter: string} - the data object to be returned * to the client. */ var value = binding.get(/*inherited:*/true); var inherited = !binding.exists(); try { var source = this.sourceFor(value); data.src = this.generateMetaData(value, source, inherited) + source; } catch (e) { suspend(); // TODO(cpcallen): Send a more informative error message. data.butter = String(e); throw e; } }; Object.setOwnerOf($.hosts.code['/editorXhr'].load, $.physicals.Maximilian); $.hosts.code['/editorXhr'].save = function $_www_code_editor_save(src, binding, data, user) { // Save changes by evalling src, doing post-processing as directed // by metadata, and then calling binding.set(/* new value */). // Sets data.saved and data.butter as appropriate to give feedback // to user. if (!user) { data.butter = 'User not logged in.'; return; } setPerms(user); var saveValue; try { suspend(); var expr = $.utils.code.rewriteForEval(src, /*forceExpression:*/true); // Evaluate src in global scope (eval by any other name, literally). var evalGlobal = eval; saveValue = evalGlobal(expr); } catch (e) { // TODO(fraser): Send a more informative error message. data.butter = String(e); return; } var oldValue = binding.get(/*inherited:*/false); // Get actual current value. try { this.handleMetaData(src, oldValue, saveValue); } catch (e) { if (typeof e === 'string') { // A thrown string should just be printed to the user. data.butter = e; return; } else { throw e; // Rethrow real errors. } } // Record last modification data on functions. if (typeof saveValue === 'function') { saveValue.lastModifiedTime = Date.now(); saveValue.lastModifiedUser = user; } try { binding.set(saveValue); } catch (e) { data.butter = String(e); return; } data.saved = true; if (binding.isProto()) { data.butter = 'Prototype Set'; } else if (binding.isOwner()) { data.butter = 'Owner Set'; } else { data.butter = 'Saved'; } }; Object.setOwnerOf($.hosts.code['/editorXhr'].save, $.physicals.Neil); $.hosts.code['/editorXhr'].handleMetaData = function handleMetaData(src, oldValue, newValue) { // Parse metadata directives from src and apply to newValue. // // The $.hosts.code['/editor'].www sends values to be edited to the // editor front-end encoded as JavaScript expressions, optionally preceded // by comments containing metadata about the value. The editor can // in turn return metadata directives which will be carried out by // this function. // // Supported directives (order matters for now): // // @copy_properties true // - Copy (most) properties from oldValue to newValue, if both // are objects. // // @hash 26076758802 // - Warn if old value doesn't hash to this value (conflicting // change happened between load and save). // // @delete_prop // - Delete the named property from newValue. // // @set_prop // - Set the named property of newValue to the specified value. // // Throws user-printed strings (not Errors) if unable to complete. var m = src.match(/^(?:[ \t]*(?:\/\/[^\n]*)?\n)+/); if (!m) { return; } var metaLines = m[0].split('\n'); for (var i = 0; i < metaLines.length; i++) { var meta = metaLines[i]; if (meta.match(/^\s*\/\/\s*@copy_properties\s+true\s*$/)) { // @copy_properties true if (!$.utils.isObject(newValue)) { throw "Can't copy properties onto primitive: " + newValue; } // Silently ignore if the old value is a primitive. if ($.utils.isObject(oldValue)) { $.utils.object.transplantProperties(oldValue, newValue); } } else if ((m = meta.match(/^\s*\/\/\s*@hash\s+(\S+)\s*$/))) { // @hash 26076758802 var oldSource = this.sourceFor(oldValue); var hash = $.utils.string.hash('md5', oldSource); if (String(hash) !== m[1]) { // The current value does not match the value when the editor was loaded. // This means the value changed out from under the editor. throw 'Collision: Out of date editor.'; } } else if ((m = meta.match(/^\s*\/\/\s*@delete_prop\s+(\S+)\s*$/))) { // @delete_prop dobj try { delete newValue[m[1]]; } catch (e) { throw "Can't delete '" + m[1] + "' property."; } } else if ((m = meta.match(/^\s*\/\/\s*@set_prop\s+(\S+)\s*=(.+)$/))) { // @set_prop dobj = "this" try { var propValue = JSON.parse(m[2]); } catch (e) { throw "Can't parse '" + m[1] + "' value: " + m[2]; } try { newValue[m[1]] = propValue; } catch (e) { throw "Can't set '" + m[1] + "' property."; } } } }; Object.setOwnerOf($.hosts.code['/editorXhr'].handleMetaData, $.physicals.Maximilian); $.hosts.code['/editorXhr'].generateMetaData = function generateMetaData(value, src, inherited) { /* Assemble any meta-data for the editor. * * Arguments: * value: any - the value which will be provided as the initial value to begin * editing from. This might be a value inherited from a prototype, if the * binding being edited does not yet exist. * inherited: boolean - should be set to true iff value is inherited from a * prototype, such that saving will create a new property binding * overriding the interhited value, rather than replacing an existing * value. * * Returns: string - metadata informing $.hosts.code['/editorXhr'].save * what to do after creating the new value from the edited description. * At present, metadata is only generated if it is a function. */ var meta = ''; if ($.utils.isObject(value)) { // TODO: add @copy_properties here, but not if the source code is a selector? } if (typeof value === 'function') { if (value.lastModifiedTime) { var date = new Date(value.lastModifiedTime); meta += '// @last_modified_time ' + date.toString() + '\n'; } if (value.lastModifiedUser) { meta += '// @last_modified_user ' + String(value.lastModifiedUser) + '\n'; } meta += '// @copy_properties ' + !inherited + '\n'; var props = ['verb', 'dobj', 'prep', 'iobj']; for (var i = 0, prop; (prop = props[i]); i++) { try { meta += '// ' + (value[prop] ? '@set_prop ' + prop + ' = ' + JSON.stringify(value[prop]) : '@delete_prop ' + prop) + '\n'; } catch (e) { // Unstringable value, or read perms error. Skip. } } if (inherited) src = 'undefined'; // What source of oldValue will be. var hash = $.utils.string.hash('md5', src); meta += '// @hash ' + hash + '\n'; } return meta; }; Object.setOwnerOf($.hosts.code['/editorXhr'].generateMetaData, $.physicals.Maximilian); $.hosts.code['/editorXhr'].sourceFor = function sourceFor(value) { /* Generate source code for a given value. * * Arguments: * - value: any - any JavaScript value. * Returns: string - source code for value. */ switch (typeof value) { // Special-case the most common cases for efficiency and to reduce // chance of editor breaking due to bugs in $.utils.code. // // TODO: consider removing special case for strings once editor frontends // cope with single-quoted strings. case 'function': return Function.prototype.toString.call(value); case 'string': return JSON.stringify(value); case 'undefined': return 'undefined'; default: // TODO: allow user-specified options. N.B.: careful when dealing with // editing sessions shared via MobWrite, to avoid @hash metatdata // failures. // TODO: add selector to options, so as to avoid including a comment // about it in the output when it is as expected - but think through // implications for @hash checking carefully first! return $.utils.code.expressionFor(value, this.sourceOptions); } }; Object.setOwnerOf($.hosts.code['/editorXhr'].sourceFor, $.physicals.Maximilian); Object.setOwnerOf($.hosts.code['/editorXhr'].sourceFor.prototype, $.physicals.Maximilian); $.hosts.code['/editorXhr'].sourceOptions = {}; Object.setOwnerOf($.hosts.code['/editorXhr'].sourceOptions, $.physicals.Maximilian); $.hosts.code['/editorXhr'].sourceOptions.depth = 3; $.hosts.code['/editorXhr'].sourceOptions.abbreviateMethods = true; $.hosts.code['/svg'] = {}; Object.setOwnerOf($.hosts.code['/svg'], $.physicals.Neil); $.hosts.code['/svg'].www = '<% var staticUrl = request.hostUrl(\'static\'); %>\n\n \n Code City SVG Editor\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'; $.hosts.code['/login'] = {}; Object.setOwnerOf($.hosts.code['/login'], $.physicals.Neil); $.hosts.code['/login'].www = '\n<% var staticUrl = request.hostUrl(\'static\'); %>\n\n\n Code City Login\n \n \n \n\n\n

\n \n Code City\n

\n

Login required to edit code.

\n \n\n'; $.hosts.code['/mirror'] = $.hosts.root['/mirror']; $.hosts.code['/eval'] = {}; Object.setOwnerOf($.hosts.code['/eval'], $.physicals.Neil); $.hosts.code['/eval'].www = "\n<% var staticUrl = request.hostUrl('static'); %>\n\n \n Code City Eval\n \n \n favicon.ico\" rel=\"shortcut icon\">\n \n \n \n \n

Immediate Eval

\n
\n    \n  \n";
$.hosts.code['/evalXhr'] = {};
Object.setOwnerOf($.hosts.code['/evalXhr'], $.physicals.Neil);
$.hosts.code['/evalXhr'].www = function code_evalXhr_www(request, response) {
  setPerms(request.user);
  var output = '';
  if (!request.fromSameOrigin()) {
    // Security check to ensure this is being loaded by the eval editor.
    output = 'Cross-origin referer: ' + String(request.headers.referer);
  } else {
    try {
      var src = $.utils.code.rewriteForEval(request.data);
      output = $.utils.code.eval(src);
    } catch (e) {
      suspend();
      output = String(e);
    }
  }
  response.write(output);
};
Object.setOwnerOf($.hosts.code['/evalXhr'].www, $.physicals.Maximilian);
Object.setOwnerOf($.hosts.code['/evalXhr'].www.prototype, $.physicals.Neil);



================================================
FILE: core/core_28_$.servers.eval.js
================================================
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Eval server for Code City.
 */

//////////////////////////////////////////////////////////////////////
// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!
//////////////////////////////////////////////////////////////////////

$.servers.eval = {};
$.servers.eval.connection = (new 'Object.create')($.connection);
$.servers.eval.connection.onReceiveLine = function onReceiveLine(text) {
  if (this !== $.servers.eval.connected) {
    this.close();
    return;
  }
  this.write('⇒ ' + $.utils.code.eval(text) + '\n');
  this.write('eval> ');
};
Object.setOwnerOf($.servers.eval.connection.onReceiveLine, $.physicals.Maximilian);
Object.setOwnerOf($.servers.eval.connection.onReceiveLine.prototype, $.physicals.Maximilian);
$.servers.eval.connection.onConnect = function onConnect() {
  $.connection.onConnect.apply(this, arguments);
  if ($.servers.eval.connected) {
    $.servers.eval.connected.close();
  }
  $.servers.eval.connected = this;
  this.write('eval> ');
};
Object.setOwnerOf($.servers.eval.connection.onConnect, $.physicals.Maximilian);
Object.setOwnerOf($.servers.eval.connection.onConnect.prototype, $.physicals.Maximilian);
$.servers.eval.connection.close = function close() {
  this.write('This session has been terminated.\n');
  return $.connection.close.apply(this, arguments);
};
Object.setOwnerOf($.servers.eval.connection.close, $.physicals.Maximilian);
Object.setOwnerOf($.servers.eval.connection.close.prototype, $.physicals.Maximilian);
$.servers.eval.connection.onEnd = function onEnd() {
  $.servers.eval.connected = null;
  return $.connection.onEnd.apply(this, arguments);
};
Object.setOwnerOf($.servers.eval.connection.onEnd, $.physicals.Maximilian);
Object.setOwnerOf($.servers.eval.connection.onEnd.prototype, $.physicals.Maximilian);
$.servers.eval.connected = null;



================================================
FILE: core/core_30_$.utils.command.js
================================================
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Command parser for Code City
 */

//////////////////////////////////////////////////////////////////////
// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!
//////////////////////////////////////////////////////////////////////

$.utils.command = {};
$.utils.command.prepositions = (new 'Object.create')(null);
$.utils.command.prepositions.with = 'with/using';
$.utils.command.prepositions.using = 'with/using';
$.utils.command.prepositions.at = 'at/to';
$.utils.command.prepositions.to = 'at/to';
$.utils.command.prepositions['in front of'] = 'in front of';
$.utils.command.prepositions.in = 'in/inside/into';
$.utils.command.prepositions.inside = 'in/inside/into';
$.utils.command.prepositions.into = 'in/inside/into';
$.utils.command.prepositions['on top of'] = 'on top of/on/onto/upon';
$.utils.command.prepositions.on = 'on top of/on/onto/upon';
$.utils.command.prepositions.onto = 'on top of/on/onto/upon';
$.utils.command.prepositions.upon = 'on top of/on/onto/upon';
$.utils.command.prepositions.over = 'over';
$.utils.command.prepositions.through = 'through';
$.utils.command.prepositions.under = 'under/underneath/beneath';
$.utils.command.prepositions.underneath = 'under/underneath/beneath';
$.utils.command.prepositions.beneath = 'under/underneath/beneath';
$.utils.command.prepositions.behind = 'behind';
$.utils.command.prepositions.beside = 'beside';
$.utils.command.prepositions.for = 'for/about';
$.utils.command.prepositions.about = 'for/about';
$.utils.command.prepositions.is = 'is';
$.utils.command.prepositions.as = 'as';
$.utils.command.prepositions.off = 'off/off of';
$.utils.command.prepositions['off of'] = 'off/off of';
$.utils.command.prepositions['out of'] = 'out of/from inside/from';
$.utils.command.prepositions['from inside'] = 'out of/from inside/from';
$.utils.command.prepositions.from = 'out of/from inside/from';
$.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.*)?$/;
$.utils.command.prepositionOptions = [];
$.utils.command.prepositionOptions[0] = 'none';
$.utils.command.prepositionOptions[1] = 'any';
$.utils.command.prepositionOptions[2] = 'with/using';
$.utils.command.prepositionOptions[3] = 'at/to';
$.utils.command.prepositionOptions[4] = 'in front of';
$.utils.command.prepositionOptions[5] = 'in/inside/into';
$.utils.command.prepositionOptions[6] = 'on top of/on/onto/upon';
$.utils.command.prepositionOptions[7] = 'out of/from inside/from';
$.utils.command.prepositionOptions[8] = 'over';
$.utils.command.prepositionOptions[9] = 'through';
$.utils.command.prepositionOptions[10] = 'under/underneath/beneath';
$.utils.command.prepositionOptions[11] = 'behind';
$.utils.command.prepositionOptions[12] = 'beside';
$.utils.command.prepositionOptions[13] = 'for/about';
$.utils.command.prepositionOptions[14] = 'is';
$.utils.command.prepositionOptions[15] = 'as';
$.utils.command.prepositionOptions[16] = 'off/off of';
$.utils.command.parse = function parse(cmdstr, user) {
  // Parse a user's command into components.
  //
  // Commands are generally expected to be of the form:
  //
  //    
  //
  // ... where all parts but  are optional, but 
  // required if  is present.
  //
  // The parse will return an object with the following properties:
  //
  // user:    The $.user object, from the parameter of the same name.
  // cmdstr:  The cmdstr parameter (coerced to string).
  // verbstr: The first non-whitespace word of cmdstr (if any).
  // argstr:  The rest of cmdstr, starting from the second character
  //          after the verb.
  // args:    An array of all the rest of the words of cmdstr.
  // dobjstr: Sring of args up to the (first) preposition.
  // dobj:    Object matching dobjstr.  If dobjstr is the empty string
  //          then this will be null.  If no object matches, it will
  //          be $.FAILED_MATCH.  If more than one object matches it
  //          will be $.AMBIGUOUS_MATCH.
  // prepstr: String of the (first) preposition, if any.
  // iobjstr: String of args after the (first) preposition.
  // iobj:    Object matching iobjstr.  Special values as for dobj.
  //
  // If cmdstr contains no non-whitespace characters, null is returned
  // instead.
  //
  // The cmdstr, verbstr and argstr properties are "raw" strings,
  // unmodified from the cmdstr parameter, while dobjstr, prepstr and
  // iobjstr are normalised, being substrings of args.join(' ').

  // Spit off verb from the rest.
  cmdstr = String(cmdstr);
  var m = cmdstr.match($.utils.command.verbRegExp);
  if (!m) return null;
  var verbstr = m[1];
  var argstr = m[2] || '';
  // Split argstr into words.
  // TODO(cpcallen): support quoting.
  var argstrTrimmed = argstr.trim();
  var args = argstrTrimmed ? argstrTrimmed.split(/\s+/) : [];
  // Recombine args and split into dobjstr / prepstr / iobjstr
  var argsNormalised = args.join(' ');
  var dobjstr = '';
  var prepstr = '';
  var iobjstr = '';
  m = argsNormalised.match($.utils.command.prepositionsRegExp);
  if (m) {
    // Preposition found.
    dobjstr = (m[1] || '').trim();
    prepstr = m[2].replace(/ +/g, ' ');
    iobjstr = (m[3] || '').trim();
  } else {
    dobjstr = argsNormalised;
  }
  function match(str) {
    if (str === '') return null;
    if (str === 'me' || str === 'myself') return user;
    if (str === 'here') return user.location;
    return $.utils.command.match(str, user);
  }
  var dobj = match(dobjstr);
  var iobj = match(iobjstr);
  return {
    user: user,
    cmdstr: cmdstr,
    verbstr: verbstr,
    argstr: argstr,
    args: args,
    dobjstr: dobjstr,
    dobj: dobj,
    prepstr: prepstr,
    iobjstr: iobjstr,
    iobj: iobj
  };
};
Object.setOwnerOf($.utils.command.parse, $.physicals.Maximilian);
$.utils.command.execute = function execute(cmdstr, user) {
  /* Parse and execute a user's command.  Returns true if a
   * verb-function was invoked; narrates an error message and
   * false otherwise.
   */
  var cmd = $.utils.command.parse(cmdstr, user);
  if (!cmd) return false;
  // Collect all objects which could host the verb.
  var hosts = [user, user.location, cmd.dobj, cmd.iobj];
  for (var i = 0; i < hosts.length; i++) {
    var host = hosts[i];
    if (!host) {
      continue;
    }
    // Check every verb on each object for a match.
    for (var prop in host) {
      var func = host[prop];
      if (typeof func !== 'function') continue;  // Not a function.
      var verbSpec = func.verb;
      var dobjSpec = func.dobj;
      var prepSpec = func.prep;
      var iobjSpec = func.iobj;  // I can't wait for ES6.
      if (!verbSpec || !dobjSpec || !prepSpec || !iobjSpec) continue;  // Not a verb.
      var verbRegExp = new RegExp('^(?:' + verbSpec + ')$');
      if (verbRegExp.test(cmd.verbstr) &&
          (prepSpec === 'any' ||
           $.utils.command.prepositions[cmd.prepstr] === prepSpec ||
           (prepSpec == 'none' && !cmd.prepstr)) &&
          (dobjSpec === 'any' || (dobjSpec === 'this' && cmd.dobj === host) ||
           (dobjSpec === 'none' && !cmd.dobj)) &&
          (iobjSpec === 'any' || (iobjSpec === 'this' && cmd.iobj === host) ||
           (iobjSpec === 'none' && !cmd.iobj))) {
        // TODO: security check/perms.
        host[prop](cmd);
        return true;
      }
    }
  }
  cmd.user.narrate('I don\'t understand that.');
  return false;
};
Object.setOwnerOf($.utils.command.execute, $.physicals.Maximilian);
$.utils.command.verbRegExp = /^\s*(\S+)(?:\s(.*))?/;
$.utils.command.match = function match(str, context) {
  /* Attempt to find an object matching str amongst context,
   * context.location, and context.contents.
   *
   * Args:
   * - str: string: prefix of name or alias of desired object.
   * - context: $.physical: an object to search.
   *
   * Returns: an object matching str, or $.FAILED_MATCH if none or
   * $.AMBIGUOUS_MATCH if more than one.
   */
  str = str.trim();
  // First, check for matches against universally accessible things.
  try {
    var v = $(str);
    if ($.utils.isObject(v)) return v;
  } catch (e) {
    // Ignore failed Selector parse/lookup.
  }
  var objects = [context].concat(context.getContents());
  if (context.location) {
    objects = objects.concat([context.location], context.location.getContents());
  }
  var m = $.utils.command.matchObjects(str, objects);
  switch (m.length) {
    case 0:
      return $.FAILED_MATCH;
    case 1:
      return m[0];
    default:
      return $.AMBIGUOUS_MATCH;
  }
};
Object.setOwnerOf($.utils.command.match, $.physicals.Maximilian);
$.utils.command.matchFailed = function matchFailed(obj, objstr, user) {
  /* Return true iff obj is NOT a valid match, and optionally narrate
   * a suitable error message if not.
   *
   * If obj is null, $.FAILED_MATCH or $.AMBIGUOUS_MATCH (and objstr
   * and user are supplied) call user.narrate with a suitable error
   * message.
   *
   * Args:
   * - obj: $.physical | null | $.FAILED_MATCH | $.AMBIGUOUS_MATCH:
   *     A match value (e.g., cmd.dobj or cmd.iobj) to be checked.
   * - objstr: string:
   *     The string which was matched to get obj.
   * - user: $.user:
   *     The user who typed the command.
   * Returns: boolean: true if obj is a $.physical.
   */
  var send = (typeof objstr === 'string' && $.user.isPrototypeOf(user));
  if (obj === null) {
    if (send) user.narrate('You must give the name of some object.');
    return true;
  } else if (obj === $.FAILED_MATCH) {
    if (send) user.narrate('I see no "' + objstr + '" here.');
    return true;
  } else if (obj === $.AMBIGUOUS_MATCH) {
    if (send) user.narrate('I don\'t know which "' + objstr + '" you mean.');
    return true;
  } else if ($.physical.isPrototypeOf(obj)) {
    return false;
  } else {
    throw new TypeError('unexpected value checking match result');
  }
};
Object.setOwnerOf($.utils.command.matchFailed, $.physicals.Maximilian);
Object.setOwnerOf($.utils.command.matchFailed.prototype, $.physicals.Maximilian);
$.utils.command.matchObjects = function matchObjects(str, objects) {
  /* Match a string against a list of objects.  Will return an array
   * of zero or more objects such that (in order of preference):
   * - all have .name === str.
   * - all have str in their .aliases.
   * - all have str as a prefix of their name or an alias.
   *
   * Duplicate entries in objects will be ignored; only a single copy
   * will appear in the returned array.
   *
   * Args:
   * str: string to match against names and aliases of objects.
   * objects: array of $.physical objects to consider.
   *
   * Returns: possibly-empty array of objects matching str.
   *
   */
  var nameMatches = [];  // These should be Sets.
  var aliasMatches = [];
  var partialMatches = [];
  var nonMatches = [];  // Non-matches will be ignored.
  var matches = [nonMatches, partialMatches, aliasMatches, nameMatches];

  for (var i = 0; i < objects.length; i++) {
    var obj = objects[i];
    var strength = $.utils.command.matchObjects.strength(str, obj);
    if (!matches[strength].includes(obj)) {
      matches[strength].push(obj);
    }
  }

  // Return the highest level bin.
  if (nameMatches.length) return nameMatches;
  if (aliasMatches.length) return aliasMatches;
  if (partialMatches.length) return partialMatches;
  return [];
};
Object.setOwnerOf($.utils.command.matchObjects, $.physicals.Maximilian);
Object.setOwnerOf($.utils.command.matchObjects.prototype, $.physicals.Maximilian);
$.utils.command.matchObjects.strength = function strength(str, obj) {
  /* Score str as a match for obj.
   * Returns: number
   * - 0: No match.
   * - 1: Partial name or alias.
   * - 2: Perfect alias match.
   * - 3: Perfect name match.
   */
  if (!str || !obj) {
    return 0;
  }
  str = str.toLowerCase();
  var name = obj.name.toLowerCase();
  if (name === str) {
    return 3;
  }
  var partial = name.startsWith(str);
  if (Array.isArray(obj.aliases)) {
    for (var i = 0; i < obj.aliases.length; i++) {
      var alias = obj.aliases[i].toLowerCase();
      if (name === alias) {
        return 2;
      }
      partial = partial || alias.startsWith(str);
    }
  }
  return partial ? 1 : 0;
};
Object.setOwnerOf($.utils.command.matchObjects.strength, $.physicals.Maximilian);



================================================
FILE: core/core_31_$.utils_world.js
================================================
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview World-related utils for Code City.
 */

//////////////////////////////////////////////////////////////////////
// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!
//////////////////////////////////////////////////////////////////////

$.utils.commandMenu = function commandMenu(commands) {
  var cmdXml = '';
  if (commands.length) {
    cmdXml += '';
    for (var i = 0; i < commands.length; i++) {
      cmdXml += '' + $.utils.html.escape(commands[i]) + '';
    }
    cmdXml += '';
  }
  return cmdXml;
};
Object.setOwnerOf($.utils.commandMenu, $.physicals.Maximilian);

$.utils.replacePhysicalsWithName = function replacePhysicalsWithName(value) {
  /* Deeply clone JSON object.
   * Replace all instances of $.physical with the object's name.
   */
  if (Array.isArray(value)) {
    var newArray = [];
    for (var i = 0; i < value.length; i++) {
      newArray[i] = replacePhysicalsWithName(value[i]);
    }
    return newArray;
  }
  if ($.physical.isPrototypeOf(value)) {
    return value.name;
  }
  if (typeof value === 'object' && value !== null) {
    var newObject = {};
    for (var prop in value) {
      newObject[prop] = replacePhysicalsWithName(value[prop]);
    }
    return newObject;
  }
  return value;
};
Object.setOwnerOf($.utils.replacePhysicalsWithName, $.physicals.Maximilian);



================================================
FILE: core/core_32_physical.js
================================================
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Physical object prototype for Code City.
 */

//////////////////////////////////////////////////////////////////////
// AUTO-GENERATED CODE FROM DUMP.  EDIT WITH CAUTION!
//////////////////////////////////////////////////////////////////////

$.physical = {};
$.physical.name = 'Physical object prototype';
$.physical.description = '';
$.physical.svgText = '';
$.physical.location = null;
$.physical.contents_ = null;
$.physical.getContents = function getContents() {
  $.physical.validate.call(this);
  return this.contents_.slice();
};
Object.setOwnerOf($.physical.getContents, $.physicals.Maximilian);
Object.setOwnerOf($.physical.getContents.prototype, $.physicals.Maximilian);
$.physical.addContents = function addContents(newThing, opt_neighbour) {
  // Add newThing to this's contents.  It will be added after
  // opt_neighbour, or to the end of list if opt_neighbour not given.
  // An item already in the contents list will be moved to the
  // specified position.
  $.physical.validate.call(this);
  if (!$.physical.isPrototypeOf(newThing)) {
    throw new TypeError('cannot add non-$.physical to contents');
  } else if(newThing.location !== this) {
    throw new RangeError('object to be added to contents must have .location set first');
  }
  for (var loc = this; loc; loc = loc.location) {
    if (loc === newThing) {
      throw new RangeError('object cannot contain itself');
    }
  }
  var contents = this.contents_;
  var index = contents.indexOf(newThing);
  if (index !== -1) {
    // Remove existing thing.
    contents.splice(index, 1);
  }
  if (opt_neighbour) {
    for (var i = 0, thing; (thing = contents[i]); i++) {
      if (thing === opt_neighbour) {
        contents.splice(i + 1, 0, newThing);
        return;
      }
    }
    // Neighbour not found, just append.
  }
  // Common case of appending a thing.
  contents.push(newThing);
};
Object.setOwnerOf($.physical.addContents, $.physicals.Maximilian);
$.physical.removeContents = function removeContents(thing) {
  var contents = this.contents_;
  var index = contents.indexOf(thing);
  if (index !== -1) {
    contents.splice(index, 1);
  }
  this.contents_ = contents;
};
Object.setOwnerOf($.physical.removeContents, $.physicals.Neil);
$.physical.moveTo = function moveTo(dest, opt_neighbour) {
  /* Move his object to the specified destination location.
   * Attempt to position this object next to a specified neighbour, if given.
   */
  $.physical.validate.call(this);
  if (!$.physical.isPrototypeOf(dest) && dest !== null) {
    throw new Error('destination must be a $.physical or null');
  }
  var src = this.location;
  if (src === dest) return;  // Nothing to do.
  // Preliminary check for recursive move.  This is formally enforced by
  // $.physical.addContents(), but we bail here if it is likely to fail later.
  for (var loc = dest; loc; loc = loc.location) {
    if (loc === this) {
      throw new RangeError('cannot move an object inside itself');
    }
  }
  // Call this.willMoveTo(dest), and refuse move unless it returns true without suspending.
  var willMove = false;
  new Thread(function checkWillMoveTo() {
    willMove = Boolean(this.willMoveTo(dest));
  }, 0, this);
  suspend(0);
  if (!willMove) {
    throw new PermissionError(String(this) + " isn't movable to " + String(dest));
  }
  // Call dest.accept(this), and refuse move unless it returns true without suspending.
  var accept = false;
  new Thread(function checkAccept() {
    accept = (dest === null || Boolean(dest.accept(this)));
  }, 0, this);
  suspend(0);
  if (!accept) {
    throw new PermissionError(String(dest) + " doesn't accept " + String(this));
  }
  // Call src.onExit(this, dest).
  new Thread(function callOnExit() {
    if (src) src.onExit(this, dest);
  }, 0, this);
  suspend(0);
  // Perform move.
  if (src && src.removeContents) src.removeContents(this);
  this.location = dest;
  if (dest) {
    try {
      dest.addContents(this, opt_neighbour);
    } finally {
      if (!dest.contents_.includes(this)) {
        this.location = null;  // Uh oh.
        dest = null;
      }
    }
  }
  // Call dest.onEnter(this, src).
  new Thread(function callOnEnter() {
    if (dest) dest.onEnter(this, src);
  }, 0, this);
  suspend(0);
};
Object.setOwnerOf($.physical.moveTo, $.physicals.Maximilian);
$.physical.look = function look(cmd) {
  var html = $.jssp.eval(this, 'lookJssp', {user: cmd.user});
  cmd.user.readMemo({type: "html", htmlText: html});
};
Object.setOwnerOf($.physical.look, $.physicals.Neil);
$.physical.look.verb = 'l(ook)?';
$.physical.look.dobj = 'this';
$.physical.look.prep = 'none';
$.physical.look.iobj = 'none';
$.physical.lookJssp = "\n  \n    \n    \n  \n
\n \n <%= $.utils.object.getValue(this, 'svgText') %>\n \n \n

<%: this %><%= $.utils.commandMenu(this.getCommands(request.user)) %>

\n

<%= $.utils.html.preserveWhitespace($.utils.object.getValue(this, 'description')) %>

\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('

Contents: ' + contentsHtml.join(', ') + '

');\n}\nif (this.location) {\n response.write('

Location: ' + $.utils.html.escape(this.location.name) +\n $.utils.commandMenu(this.location.getCommands(request.user)) + '

');\n}\n%>\n
"; $.physical.getCommands = function getCommands(who) { return [ 'look ' + this.name, // 'examine ' + this.name, 'edit ' + this.name ]; }; Object.setOwnerOf($.physical.getCommands, $.physicals.Neil); $.physical.validate = function validate() { /* Validate this $.physical object to enforce that certain * invariants are true. Those invariants are: * - this.location must be a $.physical or null. * - this.contents_ must be an array unique to this (not inherited) * - Each item in this.contents_ must be a $.physical and have * item.location === this. */ // Recover this if it has inadvertently become $.garbage. // // TODO: ideally validatate is non-overridable, and everywhere that // presently invokes $.physical.validate.call(x) can just do // x.validate() instead, and this line can go away. if ($.garbage.isPrototypeOf(this)) this.validate(); if (!$.physical.isPrototypeOf(this)) { throw TypeError('$.physical.validate called on incompatible receiver'); } // They can only be located in another $.physical object (or null) // and that object must have this in its contents: var loc = this.location; if ($.garbage.isPrototypeOf(loc)) loc.validate(); if (!$.physical.isPrototypeOf(loc) || ($.utils.validate.ownArray(loc, 'contents_'), // N.B.: comma operator !loc.contents_.includes(this))) { this.location = null; } // this.contents_ must be an array unique to this (not inherited): $.utils.validate.ownArray(this, 'contents_'); // this.contents_ must not contain any duplicates, non-$.physical // objects, objects not located in this: for (var i = this.contents_.length - 1; i >= 0; i--) { var item = this.contents_[i]; if ($.garbage.isPrototypeOf(item)) item.validate(); if (this.contents_.indexOf(item) !== i || // true for duplicates !$.physical.isPrototypeOf(item) || item.location !== this) { this.contents_.splice(i, 1); } } // TODO: check for circular containment? }; Object.setOwnerOf($.physical.validate, $.physicals.Maximilian); $.physical.toString = function toString() { return this.name; }; Object.setOwnerOf($.physical.toString.prototype, $.physicals.Maximilian); $.physical.accept = function accept(what, src) { /* Returns true iff this is willing to accept what arriving from src. * * This function should only be called by $.physical.moveTo() * immediately before actually performing a move. It is OK if this * function (or its overrides) has some kind of observable * side-effect (making noise, causing some other action, etc.). * * Other code wanting to test if a move is likely to succeed should * call .willAccept(what, src) instead. * * Throwing an error or suspending is equivalent to returning false. */ return this.willAccept(what, src); }; Object.setOwnerOf($.physical.accept, $.physicals.Maximilian); $.physical.willAccept = function willAccept(what, src) { /* Returns true iff this is willing to accept what arriving from src. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.) */ return false; }; Object.setOwnerOf($.physical.willAccept, $.physicals.Maximilian); Object.setOwnerOf($.physical.willAccept.prototype, $.physicals.Maximilian); $.physical.onExit = function onExit(what, dest) { /* Called by $.physical.moveTo just before what leaves for dest. */ }; Object.setOwnerOf($.physical.onExit, $.physicals.Maximilian); $.physical.onEnter = function onEnter(what, src) { /* Called by $.physical.moveTo just after what arrives from src. */ }; Object.setOwnerOf($.physical.onEnter, $.physicals.Maximilian); $.physical.lookAt = function lookAt(cmd) { this.look(cmd); }; Object.setOwnerOf($.physical.lookAt, $.physicals.Maximilian); $.physical.lookAt.verb = 'l(ook)?'; $.physical.lookAt.dobj = 'none'; $.physical.lookAt.prep = 'at/to'; $.physical.lookAt.iobj = 'this'; $.physical.kick = function kick(cmd) { cmd.user.narrate('You kick ' + String(this) + '.'); if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' kicks ' + String(this) + '.', cmd.user); } this.validate(); }; $.physical.kick.verb = 'kick'; $.physical.kick.dobj = 'this'; $.physical.kick.prep = 'none'; $.physical.kick.iobj = 'none'; $.physical.readMemo = function readMemo(memo) { /* Deliver a memo to this object. * * A memo is an object that encodes a message about something that * can be seen or has just happened nearby. Most usually they are * sent to the user's client (after being converted to JSON), but in * principle any $.physical object can receve a memo and potentially * react to it. * * Some example memos: * * A scene (simlified): * {type: 'scene', user: , where: , * svgText: '', * contents: [ * {type: 'user', what: , svgText: '' }, * {type: 'thing', what: , svgText: ''} * ]} * * A narration: * {type: 'narrate', text: "A door appears!"} * * Someone says something: * {type: 'say', source: , where: , text: 'Hi.'} * * If you want to make an object react to memos (e.g., by responding * to things said to it), it is better to create an .onMemo method * rather than overriding .readMemo. */ if (this.onMemo) { new Thread(function readMemoDispatcher() { try { this.onMemo(memo); } catch (e) { suspend(); if ($.room.isPrototypeOf(this.location)) { this.location.narrate(String(e) + '\n' + e.stack, undefined, this); } else { throw e; } } }, 0, this); } }; Object.setOwnerOf($.physical.readMemo, $.physicals.Maximilian); $.physical.setName = function setName(name, tryAlternative) { /* Set the .name of this physical object. If the desired name is * already in use and tryAlternative is true a similar name (like * "foo #2" or "foo #3") will be used instead; otherwise RangeError * will be thrown. * * name: string: the desired new name. * tryAlternative: boolean: try to find an alternative name. * * Returns the object's new name. */ if (!$.physical.isPrototypeOf(this)) { throw new TypeError('must be called on a $.physical'); } else if (typeof name !== 'string' || name.length < 1) { throw new TypeError('new name must be a non-empty string'); } function check(name) { if (!(name in $.physicals)) return true; // Name not in use. var oldObj = $.physicals[name]; if (!$.physical.isPrototypeOf(oldObj) && $.physical !== oldObj) { delete $.physicals[name]; return true; // Name was in use but holder no longer a $.physical } return $.physicals[name] === this; // Name in use, but maybe it's us? } if (!check.call(this, name)) { // Desired name in use. if (!tryAlternative) throw new RangeError('there is already another object named ' + name); for (var i = 2; i < Object.getOwnPropertyNames($.physicals).length + 2; i++) { var proposed = name + ' #' + i; if (check.call(this, proposed)) { name = proposed; break; } } } // New name is not in use, or already ours. if (name !== this.name) { if (this.name in $.physicals && $.physicals[this.name] === this) { delete $.physicals[this.name]; } } this.name = name; $.physicals[name] = this; new $.Selector(['$', 'physicals', name]).toValue(/*save:*/true); return name; }; Object.setOwnerOf($.physical.setName, $.physicals.Maximilian); Object.setOwnerOf($.physical.setName.prototype, $.physicals.Maximilian); $.physical.destroy = function destroy() { // TODO: add security check here!! // Remove from containment heirarchy. this.validate(); var contents = this.getContents(); for (var obj, i = 0; (obj = contents[i]); i++) { var dests = [this.location, obj.home, $.startRoom, null]; for (i in dests) { var dest = dests[i]; try { obj.moveTo(dest); break; } catch (e) { // Continue to try next dest. } } if (obj.location === this) obj.location = null; // Sorry if you didn't want to go there. } try { this.moveTo(null); } catch (e) { this.location.removeContents(this); } var origProto = Object.getPrototypeOf(this); // Note original protoype. Object.setPrototypeOf(this, $.garbage); // Make it a non-$.physical if ($.physicals[this.name] === this) delete $.physicals[this.name]; // Free up name. // Delete as much data as possible. var names = Object.getOwnPropertyNames(this); for (i = 0; i < names.length; i++) { delete this[names[i]]; } Object.setOwnerOf(this, null); // Try to remove from owner's quota. // Save original prototype, so that $.physical.validate can reparent // children of this object. (Ideally we'd do so now, but we can't // know which they are until we have an Object.getChildrenOf // function. this.proto = origProto; // Record original prototype. }; Object.setOwnerOf($.physical.destroy, $.physicals.Maximilian); Object.setOwnerOf($.physical.destroy.prototype, $.physicals.Maximilian); $.physical.rename = function rename(cmd) { try { var oldName = String(this); this.setName(cmd.iobjstr); cmd.user.narrate(oldName + ' renamed to ' + String(this)); } catch (e) { throw e.message; } }; Object.setOwnerOf($.physical.rename, $.physicals.Maximilian); Object.setOwnerOf($.physical.rename.prototype, $.physicals.Maximilian); $.physical.rename.verb = 'rename'; $.physical.rename.dobj = 'this'; $.physical.rename.prep = 'at/to'; $.physical.rename.iobj = 'any'; $.physical.destroyVerb = function destroyVerb(cmd) { // Safety checks. if (!cmd.dobj === this) throw 'Not sure what you want to destroy.'; var selector = $.Selector.for(this); if (selector && (selector[0] !== '$' || selector[1] !== 'physicals')) { throw String(this) + ' seems too well known: ' + selector.toString(); } var name = String(this); this.destroy(); cmd.user.narrate(name + ' destroyed.'); }; Object.setOwnerOf($.physical.destroyVerb, $.physicals.Maximilian); Object.setOwnerOf($.physical.destroyVerb.prototype, $.physicals.Maximilian); $.physical.destroyVerb.verb = 'destroy'; $.physical.destroyVerb.dobj = 'this'; $.physical.destroyVerb.prep = 'none'; $.physical.destroyVerb.iobj = 'none'; $.physical.home = null; $.physical.teleportTo = function teleport(dest, opt_neighbour) { /* Like moveTo, but with a bit more pizzazz. */ if (this.location === dest) return; if ($.physical.isPrototypeOf(this.location)) { this.location.narrate(String(this) + ' vanishes into thin air.', this); } this.moveTo(dest, opt_neighbour); if ($.physical.isPrototypeOf(this.location)) { this.location.narrate(String(this) + ' appears out of thin air.', this); } }; Object.setOwnerOf($.physical.teleportTo, $.physicals.Maximilian); Object.setOwnerOf($.physical.teleportTo.prototype, $.physicals.Maximilian); $.physical.describe = function describe(cmd) { this.description = cmd.iobjstr; cmd.user.narrate($.utils.string.capitalize(String(this)) + '\'s description set to "' + this.description + '".'); }; Object.setOwnerOf($.physical.describe, $.physicals.Maximilian); Object.setOwnerOf($.physical.describe.prototype, $.physicals.Maximilian); $.physical.describe.verb = 'describe'; $.physical.describe.dobj = 'this'; $.physical.describe.prep = 'as'; $.physical.describe.iobj = 'any'; $.physical.examine = function $_physical_examine(cmd) { var html = $.jssp.eval(this, 'examineJssp', {user: cmd.user}); cmd.user.readMemo({type: "html", htmlText: html}); }; Object.setOwnerOf($.physical.examine, $.physicals.Neil); Object.setOwnerOf($.physical.examine.prototype, $.physicals.Maximilian); $.physical.examine.verb = 'ex(amine)?'; $.physical.examine.dobj = 'this'; $.physical.examine.prep = 'none'; $.physical.examine.iobj = 'none'; $.physical.willMoveTo = function willMoveTo(dest) { /* Returns true iff this is willing to move to dest. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.) */ return false; }; Object.setOwnerOf($.physical.willMoveTo, $.physicals.Maximilian); Object.setOwnerOf($.physical.willMoveTo.prototype, $.physicals.Maximilian); $.physical.edit = function edit(cmd) { // Open this object in the code editor. var selector = $.Selector.for(this); if (!selector) { cmd.user.narrate('Unfortuantely the code editor does not know how to locate ' + String(this) + ' yet.'); return; } // No need to encode $. var query = encodeURIComponent(String(selector)).replace(/%24/g, '$'); var link = $.hosts.root.url('code') + '?' + query; cmd.user.readMemo({type: "link", href: link}); }; Object.setOwnerOf($.physical.edit, $.physicals.Maximilian); $.physical.edit.verb = 'edit'; $.physical.edit.dobj = 'this'; $.physical.edit.prep = 'none'; $.physical.edit.iobj = 'none'; $.physical.examineJssp = "

\n \n <%= $.utils.object.getValue(this, 'svgText') %>\n \n <%= $.utils.html.escape(String(this)) + $.utils.commandMenu(this.getCommands(request.user)) %>\n

\nYou can:\n
    \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 += ' <any>';\n }\n if (method.prep !== 'none') {\n command += ' ' + (method.prep === 'any' ? '<any>' : method.prep);\n if (method.iobj === 'this') {\n command += ' ' + this.name;\n } else if (method.iobj === 'any') {\n command += ' <any>';\n }\n }\n response.write('
  • ' + command + '
  • ');\n }\n%>\n
"; $.physicals['Physical object prototype'] = $.physical; $.utils.validate.physicals = function physicals(doSpider) { // First, make sure that $.physicals is plausible before we mess with it. var db = $.physicals; if (typeof db !== 'object' && Object.getPrototypeOf(db) === null) { throw new TypeError("$.physicals looks wrong"); } for (var name in db) { var obj = db[name]; if (!$.physical.isPrototypeOf(obj) && $.physical !== obj) { delete db[name]; continue; } if (obj.name !== name) { delete $.physicals[name]; obj.setName(obj.name, /*tryAlternative:*/ true); } } if (doSpider) { $.utils.object.spider($, function spiderPhysicals(obj) { if (!$.physical.isPrototypeOf(obj)) return false; // Skip, but don't prune. obj.setName(obj.name, /*tryAlternative:*/ true); }); } }; Object.setOwnerOf($.utils.validate.physicals, $.physicals.Maximilian); Object.setOwnerOf($.utils.validate.physicals.prototype, $.physicals.Maximilian); $.garbage = {}; $.garbage.toString = function toString() { return 'garbage'; }; Object.setOwnerOf($.garbage.toString, $.physicals.Maximilian); Object.setOwnerOf($.garbage.toString.prototype, $.physicals.Maximilian); $.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."; $.garbage.validate = function validate() { /* Fix the prototype of an object which now inherits from a * $.garbage object. * * Objects whose direct prototype is $.garbage are intentional * garbage and will not be resurrected in this way, but any other * descendents of $.garbage are assumed to be collateral damage from * $.physical.destroy and an effort is made to restore their * original prototype. This may involve walking the prototype * chain, if their direct prototype's prototype is not $.garbage. * * Once a direct descendent of $.garbage is found, that's object's * .proto property is used as th its direct child's new prototype. */ if (!$.garbage.isPrototypeOf(this)) { throw new TypeError('$.garbage.validate called on incompatible receiver'); } var obj = this; var proto = Object.getPrototypeOf(obj); while (true) { var grandProto = Object.getPrototypeOf(proto); if (grandProto === $.garbage) { if (proto.hasOwnProperty('proto')) { Object.setPrototypeOf(obj, proto.proto); // Revalidate. Only recursive in case of tiered garbage. this.validate(); } return; } obj = proto; proto = grandProto; } }; Object.setOwnerOf($.garbage.validate, $.physicals.Maximilian); Object.setOwnerOf($.garbage.validate.prototype, $.physicals.Maximilian); ================================================ FILE: core/core_33_world.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Generic physical object types for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.user = (new 'Object.create')($.physical); $.user.name = 'User prototype'; $.user.connection = null; $.user.svgText = ''; $.user.eval = function $_user_eval(cmd) { // Format: ;1+1 -or- eval 1+1 var src = (cmd.cmdstr[0] === ';') ? cmd.cmdstr.substring(1) : cmd.argstr; src = $.utils.code.rewriteForEval(src, /* forceExpression= */ false); // Do eval with this === this and vars me === this and here === this.location. var evalFunc = $_user_eval.doEval_.bind(this, this, this.location); var out = $.utils.code.eval(src, evalFunc); suspend(); cmd.user.narrate('⇒ ' + out); }; Object.setOwnerOf($.user.eval, $.physicals.Maximilian); $.user.eval.verb = 'eval|;.*'; $.user.eval.dobj = 'any'; $.user.eval.prep = 'any'; $.user.eval.iobj = 'any'; $.user.eval.doEval_ = function doEval_(me, here, $$$src) { // Execute eval in a scope with no variables. // The '$$$src' parameter is awkwardly-named so as not to collide with user // evaled code. The 'me' and 'here' parameters are exposed to the user. return eval($$$src); }; $.user.narrate = function narrate(text, obj) { var memo = {type: 'narrate', text: String(text)}; if (obj && obj.location) { memo.source = obj; memo.where = obj.location; } this.readMemo(memo); }; $.user.create = function create(cmd) { if ($.physical !== cmd.dobj && !$.physical.isPrototypeOf(cmd.dobj)) { cmd.user.narrate('Unknown prototype object.\n' + $.user.create.usage); return; } else if (!cmd.iobjstr) { cmd.user.narrate('Name must be specified.\n' + $.user.create.usage); return; } var obj = Object.create(cmd.dobj); Object.setOwnerOf(obj, cmd.user); obj.setName(cmd.iobjstr, /*tryAlternative:*/ true); cmd.user.narrate(String(obj) + ' created.'); try { obj.moveTo(cmd.user); } catch (e) { cmd.user.narrate(e.message); var selector = $.Selector.for(obj); if (selector) { cmd.user.narrate('It can be accessed as ' + String(selector)); } } }; Object.setOwnerOf($.user.create, $.physicals.Maximilian); $.user.create.usage = 'Usage: create as '; $.user.create.verb = 'create'; $.user.create.dobj = 'any'; $.user.create.prep = 'as'; $.user.create.iobj = 'any'; $.user.join = function join(cmd) { var name = cmd.dobjstr; var re = new RegExp('^' + name, 'i'); var who = null; for (var key in $.physicals) { var obj = $.physicals[key]; if (!$.user.isPrototypeOf(obj)) continue; if (String(obj).match(re)) { who = obj; break; } } if (!who) { cmd.user.narrate('Can\'t find a user named "' + name + '".'); return; } cmd.user.narrate('You join ' + String(who) + '.'); this.teleportTo(who.location); }; Object.setOwnerOf($.user.join, $.physicals.Maximilian); $.user.join.verb = 'join'; $.user.join.dobj = 'any'; $.user.join.prep = 'none'; $.user.join.iobj = 'none'; $.user.quit = function quit(cmd) { if (this.connection) { this.connection.close(); } }; Object.setOwnerOf($.user.quit, $.physicals.Maximilian); $.user.quit.verb = 'quit'; $.user.quit.dobj = 'none'; $.user.quit.prep = 'none'; $.user.quit.iobj = 'none'; $.user.willAccept = function willAccept(what, src) { /* Returns true iff this is willing to accept what arriving from src. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.). */ return $.thing.isPrototypeOf(what); }; Object.setOwnerOf($.user.willAccept, $.physicals.Maximilian); Object.setOwnerOf($.user.willAccept.prototype, $.physicals.Maximilian); $.user.moveTo = function moveTo(dest, opt_neighbour) { var r = $.physical.moveTo.call(this, dest, opt_neighbour); if (this.location === null) { // Show null scene. var memo = { type: 'scene', requested: true, user: this, where: 'The null void', description: "You have somehow ended up nowhere at all.\n(Type 'home' to go home.)", svgText: this.getNullSvgText(), contents: [] }; this.readMemo(memo); } return r; }; Object.setOwnerOf($.user.moveTo, $.physicals.Maximilian); Object.setOwnerOf($.user.moveTo.prototype, $.physicals.Maximilian); $.user.getNullSvgText = function getNullSvgText() { /* Return an SVG text for the null void (i.e., what * a user sees if they're .location is null). */ // Draw a double spiral on a black background. // TODO(cpcallen): make spiral curved, rather than angular. var out = []; out.push('\n'); for (var i = 0; i < 2; i++) { var vx = 0; var vy = Math.pow(-1, i); out.push('\n'); } return out.join(''); }; Object.setOwnerOf($.user.getNullSvgText, $.physicals.Maximilian); $.user.getCommands = function getCommands(who) { var commands = $.physical.getCommands.apply(this, arguments); if (who.location !== this.location) { commands.push('join ' + this.name); } return commands; }; Object.setOwnerOf($.user.getCommands, $.physicals.Maximilian); Object.setOwnerOf($.user.getCommands.prototype, $.physicals.Maximilian); $.user.who = function who(cmd) { $.console.look({user: cmd.user}); }; Object.setOwnerOf($.user.who, $.physicals.Maximilian); $.user.who.verb = 'w(ho)?'; $.user.who.dobj = 'none'; $.user.who.prep = 'none'; $.user.who.iobj = 'none'; $.user.onInput = function onInput(command) { // Process one line of input from the user. // TODO(cpcallen): add security checks! try { $.utils.command.execute(command.trim(), this); } catch (e) { suspend(); this.narrate(String(e)); if (e instanceof Error) this.narrate(e.stack); } }; Object.setOwnerOf($.user.onInput, $.physicals.Maximilian); $.user.grep = function grep(cmd) { try { var selector = new $.Selector(cmd.dobjstr); } catch (e) { throw 'Invalid selector ' + cmd.dobjstr; } if (!cmd.iobjstr) throw 'What do you want to search for?'; this.grep.search(cmd.user, selector.toString(), cmd.iobjstr, selector, new WeakMap()); cmd.user.narrate('Grep complete.'); }; Object.setOwnerOf($.user.grep, $.physicals.Maximilian); $.user.grep.verb = 'grep'; $.user.grep.dobj = 'any'; $.user.grep.prep = 'for/about'; $.user.grep.iobj = 'any'; $.user.grep.search = function search(user, prefix, searchString, selector, seen) { var value = selector.toValue(); if (!$.utils.isObject(value)) { // value is a primitive. if (String(value).includes(searchString)) { var formatted = $.utils.code.expressionFor(value); if (typeof value === 'string' && formatted.length > 60) { // Print only extracts of long string values. formatted = formatted.slice(1, -1); // Remove quotation marks. var re = new RegExp('.{0,20}' + $.utils.regexp.escape(searchString) + '.{0,20}', 'g'); var m; while ((m = re.exec(formatted))) { user.narrate(selector.toString() + ' includes' + ' ...' + m[0] + '...'); } } else { user.narrate(selector.toString() + ' === ' + formatted); } } return; } // Prune search when we wander into objects with canonical Selectors // not starting with prefix. Otherwise, use canonical Selector. var canonical = $.Selector.for(value); if (canonical) { if (canonical.toString().indexOf(prefix) !== 0) return; selector = canonical; } // Have we seen it before? if (seen.has(value)) return; seen.set(value, true); // Is it a function containing the search string? if (typeof value === 'function') { var text = Function.prototype.toString.call(value); if (text.includes(searchString)) { user.narrate(selector.toString() + ' mentions ' + searchString + ':'); var lines = text.split('\n'); for (var i = 0; i < lines.length; i++) { if (lines[i].includes(searchString)) { user.narrate(' line ' + (i + 1) + ': ' + lines[i]); } } } } // Check key names var keys = Object.getOwnPropertyNames(value); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var subSelector = new $.Selector(selector.concat(key)); if (key.includes(searchString)) { user.narrate(subSelector.toString() + ' exists.'); } if (key === 'cache_') { user.narrate('Skipping ' + subSelector.toString()); continue; } while (true) { try { search(user, prefix, searchString, subSelector, seen); break; } catch (e) { suspend(); if (!(e instanceof RangeError) || e.message !== 'Thread ran too long') throw e; } } } }; Object.setOwnerOf($.user.grep.search, $.physicals.Maximilian); $.user.readMemo = function readMemo(memo) { // See $.physical.readMemo for documentation. $.physical.readMemo.call(this, memo); if (!this.connection) return; memo = $.utils.replacePhysicalsWithName(memo); var json = JSON.stringify(memo) + '\n'; try { this.connection.write(json); } catch(e) { if (e.message === 'object is not connected') { this.connection = null; } else { throw e; } } }; $.user.destroyVerb = function destroyVerb(cmd) { // DO NOT MAKE SUPER CALL! if (cmd.user === this) { throw 'You can reach the National Suicide Prevention Lifeline at 1-800-273-8255.'; } throw 'You are not allowed to destroy other users.'; }; Object.setOwnerOf($.user.destroyVerb, $.physicals.Maximilian); $.user.destroyVerb.usage = 'Usage: destroy '; $.user.destroyVerb.verb = 'destroy'; $.user.destroyVerb.dobj = 'this'; $.user.destroyVerb.prep = 'none'; $.user.destroyVerb.iobj = 'none'; $.user.homeVerb = function homeVerb(cmd) { var home = cmd.user.home || $.startRoom; if (cmd.user.location === home) { cmd.user.narrate('You are already at home.'); return; } cmd.user.narrate('You go home.'); cmd.user.teleportTo(home); }; Object.setOwnerOf($.user.homeVerb, $.physicals.Maximilian); $.user.homeVerb.verb = 'home'; $.user.homeVerb.dobj = 'none'; $.user.homeVerb.prep = 'none'; $.user.homeVerb.iobj = 'none'; $.user.teleportTo = function teleportTo(dest, opt_neighbour) { if (this.location === dest) { this.narrate("You're already in " + String(dest) + ".") return; } $.physical.teleportTo.call(this, dest, opt_neighbour); }; Object.setOwnerOf($.user.teleportTo, $.physicals.Maximilian); Object.setOwnerOf($.user.teleportTo.prototype, $.physicals.Maximilian); $.user.go = function go(cmd) { var dest = null; if ($.room.isPrototypeOf(cmd.iobj)) { dest = cmd.iobj; } else if (!cmd.iobjstr) { throw 'Usage: go to '; } else { var re = new RegExp(cmd.iobjstr, 'i'); // TODO: find best match, not just first match? for (var name in $.physicals) { if (name.match(re) && $.room.isPrototypeOf($.physicals[name])) { dest = $.physicals[name]; break; } } } if (dest) { this.teleportTo(dest); } else { throw 'There is no room named ' + cmd.iobjstr + '.'; } }; Object.setOwnerOf($.user.go, $.physicals.Maximilian); Object.setOwnerOf($.user.go.prototype, $.physicals.Maximilian); $.user.go.verb = 'go'; $.user.go.dobj = 'none'; $.user.go.prep = 'at/to'; $.user.go.iobj = 'any'; $.user.onConnect = function onConnect(reconnect) { /* Called from $.servers.telnet.connection.onReceiveLine once a new * connection is logged in to this user. Argument will be true if * user was already connected (and this is just a reconnection). */ if ($.room.isPrototypeOf(this.location)) { this.location.narrate( String(this) + (reconnect ? ' startles awake.' : ' wakes up.'), this); this.onInput('look'); } else { this.teleportTo(this.home || $.startRoom); } if (this.name.match(/^Guest/)) { this.narrate( 'Welcome to Code City.\n' + "If you're planning to hang around, why not give your self a\n" + 'name by typing "rename me to " in the box below.'); } }; Object.setOwnerOf($.user.onConnect, $.physicals.Maximilian); Object.setOwnerOf($.user.onConnect.prototype, $.physicals.Maximilian); $.user.onDisconnect = function onDisconnect() { /* Called from $.servers.telnet.connection.onEnd once connection * has dropped. */ // Have they made an effort to not look like a guest? if (this.hasOwnProperty('description') || this.hasOwnProperty('home') || !this.name.match(/^Guest(?: #\d+)?/) || Object.getOwnPropertyNames(this).length > 5) { // Not a guest. if (this.location) { this.location.narrate(String(this) + ' nods off to sleep.', this); } } else { // Pretty guest-y. if (this.location) { this.location.narrate(String(this) + ' suddenly vanishes without a trace!'); } this.destroy(); } }; Object.setOwnerOf($.user.onDisconnect, $.physicals.Maximilian); Object.setOwnerOf($.user.onDisconnect.prototype, $.physicals.Maximilian); $.user.description = 'A new user who has not yet set his/her description.'; $.user.destroy = function destroy() { $.physical.destroy.call(this); // Make sure next login gets a fresh guest. suspend(); $.userDatabase.validate(); }; Object.setOwnerOf($.user.destroy, $.physicals.Maximilian); Object.setOwnerOf($.user.destroy.prototype, $.physicals.Maximilian); $.user.inventory = function inventory(cmd) { this.look(cmd); }; Object.setOwnerOf($.user.inventory, $.physicals.Neil); Object.setOwnerOf($.user.inventory.prototype, $.physicals.Maximilian); $.user.inventory.verb = 'inv(entory)?'; $.user.inventory.dobj = 'none'; $.user.inventory.prep = 'none'; $.user.inventory.iobj = 'none'; $.user.willMoveTo = function willMoveTo(dest) { /* Returns true iff this is willing to move to dest. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.) */ // Users should in general always be in a room. return $.room.isPrototypeOf(dest); }; Object.setOwnerOf($.user.willMoveTo, $.physicals.Maximilian); Object.setOwnerOf($.user.willMoveTo.prototype, $.physicals.Maximilian); $.user.inlineEdit = function inlineEdit(cmd) { var obj = cmd.iobj; var objName = cmd.iobjstr; var prop = cmd.dobjstr; if (!$.utils.isObject(obj) || !prop) { cmd.user.narrate('Usage: edit on '); return; } var url = $.hosts.code['/inlineEdit'].edit(obj, objName, prop); var memo = { type: 'iframe', url: url, alt: 'Edit ' + prop + ' on ' + objName }; cmd.user.readMemo(memo); }; Object.setOwnerOf($.user.inlineEdit, $.physicals.Maximilian); $.user.inlineEdit.verb = 'edit'; $.user.inlineEdit.dobj = 'any'; $.user.inlineEdit.prep = 'on top of/on/onto/upon'; $.user.inlineEdit.iobj = 'any'; $.user.describe = function describe(cmd) { if (typeof this.description === 'function') { cmd.user.narrate("Can't set description since it is a function."); return; } this.description = cmd.iobjstr; cmd.user.narrate($.utils.string.capitalize(String(this)) + '\'s description set to "' + this.description + '".'); }; Object.setOwnerOf($.user.describe, $.physicals.Neil); Object.setOwnerOf($.user.describe.prototype, $.physicals.Neil); $.user.describe.verb = 'describe'; $.user.describe.dobj = 'this'; $.user.describe.prep = 'as'; $.user.describe.iobj = 'any'; $.user.lookJssp = "\n \n \n \n \n
\n \n <%= $.utils.object.getValue(this, 'svgText') %>\n \n \n

<%: this %><%= $.utils.commandMenu(this.getCommands(request.user)) %>

\n

<%= $.utils.html.preserveWhitespace($.utils.object.getValue(this, 'description')) %>
\n <%: String(this) + (this.connection && this.connection.connected ? ' is awake.' : ' is sleeping.') %>

\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('

Contents: ' + contentsHtml.join(', ') + '

');\n}\nif (this.location) {\n response.write('

Location: ' + $.utils.html.escape(this.location.name) +\n $.utils.commandMenu(this.location.getCommands(request.user)) + '

');\n}\n%>\n
"; $.room = (new 'Object.create')($.physical); $.room.name = 'Room prototype'; $.room.svgText = ''; $.room.sendScene = function sendScene(who, requested) { var memo = { type: 'scene', requested: requested, user: who, where: this, description: $.utils.object.getValue(this, 'description'), svgText: $.utils.object.getValue(this, 'svgText'), contents: [] }; var contents = this.getContents(); for (var i = 0; i < contents.length; i++) { var object = contents[i]; memo.contents.push({ type: $.user.isPrototypeOf(object) ? 'user' : 'thing', what: object, svgText: $.utils.object.getValue(object, 'svgText'), cmds: object.getCommands(who) }); } who.readMemo(memo); }; Object.setOwnerOf($.room.sendScene, $.physicals.Neil); $.room.look = function look(cmd) { this.sendScene(cmd.user, true); }; Object.setOwnerOf($.room.look, $.physicals.Maximilian); $.room.look.verb = 'l(ook)?'; $.room.look.dobj = 'this'; $.room.look.prep = 'none'; $.room.look.iobj = 'none'; $.room.say = function say(cmd) { // Format: "Hello. -or- say Hello. var text = (cmd.cmdstr[0] === '"') ? cmd.cmdstr.substring(1) : cmd.argstr; var lastLetter = text.trim().slice(-1); var type = (lastLetter === '?') ? 1 : ((lastLetter === '!') ? 2 : 0); var verb = [['say', 'says'], ['ask', 'asks'], ['exclaim', 'exclaims']][type]; var altMe = 'You ' + verb[0] + ', "' + text + '"'; var altOthers = cmd.user + ' ' + verb[1] + ', "' + text + '"'; var memo = { type: 'say', source: cmd.user, where: this, text: text, alt: altMe }; cmd.user.readMemo(memo); memo.alt = altOthers; this.sendMemo(memo, cmd.user); }; Object.setOwnerOf($.room.say, $.physicals.Maximilian); $.room.say.verb = 'say?|".*'; $.room.say.dobj = 'any'; $.room.say.prep = 'any'; $.room.say.iobj = 'any'; $.room.think = function think(cmd) { var text = cmd.argstr; var altMe = 'You think, "' + text + '"'; var altOthers = cmd.user + ' thinks, "' + text + '"'; var memo = { type: "think", source: cmd.user, where: this, text: text, alt: altMe }; cmd.user.readMemo(memo); memo.alt = altOthers; this.sendMemo(memo, cmd.user); }; Object.setOwnerOf($.room.think, $.physicals.Neil); $.room.think.verb = 'think|.oO'; $.room.think.dobj = 'any'; $.room.think.prep = 'any'; $.room.think.iobj = 'any'; $.room.narrate = function narrate(text, except, obj) { /* Send narration text to the contents of the room. * * text is the contents of the narration. * * except is an individual $.physical object, or an array of such, * which should not receive the narration. * * obj, if specified, will cause the narration to have a speech- * -bubble style arrow pointing at the specified object, * provided that object is in the room. */ var contents = this.getContents(); for (var i = 0; i < contents.length; i++) { var thing = contents[i]; if (thing !== except && !(except && except.includes && except.includes(thing)) && thing.narrate) { thing.narrate(text, obj); } } }; Object.setOwnerOf($.room.narrate, $.physicals.Maximilian); $.room.willAccept = function willAccept(what, src) { /* Returns true iff this is willing to accept what arriving from src. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.). */ return $.thing.isPrototypeOf(what) || $.user.isPrototypeOf(what); }; Object.setOwnerOf($.room.willAccept, $.physicals.Maximilian); $.room.onEnter = function onEnter(what, src) { // TODO: caller check: should only be called by $.physical.moveTo. $.physical.validate.call(this); this.updateScene(false); if ($.user.isPrototypeOf(what)) { this.sendScene(what, true); } }; Object.setOwnerOf($.room.onEnter, $.physicals.Neil); $.room.onExit = function onExit(what, dest) { // TODO: caller check: should only be called by $.physical.moveTo. suspend(0); // Wait for what to actually leave. $.physical.validate.call(this); this.updateScene(false); }; Object.setOwnerOf($.room.onExit, $.physicals.Neil); $.room.lookHere = function lookHere(cmd) { return this.look(cmd); }; $.room.lookHere.verb = 'l(ook)?'; $.room.lookHere.dobj = 'none'; $.room.lookHere.prep = 'none'; $.room.lookHere.iobj = 'none'; $.room.location = null; $.room.contents_ = []; $.room.contents_.forObj = $.room; Object.defineProperty($.room.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.room.contents_.forKey = 'contents_'; Object.defineProperty($.room.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.room.sendMemo = function sendMemo(memo, except) { /* Send a memo to most or all objects in this room. * - memo: the memo to be sent. * - except: an individual $.physical object, or an array of such, * which should not receive the memo. */ var contents = this.getContents(); for (var i = 0; i < contents.length; i++) { var thing = contents[i]; if (thing === except || except && except.includes && except.includes(thing)) { continue; } thing.readMemo(memo); } }; Object.setOwnerOf($.room.sendMemo, $.physicals.Maximilian); $.room.emote = function emote(cmd) { // Format: :blinks.. -or- ::'s ears twitch. var m, action; if (cmd.verbstr === 'emote') { action = String(cmd.user) + ' ' + cmd.argstr; } else if ((m = /^:(:?)([^:]+)$/.exec(cmd.cmdstr))) { var space = (m[1] === '') ? ' ' : ''; var text = m[2].trim(); action = String(cmd.user) + space + text; } else { cmd.user.narrate('Try ":blinks." or "::\'s ears twitch."'); return } cmd.user.location.narrate(action); }; Object.setOwnerOf($.room.emote, $.physicals.Maximilian); Object.setOwnerOf($.room.emote.prototype, $.physicals.Maximilian); $.room.emote.verb = '::?[^:]+'; $.room.emote.dobj = 'any'; $.room.emote.prep = 'any'; $.room.emote.iobj = 'any'; $.room.updateScene = function updateScene(force) { var contents = this.getContents(); for (var i = 0, who; (who = contents[i]); i++) { if ($.user.isPrototypeOf(who)) { this.sendScene(who, force); } } }; Object.setOwnerOf($.room.updateScene, $.physicals.Neil); Object.setOwnerOf($.room.updateScene.prototype, $.physicals.Neil); $.thing = (new 'Object.create')($.physical); $.thing.name = 'Thing prototype'; $.thing.svgText = ''; $.thing.get = function get(cmd) { if (this.location !== cmd.user.location) { cmd.user.narrate("You can't reach " + this.name + "."); return; } try { this.moveTo(cmd.user); } catch (e) { throw (e instanceof Error) ? e.message : e; } cmd.user.narrate('You pick up ' + this.name + '.'); if (cmd.user.location) { cmd.user.location.narrate(cmd.user.name + ' picks up ' + this.name + '.', cmd.user); } }; Object.setOwnerOf($.thing.get, $.physicals.Maximilian); $.thing.get.verb = 'get|take'; $.thing.get.dobj = 'this'; $.thing.get.prep = 'none'; $.thing.get.iobj = 'none'; $.thing.drop = function drop(cmd) { if (this.location !== cmd.user) { cmd.user.narrate("You can't drop something you're not holding."); return; } try { this.moveTo(cmd.user.location); } catch (e) { throw (e instanceof Error) ? e.message : e; } cmd.user.narrate('You drop ' + this.name + '.'); if (cmd.user.location) { cmd.user.location.narrate(cmd.user.name + ' drops ' + this.name + '.', cmd.user); } }; Object.setOwnerOf($.thing.drop, $.physicals.Maximilian); $.thing.drop.verb = 'drop|throw'; $.thing.drop.dobj = 'this'; $.thing.drop.prep = 'none'; $.thing.drop.iobj = 'none'; $.thing.give = function give(cmd) { if (this.location !== cmd.user && this.location !== cmd.user.location) { cmd.user.narrate("You can't reach " + String(this) + "."); return; } try { this.moveTo(cmd.iobj); } catch (e) { throw (e instanceof Error) ? e.message : e; } cmd.user.narrate('You give ' + String(this) + ' to ' + String(cmd.iobj) + '.'); cmd.iobj.narrate(String(cmd.user) + ' gives ' + String(this) + ' to you.'); if (cmd.user.location) { cmd.user.location.narrate( String(cmd.user) + ' gives ' + String(this) + ' to ' + String(cmd.iobj) + '.', [cmd.user, cmd.iobj]); } }; Object.setOwnerOf($.thing.give, $.physicals.Maximilian); Object.setOwnerOf($.thing.give.prototype, $.physicals.Maximilian); $.thing.give.verb = 'give'; $.thing.give.dobj = 'this'; $.thing.give.prep = 'at/to'; $.thing.give.iobj = 'any'; $.thing.getCommands = function getCommands(who) { var commands = $.physical.getCommands.call(this, who); if (this.location === who) { commands.push('drop ' + this.name); } else if (this.location === who.location) { commands.push('get ' + this.name); } return commands; }; Object.setOwnerOf($.thing.getCommands, $.physicals.Neil); Object.setOwnerOf($.thing.getCommands.prototype, $.physicals.Maximilian); $.thing.movable = true; $.thing.location = null; $.thing.contents_ = []; $.thing.contents_.forObj = $.thing; Object.defineProperty($.thing.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.thing.contents_.forKey = 'contents_'; Object.defineProperty($.thing.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.thing.willMoveTo = function willMoveTo(dest) { /* Returns true iff this is willing to move to dest. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.) */ return Boolean(this.movable); }; Object.setOwnerOf($.thing.willMoveTo, $.physicals.Maximilian); Object.setOwnerOf($.thing.willMoveTo.prototype, $.physicals.Maximilian); $.container = (new 'Object.create')($.thing); $.container.getFrom = function getFrom(cmd) { var thing = cmd.dobj; if ($.utils.command.matchFailed(thing)) { thing = $.utils.command.match(cmd.dobjstr, this); } if ($.utils.command.matchFailed(thing, cmd.dobjstr, cmd.user)) return; if (!this.isOpen) { cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is closed.'); return; } if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is not here.'); return; } if (thing.location !== this) { cmd.user.narrate($.utils.string.capitalize(String(thing)) + ' is not in ' + String(this) + '.'); return; } try { thing.moveTo(this.toFloor ? this.location : cmd.user); } catch (e) { cmd.user.narrate(e.message); return; } cmd.user.narrate('You take ' + String(thing) + ' from ' + String(this) + '.'); if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' takes ' + String(thing) + ' from ' + String(this) + '.', cmd.user); } }; Object.setOwnerOf($.container.getFrom, $.physicals.Neil); $.container.getFrom.verb = 'get|take'; $.container.getFrom.dobj = 'any'; $.container.getFrom.prep = 'out of/from inside/from'; $.container.getFrom.iobj = 'this'; $.container.name = 'Container prototype'; $.container.svgTextOpen = '\n\n\n\n'; $.container.svgTextClosed = '\n\n'; $.container.isOpen = true; $.container.open = function open(cmd) { if (this.isOpen) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.'); return; } if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.'); return; } if (!this.setOpen(true)) { cmd.user.narrate('You can\'t open ' + String(cmd.dobj)); return; } if (cmd.user.location) { cmd.user.location.narrate(cmd.user.name + ' opens ' + String(cmd.dobj) + '.', cmd.user); } cmd.user.narrate('You open ' + String(cmd.dobj) + '.'); this.look(cmd); }; Object.setOwnerOf($.container.open, $.physicals.Maximilian); Object.setOwnerOf($.container.open.prototype, $.physicals.Maximilian); $.container.open.verb = 'open'; $.container.open.dobj = 'this'; $.container.open.prep = 'none'; $.container.open.iobj = 'none'; $.container.close = function close(cmd) { if (!this.isOpen) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already closed.'); return; } if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.'); return; } if (!this.setOpen(false)) { cmd.user.narrate('You can\'t close ' + String(cmd.dobj)); return; } if (cmd.user.location) { cmd.user.location.narrate(cmd.user.name + ' closes ' + String(cmd.dobj) + '.', cmd.user); cmd.user.location.sendScene(cmd.user, false); } else { this.look(); } cmd.user.narrate('You close ' + String(cmd.dobj) + '.'); }; $.container.close.verb = 'close'; $.container.close.dobj = 'this'; $.container.close.prep = 'none'; $.container.close.iobj = 'none'; $.container.setOpen = function setOpen(newState) { this.isOpen = Boolean(newState); if ($.room.isPrototypeOf(this.location)) { this.location.updateScene(false); } return true; }; Object.setOwnerOf($.container.setOpen, $.physicals.Maximilian); Object.setOwnerOf($.container.setOpen.prototype, $.physicals.Maximilian); $.container.getCommands = function getCommands(who) { var commands = $.thing.getCommands.call(this, who); if (this.isOpen) { commands.push('close ' + String(this)); } else { commands.push('open ' + String(this)); } return commands; }; Object.setOwnerOf($.container.getCommands, $.physicals.Maximilian); Object.setOwnerOf($.container.getCommands.prototype, $.physicals.Maximilian); $.container.putIn = function putIn(cmd) { if ($.utils.command.matchFailed(cmd.dobj, cmd.dobjstr, cmd.user)) return; var thing = cmd.dobj; if (!this.isOpen) { cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is closed.'); return; } if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is not here.'); return; } if (thing.location !== cmd.user.location && thing.location !== cmd.user) { cmd.user.narrate('You do not have ' + String(thing) + '.'); return; } try { thing.moveTo(this); } catch (e) { cmd.user.narrate(e.message); return; } cmd.user.narrate('You put ' + String(thing) + ' in ' + String(this) + '.'); if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' puts ' + String(thing) + ' in ' + String(this) + '.', cmd.user); } }; Object.setOwnerOf($.container.putIn, $.physicals.Maximilian); $.container.putIn.verb = 'put'; $.container.putIn.dobj = 'any'; $.container.putIn.prep = 'in/inside/into'; $.container.putIn.iobj = 'this'; $.container.willAccept = function willAccept(what, src) { /* Returns true iff this is willing to accept what arriving from src. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.) */ return this.isOpen && $.thing.isPrototypeOf(what); }; Object.setOwnerOf($.container.willAccept, $.physicals.Maximilian); Object.setOwnerOf($.container.willAccept.prototype, $.physicals.Maximilian); $.container.location = null; $.container.contents_ = []; $.container.contents_.forObj = $.container; Object.defineProperty($.container.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.container.contents_.forKey = 'contents_'; Object.defineProperty($.container.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.container.contentsVisibleWhenOpen = true; $.container.contentsVisibleWhenClosed = false; $.container.lookJssp = "\n \n \n \n \n
\n \n <%= $.utils.object.getValue(this, 'svgText') %>\n \n \n

<%: this %><%= $.utils.commandMenu(this.getCommands(request.user)) %>

\n

<%= $.utils.html.preserveWhitespace($.utils.object.getValue(this, 'description')) %>

\n

It is <%= this.isOpen ? 'open' : 'closed' %>.

\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('

Contents: ' + contentsHtml.join(', ') + '

');\n }\n}\nif (this.location) {\n response.write('

Location: ' + $.utils.html.escape(this.location.name) +\n $.utils.commandMenu(this.location.getCommands(request.user)) + '

');\n}\n%>\n
"; $.container.lookIn = function lookIn(cmd) { var thing = cmd.dobj if ($.utils.command.matchFailed(thing)) { thing = $.utils.command.match(cmd.dobjstr, this); } if ($.utils.command.matchFailed(thing, cmd.dobjstr, cmd.user)) return; if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is not here.'); return; } if (thing.location !== this) { cmd.user.narrate($.utils.string.capitalize(String(thing)) + ' is not in ' + String(this) + '.'); return; } if (this.isOpen) { if (!this.contentsVisibleWhenOpen) { cmd.user.narrate('You can\'t see inside ' + String(this) + '.'); return; } } else { if (!this.contentsVisibleWhenClosed) { cmd.user.narrate($.utils.string.capitalize(String(this)) + ' is closed.'); return; } } var html = thing.lookJssp.toString(thing, {user: cmd.user}); cmd.user.readMemo({type: "html", htmlText: html}); }; Object.setOwnerOf($.container.lookIn, $.physicals.Neil); Object.setOwnerOf($.container.lookIn.prototype, $.physicals.Neil); $.container.lookIn.verb = 'l(ook)?'; $.container.lookIn.dobj = 'any'; $.container.lookIn.prep = 'in/inside/into'; $.container.lookIn.iobj = 'this'; $.container.toFloor = false; $.container.svgText = function svgText() { return this.isOpen ? this.svgTextOpen : this.svgTextClosed; }; Object.setOwnerOf($.container.svgText, $.physicals.Neil); Object.setOwnerOf($.container.svgText.prototype, $.physicals.Maximilian); $.physicals['User prototype'] = $.user; $.physicals['Room prototype'] = $.room; $.physicals['Thing prototype'] = $.thing; $.physicals['Container prototype'] = $.container; ================================================ FILE: core/core_34_$.servers.login.js ================================================ /** * @license * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Login service backend server for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.servers.login = {}; Object.setOwnerOf($.servers.login, $.physicals.Neil); $.servers.login.connection = (new 'Object.create')($.connection); $.servers.login.connection.onReceiveLine = function onReceiveLine(line) { line = line.trim(); try { var loginData = JSON.parse(line); var cookie = $.servers.login.getCookie(loginData); this.write(cookie); } catch (err) { // Just log error. suspend(); $.system.log('$.servers.login: ' + String(err)); } finally { suspend(); this.close(); } }; Object.setOwnerOf($.servers.login.connection.onReceiveLine, $.physicals.Maximilian); Object.setOwnerOf($.servers.login.connection.onReceiveLine.prototype, $.physicals.Neil); $.servers.login.getCookie = function getCookie(loginData) { /* Get the ID cookie for the given loginData. * * Arguments: * - loginData: !Object - the loginData object from loginServer. * Returns: string - the ID cookie to set. Empty string denotes * invalid login. */ var id = loginData.id; if (typeof(id) !== 'string') { return ''; } else if ($.userDatabase.get(id)) { // User already exists. return id; } else { // Create new user object. var name = loginData.given_name || loginData.name || loginData.email && loginData.email.replace(/@.*$/, ''); this.createUser(id, name); return id; } }; Object.setOwnerOf($.servers.login.getCookie, $.physicals.Maximilian); Object.setOwnerOf($.servers.login.getCookie.prototype, $.physicals.Maximilian); $.servers.login.createUser = function createUser(id, name) { /* Create a $.user object for the given id. * * Arguments: * - id: string - the ID cookie for the given user. * - name?: string - the name for the new user. Default: 'Guest'. * Returns: Object - the new $.user object */ if ($.userDatabase.get(id)) throw new TypeError('user already exists'); // Create new $.user. var user = Object.create($.user); user.setName(name || 'Guest', /*tryAlternative:*/ true); $.userDatabase.set(id, user); /* (function() { setPerms(user); var home = Object.create($.room); home.setName(user.name + "'s room", true); home.description = 'A quiet place for ' + user.name + ' to work.'; user.home = home; user.moveTo(home); })(); */ return user; }; Object.setOwnerOf($.servers.login.createUser, $.physicals.Maximilian); Object.setOwnerOf($.servers.login.createUser.prototype, $.physicals.Maximilian); ================================================ FILE: core/core_34_$.servers.telnet.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Telnet server for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.servers.telnet = {}; $.servers.telnet.connection = (new 'Object.create')($.connection); $.servers.telnet.connection.onReceiveLine = function onReceiveLine(text) { if (this.user) { // Logged in? // Set 'user' for this thread, and permissions for call Object.setOwnerOf(Thread.current(), this.user); setPerms(this.user); this.user.onInput(text); return; } // Remainder of function handles login. // TODO(fraser): Make sure that no security issues exist due to // called code suspending or timing out unexpectedly. var m = text.match(/identify as ([0-9a-f]+)/); if (!m) { this.write('{type: "narrate", text: "Unknown command: ' + $.utils.html.preserveWhitespace(text) + '"}'); return; } var id = m[1]; var user = $.userDatabase.get(id) || $.servers.login.createUser(id); this.user = user; var rebind = false; if (user.connection) { rebind = true; try { user.connection.close(); } catch (e) { // Ignore; maybe connection already closed (e.g., due to crash/reboot). } $.system.log('Rebinding connection to ' + user.name); } else { $.system.log('Binding connection to ' + user.name); } user.connection = this; Object.setOwnerOf(Thread.current(), user); setPerms(this.user); new Thread(user.onConnect, 0, user, rebind); }; Object.setOwnerOf($.servers.telnet.connection.onReceiveLine, $.physicals.Maximilian); $.servers.telnet.connection.onEnd = function onEnd() { var user = this.user; // Mark connection as closed. $.connection.onEnd.call(this); if (user) { // Unbind connection from user. this.user = null; if (user.connection === this) { user.connection = null; $.system.log('Unbinding connection from ' + user.name); (function () { setPerms(user); new Thread(user.onDisconnect, 0, user); })(); } } // Remove this and any other closed / debound connections from array of open connections. $.servers.telnet.validate(); }; Object.setOwnerOf($.servers.telnet.connection.onEnd, $.physicals.Maximilian); $.servers.telnet.connection.onConnect = function onConnect() { // super call. Records .connectTime (as number of ms since epoch). $.connection.onConnect.apply(this, arguments); // Add this connection to list of active telnet connections. $.servers.telnet.connected.push(this); setTimeout((function onConnect_timeout() { if (!this.user) this.close(); }).bind(this), $.servers.telnet.LOGIN_TIMEOUT_MS); }; Object.setOwnerOf($.servers.telnet.connection.onConnect, $.physicals.Maximilian); Object.setOwnerOf($.servers.telnet.connection.onConnect.prototype, $.physicals.Maximilian); $.servers.telnet.validate = function validate() { // Examine supposedly-open connections and close and/or remove // closed / timed-out / debound ones from the .connected arary. var limit = Date.now() - this.LOGIN_TIMEOUT_MS; this.connected = this.connected.filter(function(c) { // Close any connections that haven't logged in promptly. if (!c.user && c.connectTime < limit) { try { // Call .close(). Note that that this won't result in the // object's .connected property being set to false // immediately, but only after an async callback to // connection.onEnd() - which will result in another call // to $.servers.telnet.validate(). c.close(); } catch (e) { // Connection was already closed. Mark it as such. c.connected = false; } } return c.connected && (!c.user || c.user.connection === c); }); }; Object.setOwnerOf($.servers.telnet.validate, $.physicals.Maximilian); Object.setOwnerOf($.servers.telnet.validate.prototype, $.physicals.Maximilian); $.servers.telnet.LOGIN_TIMEOUT_MS = 20000; $.servers.telnet.connected = []; ================================================ FILE: core/core_40_$.startRoom.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Initial starting room for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.startRoom = (new 'Object.create')($.room); $.startRoom.location = null; $.startRoom.contents_ = []; $.startRoom.contents_.forObj = $.startRoom; Object.defineProperty($.startRoom.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.startRoom.contents_.forKey = 'contents_'; Object.defineProperty($.startRoom.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.startRoom.name = 'Hangout'; $.startRoom.description = 'A place to hang out, chat, and program.'; $.startRoom.roll = function roll(cmd) { var memo = { type: 'iframe', url: 'https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1' }; this.sendMemo(memo); }; $.startRoom.roll.verb = 'roll'; $.startRoom.roll.dobj = 'none'; $.startRoom.roll.prep = 'none'; $.startRoom.roll.iobj = 'none'; $.clock = (new 'Object.create')($.thing); $.clock.name = 'clock'; $.clock.location = $.startRoom; $.clock.chime = function chime(silent) { // Chiming only. Timer management all handled by .onTimeout. var hours = (new Date().getHours() %12) || 12; var text = []; for (var i = 0; i < hours; i++) { text.push('Bong.'); } this.location.narrate(text.join(' '), undefined, this); }; Object.setOwnerOf($.clock.chime, $.physicals.Maximilian); $.clock.contents_ = []; $.clock.contents_.forObj = $.clock; Object.defineProperty($.clock.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.clock.contents_.forKey = 'contents_'; Object.defineProperty($.clock.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.clock.validate = function validate() { $.thing.validate.call(this); // Reset timer that runs the chime. this.onTimer(); }; Object.setOwnerOf($.clock.validate, $.physicals.Maximilian); Object.setOwnerOf($.clock.validate.prototype, $.physicals.Maximilian); $.clock.onTimer = function onTimer() { /* Function that creates a thread to call itself at the next hour * (and calls this.chime() if it is the right time to do so.) */ var time = new Date(); // Chime during first minute past the hour. If we got called early // we'll automatically try again at (hopefully) the correct time. var doChime = (time.getMinutes() === 0); // Compute next hour in local timezone. time.setMilliseconds(0); time.setSeconds(0); time.setMinutes(0); time.setHours(time.getHours() + 1); // Automagically increments date if required. // Kill any other thread associated with this clock. clearTimeout(this.thread_); // Schedule ourselves to be run again at time. this.thread_ = new Thread(this.onTimer, time - Date.now(), this); if (doChime) this.chime(); }; Object.setOwnerOf($.clock.onTimer, $.physicals.Maximilian); Object.setOwnerOf($.clock.onTimer.prototype, $.physicals.Maximilian); $.clock.movable = false; $.clock.description = function description() { return 'It is currently ' + Date(); }; Object.setOwnerOf($.clock.description, $.physicals.Neil); Object.setOwnerOf($.clock.description.prototype, $.physicals.Neil); $.clock.svgText = function svgText() { var svg = ''; var r = 10; for (var i = 0; i < 12; i++) { var a = Math.PI * 2 / 12 * i; var length = (i % 3 === 0) ? 2 : 1; var x1 = Math.sin(a) * r; var y1 = Math.cos(a) * r + 30; var x2 = Math.sin(a) * (r - length); var y2 = Math.cos(a) * (r - length) + 30; svg += ''; } var now = new Date(); var minutes = now.getMinutes() + (now.getSeconds() / 60); var hours = now.getHours() + (minutes / 60); var x1 = 0; var y1 = 30; a = minutes / 60 * Math.PI * 2 + Math.PI; var x2 = Math.sin(a) * -8; var y2 = Math.cos(a) * 8 + 30; svg += ''; a = hours / 12 * Math.PI * 2 + Math.PI; var x2 = Math.sin(a) * -6; var y2 = Math.cos(a) * 6 + 30; svg += ''; return svg; }; Object.setOwnerOf($.clock.svgText, $.physicals.Neil); ================================================ FILE: core/core_41_deutsche_zimmer.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Translation room and tutorial demo for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.physicals['Das deutsche Zimmer'] = (new 'Object.create')($.room); $.physicals['Das deutsche Zimmer'].name = 'Das deutsche Zimmer'; $.physicals['Das deutsche Zimmer'].translate = function translate(text) { /* Try to translate text into German. If successful, return * translation. If not, narrate an indication of failure and return * the original text untranslated. */ try { return $.utils.string.translate(text, 'de'); } catch (e) { this.narrate('There is a crackling noise.'); return text; } }; Object.setOwnerOf($.physicals['Das deutsche Zimmer'].translate, $.physicals.Maximilian); $.physicals['Das deutsche Zimmer'].say = function say(cmd) { // Format: "Hello. -or- say Hello. var text = (cmd.cmdstr[0] === '"') ? cmd.cmdstr.substring(1) : cmd.argstr; cmd.cmdstr = []; cmd.argstr = this.translate(text); return $.room.say.call(this, cmd); }; Object.setOwnerOf($.physicals['Das deutsche Zimmer'].say, $.physicals.Maximilian); $.physicals['Das deutsche Zimmer'].say.verb = 'say|".*'; $.physicals['Das deutsche Zimmer'].say.dobj = 'any'; $.physicals['Das deutsche Zimmer'].say.prep = 'any'; $.physicals['Das deutsche Zimmer'].say.iobj = 'any'; $.physicals['Das deutsche Zimmer'].contents_ = []; $.physicals['Das deutsche Zimmer'].contents_.forObj = $.physicals['Das deutsche Zimmer']; Object.defineProperty($.physicals['Das deutsche Zimmer'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals['Das deutsche Zimmer'].contents_.forKey = 'contents_'; Object.defineProperty($.physicals['Das deutsche Zimmer'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.physicals['Das deutsche Zimmer'].location = null; $.tutorial = (new 'Object.create')($.thing); $.tutorial.name = 'tutorial'; $.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.'; $.tutorial.svgText = '\n\n\n'; $.tutorial.look = function look(cmd) { if (this.location !== cmd.user) { // Show description, encouraging user to pick up tutorial. $.thing.look.call(this, cmd); return; } this.show(cmd.user); // Show current step. }; Object.setOwnerOf($.tutorial.look, $.physicals.Maximilian); $.tutorial.look.verb = 'l(ook)?'; $.tutorial.look.dobj = 'this'; $.tutorial.look.prep = 'none'; $.tutorial.look.iobj = 'none'; $.tutorial.reset = function reset(cmd) { this.checkLocation(); this.step = 0; this.room = undefined; this.origFunc = undefined; if (this.user) this.show(); }; Object.setOwnerOf($.tutorial.reset, $.physicals.Maximilian); $.tutorial.reset.verb = 'reset'; $.tutorial.reset.dobj = 'this'; $.tutorial.reset.prep = 'none'; $.tutorial.reset.iobj = 'none'; $.tutorial.continue = function continueVerb(cmd) { this.step++; this.run(); this.show(); }; Object.setOwnerOf($.tutorial.continue, $.physicals.Maximilian); $.tutorial.continue.verb = 'continue'; $.tutorial.continue.dobj = 'this'; $.tutorial.continue.prep = 'none'; $.tutorial.continue.iobj = 'none'; $.tutorial.getCommands = function getCOmmands(who) { var commands = $.thing.getCommands.call(this, who); if (this.location === who) { commands.push('continue ' + this.name); commands.push('reset ' + this.name); } return commands; }; Object.setOwnerOf($.tutorial.getCommands, $.physicals.Maximilian); $.tutorial.moveTo = function moveTo(dest) { // Set this.user th the $.user holding us, or to undefined if not held. var r = $.thing.moveTo.call(this, dest); this.checkLocation(); return r; }; Object.setOwnerOf($.tutorial.moveTo, $.physicals.Maximilian); $.tutorial.checkLocation = function checkLocation() { if ($.user.isPrototypeOf(this.location)) { this.user = this.location; this.thread = new Thread(this.check, 0, this); } else { this.user = undefined; if (this.t) { Thread.kill(this.thread); this.thread = null; } } }; Object.setOwnerOf($.tutorial.checkLocation, $.physicals.Maximilian); $.tutorial.check = function check() { while (true) { var step = this.step; switch (step) { case 1: // See if user has done step 1: are they carrying a room? if (this.room) throw new Error('How is .room set already??'); for (var key in $.physicals) { var item = $.physicals[key]; if ($.room.isPrototypeOf(item) && Object.getOwnerOf(item) === this.user && item.name.match(/Deutsche Zimmer/i)) { this.room = item; break; } } if (this.room) this.step++; break; case 3: if (Object.getOwnPropertyDescriptor(this.room, 'description')) { this.step++; } break; case 5: var pd = Object.getOwnPropertyDescriptor(this.room, 'translate'); if (pd && typeof pd.value === 'function') { this.origFunc = pd.value; var tutorial = this; this.room.translate = function translateHook() { // This is just a hook to help automate the tutorial. if (tutorial.step === 6) tutorial.step++; // Restore and call original version of the function. this.translate = tutorial.origFunc; tutorial.origFunc = undefined; new Thread(function() { tutorial.run(); tutorial.show(); }, 500); return this.translate.apply(this, arguments); }; this.step++; } break; case 6: // Handled by hook function installed in step 5. break; case 7: var pd = Object.getOwnPropertyDescriptor(this.room, 'say'); if (pd && typeof pd.value === 'function') { this.origFunc = this.room.translate; var tutorial = this; this.room.translate = function() { // This is just a hook to help automate the tutorial. if (tutorial.step === 8) tutorial.step++; // Restore and call original version of the function. this.translate = tutorial.origFunc; tutorial.origFunc = undefined; new Thread(function() { tutorial.run(); tutorial.show(); }, 500); return this.translate.apply(this, arguments); }; this.step++; } break; case 8: // Handled by hook function installed in step 7. break; default: // Nothing to do. } if (this.step !== step) { this.run(); this.show(); } suspend(1000); } }; Object.setOwnerOf($.tutorial.check, $.physicals.Maximilian); $.tutorial.run = function run() { switch (this.step) { case 3: if (this.room.location !== null) this.room.moveTo(null); if (this.user.location !== this.room) this.user.moveTo(this.room); break; case 5: // Open room in the code editor. var link = '/code?' + encodeURIComponent($.Selector.for(this.room).toString() + '.translate'); this.user.readMemo({type: "link", href: link}); break; default: // Nothing to do. } }; Object.setOwnerOf($.tutorial.run, $.physicals.Maximilian); $.tutorial.show = function show() { var lines; var step = this.step; switch(step) { case 0: lines = [ '

Translation API Tutorial

', '

This tutorial will teach you how to use the Google machine', 'translation API to create a room that will automatically', 'translate everything said to the language of your choice.

', '

Type continue tutorial to continue.

' ]; break; case 1: lines = [ '

Step 1: Create a new room

', '

Run the following command:

', 'create $.room as Deutsche Zimmer', '

(Click to run, or type your own variation.)

', ]; break; case 2: lines = [ '

Step 2: Move to the newly-created room

', '

You\'ve created a room named "' + this.room.name + '". Now type', "continue tutorial and you'll be transported there", 'automagically.

', ]; break; case 3: lines = [ '

Step 3: Give your new room a description

', "

You're now in you're newly-created room. Let's give it a", 'description using the eval command:

', 'eval here.description = "Wir sprechen Deutsch hier."', ]; break; case 4: lines = [ '

Step 4: Open code editor

', "

We'll use the code editor to add a translate method to this room.", 'When you type continue tutorial the code inspector/editor', 'will open in another tab. (You might need to enable pop-ups!)', 'Click back to this tab to see the next set of instructions.', ]; break; case 5: lines = [ '

Step 5: Add a translate() method

', '

Make sure the status bar of the code inspector says', '$.tutorial.room.translate, then replace "undefined" with the', 'following code (and save it):

', '
',
        'function translate(text) {',
        '  // Try to translate text into German.  If successful, return the translation.',
        '  // If not, narrate an indication of failure and return the original text.',
        '  try {',
        "    var json = $.system.xhr('https://translate-service.scratch.mit.edu' +",
        "        '/translate?language=de&text=' + encodeURIComponent(text));",
        '    return JSON.parse(json).result;',
        '  } catch (e) {',
        "    this.narrate('There is a crackling noise.');",
        '    return text;',
        '  }',
        '};',
        '
', ]; break; case 6: lines = [ '

Step 6: Test the translate() method

', '

Let\'s use the eval command to test the the new translate', 'method:

', 'eval here.translate("Good morning.")', '

You should see output that looks like this:

', '

=> "Guten Morgen."

', ]; break; case 7: lines = [ '

Step 7: Override the "say" verb

', '

Use the top part of the inspector to navigate to the "say"', 'function, and replace it with the following:

', '
',
        'function say(cmd) {',
        '  // Format:  "Hello.    -or-    say Hello.',
        '  var text = (cmd.cmdstr[0] === \'"\') ? cmd.cmdstr.substring(1) : cmd.argstr;',
        '  cmd.cmdstr = [];',
        '  cmd.argstr = this.translate(text);',
        '  return $.room.say.call(this, cmd);',
        '}',
        '
', ]; break; case 8: lines = [ '

Step 8: Test out the new "say" verb

', '

The function you created in the last step, $.tutorial.room.say,', 'overrides the default $.room.say function by translating the text to', 'be said and then passing it along to the latter to actually say.

', "

Let's test it it out by saying something!:

", 'say Now I can speak German!', ]; break; case 9: lines = [ '

Step 9: Finish up

', "

Feel free to hang around an play with the room you've created.", 'Can you change the language it translates into?', '(Hint: look in $.tutorial.room.translate, and remever that "de" is', 'the two-letter code for the German language.)

', "

When you're done, type continue tutorial and you'll", 'be taken back to where you came from. You can delete this room ', 'when you no longer want it by typing destroy ' + $.Selector.for(this.room).toString() + '.', ]; break; case 10: this.user.moveTo($.startRoom); this.room = undefined; // FALLTTHROUGH default: lines = [ '

Tutorial Ended

', "You've either finished the tutorial, or you've found a bug in it.", 'Either way: contratulations!

', '

You can always reset tutorial to do it all again.

', ]; } this.user.readMemo({type: 'html', htmlText: lines.join('\n')}); }; Object.setOwnerOf($.tutorial.show, $.physicals.Maximilian); $.tutorial.contents_ = []; $.tutorial.contents_.forObj = $.tutorial; Object.defineProperty($.tutorial.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.tutorial.contents_.forKey = 'contents_'; Object.defineProperty($.tutorial.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.tutorial.location = undefined; $.tutorial.user = undefined; $.tutorial.thread = undefined; $.tutorial.step = undefined; $.tutorial.room = undefined; $.tutorial.origFunc = undefined; $.physicals.tutorial = $.tutorial; ================================================ FILE: core/core_42_plant.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Plant demo for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.seed = (new 'Object.create')($.thing); $.seed.name = 'Generic Seed'; $.seed.aliases = []; $.seed.aliases[0] = 'seed'; $.seed.description = 'A harmless looking seed. Try planting it in a pot, then watering it.'; $.seed.svgText = '\n'; $.seed.contents_ = []; $.seed.contents_.forObj = $.seed; Object.defineProperty($.seed.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.seed.contents_.forKey = 'contents_'; Object.defineProperty($.seed.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.seed.location = undefined; $.physicals['Generic Seed'] = $.seed; $.pot = (new 'Object.create')($.thing); $.pot.name = 'flower pot'; $.pot.aliases = []; $.pot.aliases[0] = 'pot'; $.pot.description = 'A clay flower pot. Try planting a seed in a pot, then watering it.'; $.pot.plant = function plant(cmd) { cmd.user.narrate('You plant ' + String(cmd.dobj) + ' in ' + String(this) + '.'); if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' plants ' + String(cmd.dobj) + ' in ' + String(this) + '.', cmd.user); } cmd.dobj.moveTo(null); this.stage = 0; this.seed = cmd.dobj; }; Object.setOwnerOf($.pot.plant, $.physicals.Maximilian); $.pot.plant.verb = 'plant|put'; $.pot.plant.dobj = 'any'; $.pot.plant.prep = 'in/inside/into'; $.pot.plant.iobj = 'this'; $.pot.water = function water(cmd) { cmd.user.narrate('You water ' + String(this) + '.'); if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' waters ' + String(this) + '.', cmd.user); } if (this.seed && this.stage < 4) { if (this.stage === 2) { var newSeed = Object.create(this.seed); newSeed.moveTo(this.location, this); cmd.user.location.narrate('A new seed appears.'); } this.stage++; this.location.updateScene(true); } }; Object.setOwnerOf($.pot.water, $.physicals.Neil); $.pot.water.verb = 'water'; $.pot.water.dobj = 'this'; $.pot.water.prep = 'none'; $.pot.water.iobj = 'none'; $.pot.getCommands = function getCommands(who) { var commands = $.thing.getCommands.call(this, who); commands.push('water ' + this.name); return commands; }; Object.setOwnerOf($.pot.getCommands, $.physicals.Neil); $.pot.contents_ = []; $.pot.contents_.forObj = $.pot; Object.defineProperty($.pot.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.pot.contents_.forKey = 'contents_'; Object.defineProperty($.pot.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.pot.reset = function reset(cmd) { $.physicals["a seed"].moveTo(this.location); this.stage = 0; this.seed = null; cmd.user.narrate('You reset ' + String(this) + '.'); }; Object.setOwnerOf($.pot.reset, $.physicals.Neil); Object.setOwnerOf($.pot.reset.prototype, $.physicals.Neil); $.pot.reset.verb = 'reset'; $.pot.reset.dobj = 'this'; $.pot.reset.prep = 'none'; $.pot.reset.iobj = 'none'; $.pot.svgText = function svgText() { return this.stages[this.stage]; }; Object.setOwnerOf($.pot.svgText, $.physicals.Neil); $.pot.location = undefined; $.pot.seed = undefined; $.pot.stage = undefined; $.pot.stages = []; $.pot.stages[0] = '\n'; $.pot.stages[1] = '\n\n\n\n'; $.pot.stages[2] = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'; $.pot.stages[3] = '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'; $.pot.stages[4] = '\n\n\n\n\n\n \n \n \n \n \n \n \n'; $.pot.stages[5] = '\n\n\n\n\n'; $.physicals['flower pot'] = $.pot; $.thrower = (new 'Object.create')($.thing); $.thrower.name = 'a flame thrower'; $.thrower.aliases = []; Object.setOwnerOf($.thrower.aliases, $.physicals.Maximilian); $.thrower.aliases[0] = 'flame thrower'; $.thrower.aliases[1] = 'flamethrower'; $.thrower.aliases[2] = 'a flamethrower'; $.thrower.aliases[3] = 'thrower'; $.thrower.description = 'A backpack filled with napalm. A pilot light is burning quietly.'; $.thrower.svgText = '\n\n'; $.thrower.wear = function wear(user) { if (this.savedSvg) { user.narrate(String(this) + ' is already being worn.'); return; } this.moveTo(user); this.savedSvg = user.svgText; user.svgText += this.svgText; if (user.location) { user.location.updateScene(true); user.location.narrate(String(user) + ' straps on ' + String(this) + '.', user); } user.narrate('You strap on ' + String(this) + '.'); }; Object.setOwnerOf($.thrower.wear, $.physicals.Neil); $.thrower.unwear = function unwear(user) { if (!this.savedSvg) { user.narrate('You aren\'t wearing ' + String(this) + '.'); return; } user.svgText = this.savedSvg; this.savedSvg = undefined; if (user.location) { user.location.updateScene(true); user.location.narrate(String(user) + ' takes off ' + String(this) + '.', user); } user.narrate('You takes off ' + String(this) + '.'); }; Object.setOwnerOf($.thrower.unwear, $.physicals.Neil); $.thrower.fire = function fire(cmd) { var memo = { type: 'iframe', url: '/static/flamethrower.html', alt: 'FIRE!!!' }; cmd.user.location.sendMemo(memo); if (cmd.iobj.seed) { cmd.iobj.seed = null; } if (typeof cmd.iobj.stage === 'number') { if (cmd.iobj.stage > 0) { cmd.iobj.stage = cmd.iobj.stages.length - 1; } } suspend(5000); cmd.user.location.updateScene(true); }; Object.setOwnerOf($.thrower.fire, $.physicals.Neil); $.thrower.fire.verb = 'fire'; $.thrower.fire.dobj = 'this'; $.thrower.fire.prep = 'at/to'; $.thrower.fire.iobj = 'any'; $.thrower.getCommands = function getCommands(who) { var commands = $.thing.getCommands.call(this, who); if (this.savedSvg) { commands.push('take off ' + this.name); } else { commands.push('put on ' + this.name); } return commands; }; Object.setOwnerOf($.thrower.getCommands, $.physicals.Neil); $.thrower.contents_ = []; $.thrower.contents_.forObj = $.thrower; Object.defineProperty($.thrower.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.thrower.contents_.forKey = 'contents_'; Object.defineProperty($.thrower.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.thrower.unwear1 = function unwear1(cmd) { this.unwear(cmd.user); }; Object.setOwnerOf($.thrower.unwear1, $.physicals.Neil); Object.setOwnerOf($.thrower.unwear1.prototype, $.physicals.Neil); $.thrower.unwear1.verb = 'take'; $.thrower.unwear1.dobj = 'this'; $.thrower.unwear1.prep = 'off/off of'; $.thrower.unwear1.iobj = 'none'; $.thrower.unwear2 = function unwear2(cmd) { this.unwear(cmd.user); }; Object.setOwnerOf($.thrower.unwear2, $.physicals.Neil); Object.setOwnerOf($.thrower.unwear2.prototype, $.physicals.Neil); $.thrower.unwear2.verb = 'take'; $.thrower.unwear2.dobj = 'none'; $.thrower.unwear2.prep = 'off/off of'; $.thrower.unwear2.iobj = 'this'; $.thrower.wear1 = function wear1(cmd) { this.wear(cmd.user); }; Object.setOwnerOf($.thrower.wear1, $.physicals.Neil); Object.setOwnerOf($.thrower.wear1.prototype, $.physicals.Neil); $.thrower.wear1.verb = 'put'; $.thrower.wear1.dobj = 'this'; $.thrower.wear1.prep = 'on top of/on/onto/upon'; $.thrower.wear1.iobj = 'none'; $.thrower.wear2 = function wear2(cmd) { this.wear(cmd.user); }; Object.setOwnerOf($.thrower.wear2, $.physicals.Neil); Object.setOwnerOf($.thrower.wear2.prototype, $.physicals.Neil); $.thrower.wear2.verb = 'put'; $.thrower.wear2.dobj = 'none'; $.thrower.wear2.prep = 'on top of/on/onto/upon'; $.thrower.wear2.iobj = 'this'; $.thrower.location = undefined; $.thrower.savedSvg = undefined; $.physicals['a flame thrower'] = $.thrower; ================================================ FILE: core/core_43_genetics_lab.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Genetics lab demo for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.physicals['Genetics Lab'] = (new 'Object.create')($.room); $.physicals['Genetics Lab'].name = 'Genetics Lab'; $.physicals['Genetics Lab'].location = null; $.physicals['Genetics Lab'].description = 'To create a new mouse, type: create $.cage.mousePrototype as '; $.physicals['Genetics Lab'].contents_ = []; $.physicals['Genetics Lab'].contents_.forObj = $.physicals['Genetics Lab']; Object.defineProperty($.physicals['Genetics Lab'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals['Genetics Lab'].contents_.forKey = 'contents_'; Object.defineProperty($.physicals['Genetics Lab'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.cage = (new 'Object.create')($.container); $.cage.name = 'cage'; $.cage.contents_ = []; $.cage.contents_.forObj = $.cage; Object.defineProperty($.cage.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.cage.contents_.forKey = 'contents_'; Object.defineProperty($.cage.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.cage.isOpen = true; $.cage.variation = 1; $.cage.tempo = 30; $.cage.maxPopulation = 50; $.cage.fight = function fight(aggressor, defender) { var capitalizedAggressorName = $.utils.string.capitalize(String(aggressor)) + '(' + aggressor.size + ' cm)'; var defenderName = String(defender) + '(' + defender.size + ' cm)'; aggressor.aggressiveness--; var point = Math.floor(Math.random() * (aggressor.size + defender.size)); var victim = null; if (point > defender.size) { victim = defender; } else if (point < defender.size) { victim = aggressor; } if (victim === defender) { this.location.narrate(capitalizedAggressorName + ' fights and kills ' + defenderName + '.'); } else if (victim === aggressor) { this.location.narrate(capitalizedAggressorName + ' fights and is killed by ' + defenderName + '.'); } else { this.location.narrate(capitalizedAggressorName + ' fights ' + defenderName + ' to a draw.'); } if (victim) { this.kill(victim); } }; Object.setOwnerOf($.cage.fight, $.physicals.Neil); $.cage.kill = function kill(victim) { if (!this.isMouse(victim)) { this.location.narrate('ERROR: Cannot kill ' + String(victim) + " since it doesn't appear to be a mouse in here."); return; } var owner = Object.getOwnerOf(victim); if (this === $.physicals.cage.mousePrototype) { // Can't happen. But would be catastrophic, so check anyway. victim.moveTo(null); throw Error('Tried to kill the prototype mouse.'); } else if (owner === this) { // This mouse is a child. victim.destroy(); } else { // This mouse belongs to a user. victim.moveTo(owner); this.location.narrate($.utils.string.capitalize(String(victim)) + ' is ejected from ' + String(this)); } }; Object.setOwnerOf($.cage.kill, $.physicals.Neil); $.cage.breed = function breed(mother, father) { mother.fertility--; father.fertility--; if (mother.fertility < 0 || father.fertility < 0) { this.location.narrate('Mating failed since one of them is sterile.'); return; } if (mother.sex === father.sex) { var sex = mother.sex; if (sex === 'M') { sex = 'male'; } else if (sex === 'F') { sex = 'female'; } this.location.narrate('Mating failed since both are ' + mother.sex + '.'); return; } var mice = this.getContents(); if (mice.length >= this.maxPopulation) { var oldest = mice[0]; for (var i = 1; i < mice.length; i++) { if (mice[i].generation < oldest.generation) { oldest = mice[i]; } } this.location.narrate('Maximum population (' + this.maxPopulation, ') reached; ' + String(oldest) + ' dies of old age.'); this.kill(oldest); } var kid = Object.create(this.mousePrototype); Object.setOwnerOf(kid, this); kid.init(mother, father, this.variation); kid.moveTo(this); this.location.narrate($.utils.string.capitalize(String(kid)) + ' has been born to ' + String(mother) + ' & ' + String(father) + '.'); this.tasks.push(setTimeout(this.life.bind(this, kid), 0)); }; Object.setOwnerOf($.cage.breed, $.physicals.Neil); $.cage.tasks = []; $.cage.setOpen = function setOpen(newState) { var success = Object.getPrototypeOf($.cage).setOpen.call(this, newState); if (!success) { return false; } while (this.tasks.length) { clearTimeout(this.tasks.pop()); } var location = this.location; var mice = this.getContents(); if (this.isOpen) { for (var i = mice.length - 1; i >= 0; i--) { this.kill(mice[i]); } location.narrate('All mice in ' + String(this) + ' have been exterminated.'); } else { location.narrate($.utils.string.capitalize(String(this)) + ' starts running.'); for (var i = mice.length - 1; i >= 0; i--) { var mouse = mice[i]; if (this.isMouse(mouse)) { location.narrate($.utils.string.capitalize(String(mouse)) + ' starts moving.'); this.startMouse(mouse); } else { location.narrate($.utils.string.capitalize(String(mouse)) + " isn't a valid mouse and gets thrown out."); mouse.moveTo(location); } } } return true; }; Object.setOwnerOf($.cage.setOpen, $.physicals.Maximilian); Object.setOwnerOf($.cage.setOpen.prototype, $.physicals.Maximilian); $.cage.life = function life(mouse) { if (!this.isMouse(mouse)) { throw Error(String(mouse) + ' is not a valid mouse.'); } var capitalizedMouseName = $.utils.string.capitalize(String(mouse)); var self = 'itself'; if (mouse.sex === 'M') { self = 'himself'; } else if (mouse.sex === 'F') { self = 'herself'; } while (true) { this.tasks.push(suspend(Math.random() * this.tempo * 1000)); if (mouse.location !== this) { return; } if (mouse.aggressiveness < 1 && mouse.fertility < 1) { this.location.narrate(capitalizedMouseName + ' dies after a productive life.'); this.kill(mouse); return; } if (mouse.aggressiveness > 0) { try { var victim = mouse.pickFight(); } catch (e) { this.kill(mouse); this.location.narrate(capitalizedMouseName + ' threw "' + e + '" in .pickFight function.'); this.location.narrate(capitalizedMouseName + ' is being executed to put it out of its misery.'); } if (!victim) { this.location.narrate(capitalizedMouseName + ' decides not to fight ever again.'); mouse.aggressiveness = 0; } else if (mouse === victim) { this.location.narrate(capitalizedMouseName + ' fights and kills ' + self + '.'); this.kill(mouse); return; } else if (this.isMouse(victim)) { this.fight(mouse, victim); } else { this.location.narrate(capitalizedMouseName + ' returned "' + String(victim) + '" from .pickFight function.'); this.location.narrate(capitalizedMouseName + ' is being executed to put it out of its misery.'); this.kill(mouse); return; } } else if (mouse.fertility > 0) { try { var target = mouse.proposeMate(); } catch (e) { this.kill(mouse); this.location.narrate($.utils.string.capitalize(String(target)) + ' threw "' + e + '" in .proposeMate function.'); this.location.narrate($.utils.string.capitalize(String(mouse)) + ' is being executed to put it out of its misery.'); } if (!target) { this.location.narrate(capitalizedMouseName + ' decides not to mate ever again.'); mouse.fertility = 0; } else if (mouse === target) { mouse.fertility--; this.location.narrate(capitalizedMouseName + ' is caught trying to mate with ' + self + '.'); } else if (this.isMouse(target)) { try { var answer = target.acceptMate(mouse); } catch (e) { this.location.narrate($.utils.string.capitalize(String(target)) + ' threw "' + e + '" in .acceptMate function.'); this.location.narrate($.utils.string.capitalize(String(target)) + ' is being executed to put it out of its misery.'); this.kill(target); } if (answer) { this.location.narrate(capitalizedMouseName + ' asked ' + String(target) + ' to mate. The answer is YES!'); this.breed(mouse, target); } else { this.location.narrate(capitalizedMouseName + ' asked ' + String(target) + ' to mate. The answer is NO!'); } } else { this.location.narrate(capitalizedMouseName + ' returned "' + String(target) + '" from .proposeMate function.'); this.location.narrate(capitalizedMouseName + ' is being executed to put it out of its misery.'); this.kill(mouse); return; } } } }; Object.setOwnerOf($.cage.life, $.physicals.Neil); $.cage.willAccept = function willAccept(what, src) { // Returns true iff this is willing to accept what arriving from src. // // This function (or its overrides) MUST NOT have any kind of // observable side-effect (making noise, causing some other action, // etc.). return this.isOpen || (this.mousePrototype.isPrototypeOf(what) && !src); }; Object.setOwnerOf($.cage.willAccept, $.physicals.Neil); Object.setOwnerOf($.cage.willAccept.prototype, $.physicals.Maximilian); $.cage.mousePrototype = (new 'Object.create')($.thing); $.cage.mousePrototype.name = 'Genetic Mouse Prototype'; $.cage.mousePrototype.location = null; $.cage.mousePrototype.contents_ = []; $.cage.mousePrototype.contents_.forObj = $.cage.mousePrototype; Object.defineProperty($.cage.mousePrototype.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.cage.mousePrototype.contents_.forKey = 'contents_'; Object.defineProperty($.cage.mousePrototype.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.cage.mousePrototype.size = 10; $.cage.mousePrototype.generation = 0; $.cage.mousePrototype.sex = NaN; $.cage.mousePrototype.proposeMate = function proposeMate() { // Return who you'd like to mate with! // Returning null will pass on this mating and all future ones. // Reprogram this function to make it smarter! var mice = this.location.getContents(); return mice[Math.floor(Math.random() * mice.length)]; }; Object.setOwnerOf($.cage.mousePrototype.proposeMate, $.physicals.Neil); $.cage.mousePrototype.acceptMate = function acceptMate(whom) { // The mouse 'whom' wishes to mate with you! // Return true to mate with it, or false to tell it to go away. // Reprogram this function to make it smarter! return Math.random() > 0.5; }; Object.setOwnerOf($.cage.mousePrototype.acceptMate, $.physicals.Neil); $.cage.mousePrototype.pickFight = function pickFight() { // Return who you'd like to fight with! // Returning null will pass on this fight and all future ones. // The bigger mouse (based on .size) usually wins. // Reprogram this function to make it smarter! var mice = this.location.getContents(); return mice[Math.floor(Math.random() * mice.length)]; }; Object.setOwnerOf($.cage.mousePrototype.pickFight, $.physicals.Neil); $.cage.mousePrototype.toString = function toString() { var prototype = Object.getPrototypeOf(this); var pickFightOwner = (this.pickFight === prototype.pickFight) ? null : Object.getOwnerOf(this.pickFight); var proposeMateOwner = (this.proposeMate === prototype.proposeMate) ? null : Object.getOwnerOf(this.proposeMate); var acceptMateOwner = (this.acceptMate === prototype.acceptMate) ? null : Object.getOwnerOf(this.acceptMate); return this.name + ' (' + String(pickFightOwner) + '/' + String(proposeMateOwner) + '/' + String(acceptMateOwner) + ')'; }; Object.setOwnerOf($.cage.mousePrototype.toString, $.physicals.Neil); $.cage.mousePrototype.init = function init(mother, father, variation) { // Blend together the numeric attributes from the parents. var thisMouse = this; function blend(name) { var average = (mother[name] + father[name]) / 2; var mutation = Math.random() * 2 * variation - variation; thisMouse[name] = Math.max(1, Math.round(average + mutation)); } blend('size'); blend('startFertility'); this.fertility = this.startFertility; blend('startAggressiveness'); this.aggressiveness = this.startAggressiveness; this.generation = 1 + Math.max(mother.generation, father.generation); // Random sex and name. this.sex = Math.random() > 0.5 ? 'M' : 'F'; var name = ''; for (var i = 0; i < 6; i++) { var letters = ((i % 2) == (this.sex === 'F') ? $.utils.string.VOWELS : $.utils.string.CONSONANTS); name += $.utils.string.randomCharacter(letters); } this.setName($.utils.string.capitalize(name), /*tryAlternative:*/ true); // Copy the three 'genetic' functions. // Take two from one parent, and one from the other. var f1 = Math.floor(Math.random() * 2); var f2 = Math.floor(Math.random() * 2); var f3 = (f1 === f2) ? 1 - f1 : Math.floor(Math.random() * 2); this.proposeMate = (f1 ? mother : father).proposeMate; this.acceptMate = (f2 ? mother : father).acceptMate; this.pickFight = (f3 ? mother : father).pickFight; }; Object.setOwnerOf($.cage.mousePrototype.init, $.physicals.Neil); $.cage.mousePrototype.svgText = '\n\n\n\n\n\n\n\n\n\n'; $.cage.mousePrototype.startAggressiveness = 2; $.cage.mousePrototype.aggressiveness = 2; $.cage.mousePrototype.startFertility = 4; $.cage.mousePrototype.fertility = 3; $.cage.mousePrototype.getCommands = function getCommands(who) { var commands = $.thing.getCommands.call(this, who); commands.push('program ' + this.name); return commands; }; Object.setOwnerOf($.cage.mousePrototype.getCommands, $.physicals.Neil); $.cage.mousePrototype.program = function program(cmd) { // Open this mouse in the genetics editor. var selector = $.Selector.for(this).toString(); // No need to encode $. var query = encodeURIComponent(String(selector)).replace(/%24/g, '$'); var link = $.hosts.root.url('genetics') + 'editor?' + query; cmd.user.readMemo({type: "link", href: link}); }; Object.setOwnerOf($.cage.mousePrototype.program, $.physicals.Maximilian); Object.setOwnerOf($.cage.mousePrototype.program.prototype, $.physicals.Neil); $.cage.mousePrototype.program.verb = 'program'; $.cage.mousePrototype.program.dobj = 'this'; $.cage.mousePrototype.program.prep = 'none'; $.cage.mousePrototype.program.iobj = 'none'; $.cage.mousePrototype.description = function description() { var sex = 'multi-sexual'; if (this.sex === 'm') sex = 'male'; if (this.sex === 'f') sex = 'female'; var desc = []; desc.push('A ' + sex + ' mouse.'); desc.push('It is ' + this.size + ' cm long, and can have ' + this.fertility + ' more children.'); desc.push('It can fight ' + this.aggressiveness + ' other mice.'); desc.push('It belongs to generation ' + this.generation + '.'); return desc.join('\n'); }; Object.setOwnerOf($.cage.mousePrototype.description, $.physicals.Neil); Object.setOwnerOf($.cage.mousePrototype.description.prototype, $.physicals.Neil); $.cage.isMouse = function isMouse(animal) { return this.mousePrototype.isPrototypeOf(animal) && (animal.location === this); }; Object.setOwnerOf($.cage.isMouse, $.physicals.Neil); $.cage.startMouse = function startMouse(mouse) { // Reset all attributes to defaults. var reset = ['fertility', 'startFertility', 'generation', 'startAggressiveness', 'sex', 'size']; for (var i = 0; i < reset.length; i++) { delete mouse[reset[i]]; } // First generation mice don't fight. mouse.aggressiveness = 0; this.tasks.push(setTimeout(this.life.bind(this, mouse), 0)); }; Object.setOwnerOf($.cage.startMouse, $.physicals.Maximilian); $.cage.open = function open(cmd) { if (this.isOpen) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.'); return; } if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.'); return; } if (!this.setOpen(true)) { cmd.user.narrate('You can\'t open ' + String(cmd.dobj)); return; } if (cmd.user.location) { cmd.user.location.narrate(cmd.user.name + ' opens ' + String(cmd.dobj) + '.', cmd.user); } cmd.user.narrate('You open ' + String(cmd.dobj) + '.'); this.look(cmd); }; Object.setOwnerOf($.cage.open, $.physicals.Maximilian); Object.setOwnerOf($.cage.open.prototype, $.physicals.Maximilian); $.cage.open.verb = 'open'; $.cage.open.dobj = 'this'; $.cage.open.prep = 'none'; $.cage.open.iobj = 'none'; $.cage.svgTextClosed = '\n\n\n'; $.cage.svgTextOpen = '\n\n\n\n\n'; $.cage.location = undefined; $.physicals.cage = $.cage; $.physicals['Genetic Mouse Prototype'] = $.cage.mousePrototype; $.hosts.genetics = (new 'Object.create')($.servers.http.Host.prototype); $.hosts.genetics['/editor'] = {}; $.hosts.genetics['/editor'].www = "\n<% var staticUrl = request.hostUrl('static'); %>\n\n \n \n Code City: Genetics Editor\n favicon.ico\" rel=\"shortcut icon\">\n \n style/jfk.css\">\n\n CodeMirror/lib/codemirror.css\">\n CodeMirror/addon/lint/lint.css\">\n CodeMirror/theme/eclipse.css\">\n \n \n \n \n \n \n \n \n \n \n<%\nvar mouseSelector = decodeURIComponent(request.query);\nvar mouse = $(mouseSelector);\n%>\n \n \n\n \n
\n
\n
\n \n
\n
<%= mouse && mouse.name %>
\n
\n .pickFight.proposeMate.acceptMateReference\n
\n
\n
\n
\n
\n
\n

Properties on the mice:

\n
\n
.generation → integer
\n
The initial mice placed in the cage are generation 0.\n Their children are generation 1, and so on.
\n
.sex → 'M' or 'F' or NaN
\n
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.
\n
.size → integer
\n
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.
\n
.startFertility → integer
\n
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.
\n
.fertility → integer
\n
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.
\n
.startAggressiveness → integer
\n
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.
\n
.aggressiveness → integer
\n
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.
\n
.location → cage
\n
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.
\n
\n

Functions on the mice:

\n
\n
.pickFight → mouse or null
\n
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.
\n
.proposeMate() → mouse or null
\n
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.
\n
.acceptMate(mouse) → boolean
\n
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.
\n
Ownership
\n
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.
\n
\n

Lifecycle

\n
    \n
  1. 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.
  2. \n
  3. 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.
  4. \n
  5. 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.
  6. \n
  7. 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.
  8. \n
\n

Your mouse will die. The question is can your genes (functions) spread across the\n population. There are a lot of strategies, have fun!

\n
\n
\n \n\n"; $.hosts.genetics['/editorXhr'] = {}; Object.setOwnerOf($.hosts.genetics['/editorXhr'], $.physicals.Neil); $.hosts.genetics['/editorXhr'].www = function genetics_editorXhr_www(request, response) { var data = {login: !!request.user, saved: false}; try { // ends with ... finally {response.write(JSON.stringify(data));} if (!request.fromSameOrigin()) { // Security check to ensure this is being loaded by the genetics editor. data.butter = 'Cross-origin referer: ' + String(request.headers.referer); return; } var selector; try { selector = new $.Selector(decodeURIComponent(request.parameters.selector)); } catch (e) { data.butter = 'Invalid selector: ' + String(e); return; } if (!request.user) { data.butter = 'User not logged in.'; return; } setPerms(request.user); // Populate the (original) value object in the reverse-lookup db. var mouse = selector.toValue(/*save:*/true); if (!$.cage.mousePrototype.isPrototypeOf(mouse)) { data.butter = 'Not a mouse: ' + String(request.parameters.selector); return; } // Evaluate src in global scope (eval by any other name, literally). var evalGlobal = eval; var butter = []; var functionNames = ['pickFight', 'proposeMate', 'acceptMate']; for (var i = 0; i < functionNames.length; i++) { var functionName = functionNames[i]; var src = request.parameters[functionName]; try { suspend(); var expr = $.utils.code.rewriteForEval(src, /*forceExpression:*/true); var saveValue = evalGlobal(expr); mouse[functionName] = saveValue; } catch (e) { // TODO(fraser): Send a more informative error message. butter.push(functionName + ': ' + String(e)); } } if (butter.length) { data.butter = butter.join('\n'); } else { data.butter = 'Saved'; data.saved = true; } } finally { response.write(JSON.stringify(data)); } }; Object.setOwnerOf($.hosts.genetics['/editorXhr'].www, $.physicals.Neil); Object.setOwnerOf($.hosts.genetics['/editorXhr'].www.prototype, $.physicals.Neil); $.hosts.root.subdomains.genetics = $.hosts.genetics; ================================================ FILE: core/core_44_$.assistant.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Voice-activated assistant demo for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.assistant = (new 'Object.create')($.thing); $.assistant.name = 'assistant'; $.assistant.contents_ = []; $.assistant.contents_.forObj = $.assistant; Object.defineProperty($.assistant.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.assistant.contents_.forKey = 'contents_'; Object.defineProperty($.assistant.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.assistant.svgText = '\n'; $.assistant.onMemo = function onMemo(memo) { if (memo.type !== 'say') return; // Only listen to users, not self or other bots. if (!$.user.isPrototypeOf(memo.source)) return; // Don't respond for 1s after last successful activation. if (!this.lastActivated) this.lastActivated = 0; if (Date.now() - this.lastActivated < 1000) { this.location.narrate(String(this) + ' flashes its lights in confusion.'); return; } // Look for activation pharase. var text = memo.text; var activation = new RegExp('^\\s*hey[,\\s]+' + this.name + '[,:;.!?\\s]*([^,:;.!?\\s].*)?', 'i'); var m = activation.exec(text); if (!m) return; // Didn't hear "hello, ". this.lastActivated = Date.now() // Process command. this.onCommand(m[1] || ''); }; Object.setOwnerOf($.assistant.onMemo, $.physicals.Maximilian); $.assistant.say = function say(speech) { if (!this.location) return; var memo = { type: 'say', source: this, where: this.location, text: speech }; this.location.sendMemo(memo); }; $.assistant.onCommand = function onCommand(command) { /* Attempt to find a handler for command, by calling methods on this * named cmd_* until one of them returns true. */ suspend(2000); var raw = String(command); command = command.replace(/[.,!?]*$/, ''); // Trim trailing punctuation. command = command.replace(/\s+/, ' '); // Normalise whitespace. if (!command) { this.say('How can I help?'); return; } // Look for properties on this named 'cmd_'. var done = false; for (var key in this) { if (key.lastIndexOf('cmd_', 0) !== 0) continue; var func = this[key]; if (typeof func !== 'function') continue; if (func.call(this, command, raw)) { done = true; break; } } if (!done) this.say('Sorry, I don\'t understand "' + command + '".'); }; Object.setOwnerOf($.assistant.onCommand, $.physicals.Maximilian); $.assistant.cmd_time = function cmd_time(command, raw) { // First check to see if the command looked like a request for the time. if (!command.match(/what time is it|what('s| is) the time/i)) return false; // It did. Tell the time. this.say('The current time is ' + new Date().toTimeString()); return true; }; Object.setOwnerOf($.assistant.cmd_time, $.physicals.Maximilian); Object.setOwnerOf($.assistant.cmd_time.prototype, $.physicals.Maximilian); $.assistant.cmd_translate = function cmd_translate(command, raw) { // First check to see if the command looked like a request to translate some text. var m = raw.match(/(?:what\s+is|how\s+do\s+you\s+say)\s+(?:"([^"]+)"|(.*))\s+in\s+(\w+)/i); if (!m) return false; // Nope; try another handler. // It did. Try to tranlsate it. var phrase = m[1] || m[2]; var code = this.cmd_translate.languages[m[3].toLowerCase()]; var language = $.utils.string.capitalize(m[3]); if (!code) { this.say("Sorry; I don't know how to speak " + language); return true; } try { var translation = $.utils.string.translate(phrase, code); this.say('"' + phrase + '" in ' + language + ' is "' + translation + '"'); } catch (e) { this.say('Sorry: I seem to have forotten how to speak ' + language + '.'); } return true; }; Object.setOwnerOf($.assistant.cmd_translate, $.physicals.Maximilian); Object.setOwnerOf($.assistant.cmd_translate.prototype, $.physicals.Maximilian); $.assistant.cmd_translate.languages = (new 'Object.create')(null); $.assistant.cmd_translate.languages.german = 'de'; $.assistant.cmd_translate.languages.italian = 'it'; $.assistant.cmd_translate.languages.french = 'fr'; $.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.'; $.assistant.description = "A squat grey cylinder that looks like it's listening."; $.assistant.location = undefined; $.assistant.lastActivated = undefined; $.physicals.assistant = $.assistant; ================================================ FILE: core/core_45_Challenge_Room.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Challenge room demo for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.physicals['Challenge room'] = (new 'Object.create')($.room); Object.setOwnerOf($.physicals['Challenge room'], $.physicals.Neil); $.physicals['Challenge room'].name = 'Challenge room'; $.physicals['Challenge room'].location = null; $.physicals['Challenge room'].contents_ = []; $.physicals['Challenge room'].contents_[0] = (new 'Object.create')($.thing); $.physicals['Challenge room'].contents_[1] = (new 'Object.create')($.container); $.physicals['Challenge room'].contents_[2] = (new 'Object.create')($.thing); $.physicals['Challenge room'].contents_.forObj = $.physicals['Challenge room']; Object.defineProperty($.physicals['Challenge room'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals['Challenge room'].contents_.forKey = 'contents_'; Object.defineProperty($.physicals['Challenge room'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.physicals['Challenge room'].reset = function reset(cmd) { this.switch.state = false; this.switch.movable = true; this.switch.moveTo(this); this.switch.movable = false; for (var x = 0; x < 1000; x++) { this.safe.setOpen(true, x); } this.food.moveTo(this.safe); this.food.svgText = this.food.svgTextReset; this.safe.setOpen(false); this.safe.crack = this.safe.crackReset; this.chest.movable = true; this.chest.moveTo(this); this.chest.movable = false; this.chest.setOpen(true); this.safe.moveTo(this.chest); this.chest.setOpen(false); this.girl.movable = true; this.girl.moveTo(this); this.girl.movable = false; this.girl.attempts = 0; if (cmd) { this.sendScene(cmd.user, true); this.narrate(cmd.user.name + ' resets ' + String(this) + '.', cmd.user); cmd.user.narrate('You reset ' + String(this) + '.'); } }; Object.setOwnerOf($.physicals['Challenge room'].reset, $.physicals.Neil); Object.setOwnerOf($.physicals['Challenge room'].reset.prototype, $.physicals.Neil); $.physicals['Challenge room'].reset.verb = 'reset'; $.physicals['Challenge room'].reset.dobj = 'none'; $.physicals['Challenge room'].reset.prep = 'none'; $.physicals['Challenge room'].reset.iobj = 'none'; $.physicals['Challenge room'].chest = $.physicals['Challenge room'].contents_[1]; $.physicals['Challenge room'].safe = (new 'Object.create')($.container); $.physicals['Challenge room'].girl = $.physicals['Challenge room'].contents_[2]; $.physicals['Challenge room'].food = (new 'Object.create')($.thing); $.physicals['Challenge room'].switch = $.physicals['Challenge room'].contents_[0]; $.physicals['Challenge room'].svgTextNight = '\n'; $.physicals['Challenge room'].getContents = function getContents() { $.physical.validate.call(this); if (this.switch.state) { return this.contents_.slice(); } else { var contents = []; for (var i = 0, o; (o = this.contents_[i]); i++) { if (o === this.switch || $.user.isPrototypeOf(o)) { contents.push(o); } } return contents; } }; Object.setOwnerOf($.physicals['Challenge room'].getContents, $.physicals.Neil); $.physicals['Challenge room'].description = function description() { return this.switch.state ? 'Can you solve the challenge?' : 'It\'s dark in here.'; }; Object.setOwnerOf($.physicals['Challenge room'].description, $.physicals.Neil); $.physicals['Challenge room'].svgTextDay = ''; $.physicals['Challenge room'].svgText = function svgText() { return this.switch.state ? this.svgTextDay : this.svgTextNight; }; Object.setOwnerOf($.physicals['Challenge room'].svgText, $.physicals.Neil); $.physicals['light switch'] = $.physicals['Challenge room'].switch; Object.setOwnerOf($.physicals['light switch'], $.physicals.Neil); $.physicals['light switch'].name = 'light switch'; $.physicals['light switch'].location = $.physicals['Challenge room']; $.physicals['light switch'].contents_ = []; $.physicals['light switch'].contents_.forObj = $.physicals['light switch']; Object.defineProperty($.physicals['light switch'].contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals['light switch'].contents_.forKey = 'contents_'; Object.defineProperty($.physicals['light switch'].contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.physicals['light switch'].svgText = function svgText() { return this.state ? this.svgTextDay : this.svgTextNight; }; Object.setOwnerOf($.physicals['light switch'].svgText, $.physicals.Neil); Object.setOwnerOf($.physicals['light switch'].svgText.prototype, $.physicals.Maximilian); $.physicals['light switch'].state = false; $.physicals['light switch'].flip = function flip(newState, user) { var onOff = newState ? 'on' : 'off'; if (this.state === newState) { user.narrate('The switch is already ' + onOff + '.'); } else { this.state = newState; this.home.updateScene(true); user.narrate('You turn ' + onOff + ' the switch.'); this.home.narrate(String(user) + ' turns ' + onOff + ' the switch.', user); } }; Object.setOwnerOf($.physicals['light switch'].flip, $.physicals.Neil); Object.setOwnerOf($.physicals['light switch'].flip.prototype, $.physicals.Neil); $.physicals['light switch'].flipOn1 = function flipOn1(cmd) { this.flip(true, cmd.user); }; Object.setOwnerOf($.physicals['light switch'].flipOn1, $.physicals.Maximilian); Object.setOwnerOf($.physicals['light switch'].flipOn1.prototype, $.physicals.Maximilian); $.physicals['light switch'].flipOn1.verb = 'flip|turn|switch'; $.physicals['light switch'].flipOn1.dobj = 'this'; $.physicals['light switch'].flipOn1.prep = 'on top of/on/onto/upon'; $.physicals['light switch'].flipOn1.iobj = 'none'; $.physicals['light switch'].flipOn2 = function flipOn2(cmd) { this.flip(true, cmd.user); }; Object.setOwnerOf($.physicals['light switch'].flipOn2, $.physicals.Maximilian); Object.setOwnerOf($.physicals['light switch'].flipOn2.prototype, $.physicals.Maximilian); $.physicals['light switch'].flipOn2.verb = 'flip|turn|switch'; $.physicals['light switch'].flipOn2.dobj = 'none'; $.physicals['light switch'].flipOn2.prep = 'on top of/on/onto/upon'; $.physicals['light switch'].flipOn2.iobj = 'this'; $.physicals['light switch'].flipOff2 = function flipOff2(cmd) { this.flip(false, cmd.user); }; Object.setOwnerOf($.physicals['light switch'].flipOff2, $.physicals.Maximilian); Object.setOwnerOf($.physicals['light switch'].flipOff2.prototype, $.physicals.Maximilian); $.physicals['light switch'].flipOff2.verb = 'flip|turn|switch'; $.physicals['light switch'].flipOff2.dobj = 'none'; $.physicals['light switch'].flipOff2.prep = 'off/off of'; $.physicals['light switch'].flipOff2.iobj = 'this'; $.physicals['light switch'].flipOff1 = function flipOff1(cmd) { this.flip(false, cmd.user); }; Object.setOwnerOf($.physicals['light switch'].flipOff1, $.physicals.Maximilian); Object.setOwnerOf($.physicals['light switch'].flipOff1.prototype, $.physicals.Maximilian); $.physicals['light switch'].flipOff1.verb = 'flip|turn|switch'; $.physicals['light switch'].flipOff1.dobj = 'this'; $.physicals['light switch'].flipOff1.prep = 'off/off of'; $.physicals['light switch'].flipOff1.iobj = 'none'; $.physicals['light switch'].home = $.physicals['Challenge room']; $.physicals['light switch'].svgTextNight = '\n \n \n \n'; $.physicals['light switch'].getCommands = function getCommands(who) { var commands = $.thing.getCommands.call(this, who); if (this.state) { commands.push('turn off ' + String(this)); } else { commands.push('turn on ' + String(this)); } return commands; }; Object.setOwnerOf($.physicals['light switch'].getCommands, $.physicals.Neil); Object.setOwnerOf($.physicals['light switch'].getCommands.prototype, $.physicals.Maximilian); $.physicals['light switch'].aliases = []; Object.setOwnerOf($.physicals['light switch'].aliases, $.physicals.Maximilian); $.physicals['light switch'].aliases[0] = 'lightswitch'; $.physicals['light switch'].aliases[1] = 'switch'; $.physicals['light switch'].movable = false; $.physicals['light switch'].svgTextDay = '\n\n\n\n'; $.physicals.chest = $.physicals['Challenge room'].chest; Object.setOwnerOf($.physicals.chest, $.physicals.Neil); $.physicals.chest.name = 'chest'; $.physicals.chest.location = $.physicals['Challenge room']; $.physicals.chest.contents_ = []; $.physicals.chest.contents_[0] = $.physicals.chest.location.safe; $.physicals.chest.contents_.forObj = $.physicals.chest; Object.defineProperty($.physicals.chest.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals.chest.contents_.forKey = 'contents_'; Object.defineProperty($.physicals.chest.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.physicals.chest.svgTextClosed = '\n\n\n\n\n'; $.physicals.chest.svgTextOpen = '\n\n\n\n\n\n\n'; $.physicals.chest.isOpen = false; $.physicals.chest.description = 'A steamer chest with a very heavy lid.'; $.physicals.chest.TIME = 5000; $.physicals.chest.lastTime_ = 1597444509970; $.physicals.chest.lastUser_ = $.physicals.Neil; $.physicals.chest.open = function open(cmd) { if (this.isOpen) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.'); return; } if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.'); return; } if (this.lastUser_ === cmd.user || this.lastTime_ + this.TIME < Date.now()) { cmd.user.narrate('You try to open the chest, but the lid is too heavy for one person.'); if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' tries to open the chest, but the lid is too heavy for one person.', cmd.user); } this.lastUser_ = cmd.user; this.lastTime_ = Date.now(); return; } if (!this.setOpen(true)) { cmd.user.narrate('You can\'t open ' + String(cmd.dobj)); return; } if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' helps ' + String(this.lastUser_.name) + ' to opens ' + String(cmd.dobj) + '.', cmd.user); } cmd.user.narrate('You help ' + String(this.lastUser_) + ' to open ' + String(cmd.dobj) + '.'); this.look(cmd); this.lastUser_ = null; this.lastTime_ = 0; }; Object.setOwnerOf($.physicals.chest.open, $.physicals.Neil); Object.setOwnerOf($.physicals.chest.open.prototype, $.physicals.Maximilian); $.physicals.chest.open.verb = 'open'; $.physicals.chest.open.dobj = 'this'; $.physicals.chest.open.prep = 'none'; $.physicals.chest.open.iobj = 'none'; $.physicals.chest.movable = false; $.physicals.chest.toFloor = true; $.physicals.chest.setOpen = function setOpen(newState) { this.isOpen = Boolean(newState); if ($.room.isPrototypeOf(this.location)) { this.location.updateScene(true); } return true; }; Object.setOwnerOf($.physicals.chest.setOpen, $.physicals.Neil); Object.setOwnerOf($.physicals.chest.setOpen.prototype, $.physicals.Maximilian); $.physicals.safe = $.physicals.chest.location.safe; Object.setOwnerOf($.physicals.safe, $.physicals.Neil); $.physicals.safe.name = 'safe'; $.physicals.safe.location = $.physicals.chest; $.physicals.safe.contents_ = []; $.physicals.safe.contents_[0] = $.physicals.chest.location.food; $.physicals.safe.contents_.forObj = $.physicals.safe; Object.defineProperty($.physicals.safe.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals.safe.contents_.forKey = 'contents_'; Object.defineProperty($.physicals.safe.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.physicals.safe.isOpen = false; $.physicals.safe.description = 'The safe is secured with a three digit combination: open safe with xxx'; $.physicals.safe.open = function open(cmd) { cmd.user.narrate('You need a three-digit combination to open the safe: open ' + String(cmd.dobj) + ' with xxx'); }; Object.setOwnerOf($.physicals.safe.open, $.physicals.Maximilian); Object.setOwnerOf($.physicals.safe.open.prototype, $.physicals.Maximilian); $.physicals.safe.open.verb = 'open'; $.physicals.safe.open.dobj = 'this'; $.physicals.safe.open.prep = 'none'; $.physicals.safe.open.iobj = 'none'; $.physicals.safe.openWith = function openWith(cmd) { if (this.isOpen) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is already open.'); return; } if (this.location !== cmd.user.location && this.location !== cmd.user) { cmd.user.narrate($.utils.string.capitalize(String(cmd.dobj)) + ' is not here.'); return; } if (!this.setOpen(true, cmd.iobjstr)) { cmd.user.narrate('"' + cmd.iobjstr + '" is not the correct combination.'); return; } if (cmd.user.location) { cmd.user.location.narrate(cmd.user.name + ' opens ' + String(cmd.dobj) + '.', cmd.user); } cmd.user.narrate('You open ' + String(cmd.dobj) + '.'); this.look(cmd); }; Object.setOwnerOf($.physicals.safe.openWith, $.physicals.Maximilian); Object.setOwnerOf($.physicals.safe.openWith.prototype, $.physicals.Maximilian); $.physicals.safe.openWith.verb = 'open'; $.physicals.safe.openWith.dobj = 'this'; $.physicals.safe.openWith.prep = 'with/using'; $.physicals.safe.openWith.iobj = 'any'; $.physicals.safe.setOpen = function setOpen(newState, combo) { if (newState && this.combo !== $.utils.string.hash('md5', String(combo))) { return false; } return $.container.setOpen.call(this, newState); }; Object.setOwnerOf($.physicals.safe.setOpen, $.physicals.Neil); Object.setOwnerOf($.physicals.safe.setOpen.prototype, $.physicals.Maximilian); $.physicals.safe.combo = 'e94550c93cd70fe748e6982b3439ad3b'; $.physicals.safe.svgTextClosed = '\n\n\n\n'; $.physicals.safe.svgTextOpen = '\n\n\n\n\n'; $.physicals.safe.getCommands = function getCommands(who) { var commands = $.container.getCommands.call(this, who); commands.push('crack ' + String(this)); return commands; }; Object.setOwnerOf($.physicals.safe.getCommands, $.physicals.Neil); Object.setOwnerOf($.physicals.safe.getCommands.prototype, $.physicals.Maximilian); $.physicals.safe.crack = function crack(cmd) { cmd.user.narrate('The "crack" function has not been programmed. ' + 'To do so, visit: https://google.codecity.world/blocklySafe'); // API information: To open the safe with combo 123, use: // this.setOpen(true, 123); // Have fun! }; Object.setOwnerOf($.physicals.safe.crack, $.physicals.Neil); Object.setOwnerOf($.physicals.safe.crack.prototype, $.physicals.Neil); $.physicals.safe.crack.verb = 'crack'; $.physicals.safe.crack.dobj = 'this'; $.physicals.safe.crack.prep = 'none'; $.physicals.safe.crack.iobj = 'none'; $.physicals.safe.crackReset = $.physicals.safe.crack; $.physicals.safe.toFloor = true; $.physicals.food = $.physicals.chest.location.food; Object.setOwnerOf($.physicals.food, $.physicals.Neil); $.physicals.food.name = 'food'; $.physicals.food.location = $.physicals.safe; $.physicals.food.contents_ = []; $.physicals.food.contents_.forObj = $.physicals.food; Object.defineProperty($.physicals.food.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals.food.contents_.forKey = 'contents_'; Object.defineProperty($.physicals.food.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.physicals.food.svgText = '\n\n'; $.physicals.food.give = function give(cmd) { if (cmd.iobj !== this.girl) { return $.thing.give.call(this, cmd); } if (this.location !== cmd.user && this.location !== cmd.user.location) { cmd.user.narrate("You can't reach " + String(this) + "."); return; } cmd.user.narrate('You offer ' + String(this) + ' to ' + String(cmd.iobj) + '.'); if (cmd.user.location) { cmd.user.location.narrate( String(cmd.user) + ' offers ' + String(this) + ' to ' + String(cmd.iobj) + '.', [cmd.user, cmd.iobj]); } var matches = $.utils.imageMatch.recog($.utils.object.getValue(this, 'svgText')); var ok = this.girl.foodList.includes(matches[0]); if (!ok) { this.girl.attempts++; } var name = matches[0] || 'nothing I\'ve ever seen before.'; suspend(1); var text = 'It looks like a ' + name + '; ' + (ok ? 'delicious!' : (this.girl.attempts < 3 ? 'I won\'t eat that!' : (Math.random() >= 0.5 ? 'that won\'t keep the doctor away!' : 'some fruit would be nice!' ) ) ); var alt = 'The girl says, "' + text +'"'; var memo = { type: 'say', source: this.girl, where: this.girl.location, text: text, alt: alt }; this.girl.location.sendMemo(memo); if (ok) { suspend(10); memo.text = 'Thank you so much. Congratulations on solving the challenge room. Don\'t forget to turn out the light when you leave.'; memo.alt = 'The girl says, "' + text + '"'; this.girl.location.sendMemo(memo); } }; Object.setOwnerOf($.physicals.food.give, $.physicals.Neil); Object.setOwnerOf($.physicals.food.give.prototype, $.physicals.Maximilian); $.physicals.food.give.verb = 'give'; $.physicals.food.give.dobj = 'this'; $.physicals.food.give.prep = 'at/to'; $.physicals.food.give.iobj = 'any'; $.physicals.food.girl = $.physicals.chest.location.girl; $.physicals.food.redraw = function inspect(cmd) { // Open this object in the SVG editor. var selector = $.Selector.for(this); if (!selector) { cmd.user.narrate('Unfortuantely the code editor does not know how to locate ' + String(this) + ' yet.'); return; } var link = '/code?' + encodeURIComponent(String(selector) + '.svgText'); cmd.user.readMemo({type: "link", href: link}); }; Object.setOwnerOf($.physicals.food.redraw, $.physicals.Neil); Object.setOwnerOf($.physicals.food.redraw.prototype, $.physicals.Neil); $.physicals.food.redraw.verb = 'redraw'; $.physicals.food.redraw.dobj = 'this'; $.physicals.food.redraw.prep = 'none'; $.physicals.food.redraw.iobj = 'none'; $.physicals.food.getCommands = function getCommands(who) { var commands = $.thing.getCommands.call(this, who); commands.push('redraw ' + this.name); commands.push('give ' + this.name + ' to girl'); return commands; }; Object.setOwnerOf($.physicals.food.getCommands, $.physicals.Neil); Object.setOwnerOf($.physicals.food.getCommands.prototype, $.physicals.Maximilian); $.physicals.food.svgTextReset = '\n\n'; $.physicals.girl = $.physicals.food.girl; Object.setOwnerOf($.physicals.girl, $.physicals.Neil); $.physicals.girl.name = 'girl'; $.physicals.girl.location = $.physicals.chest.location; $.physicals.girl.contents_ = []; $.physicals.girl.contents_.forObj = $.physicals.girl; Object.defineProperty($.physicals.girl.contents_, 'forObj', {writable: false, enumerable: false, configurable: false}); $.physicals.girl.contents_.forKey = 'contents_'; Object.defineProperty($.physicals.girl.contents_, 'forKey', {writable: false, enumerable: false, configurable: false}); $.physicals.girl.description = 'She looks REALLY hungry.'; $.physicals.girl.svgText = ' \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n'; $.physicals.girl.get = function get(cmd) { cmd.user.narrate('That\'s probably not appropriate.'); if (cmd.user.location) { cmd.user.location.narrate(String(cmd.user) + ' tries to pick up ' + String(this) + '.', cmd.user); } }; Object.setOwnerOf($.physicals.girl.get, $.physicals.Neil); Object.setOwnerOf($.physicals.girl.get.prototype, $.physicals.Maximilian); $.physicals.girl.get.verb = 'get|take'; $.physicals.girl.get.dobj = 'this'; $.physicals.girl.get.prep = 'none'; $.physicals.girl.get.iobj = 'none'; $.physicals.girl.food = $.physicals.food; $.physicals.girl.foodList = []; $.physicals.girl.foodList[0] = 'Açaí'; $.physicals.girl.foodList[1] = 'Ackee'; $.physicals.girl.foodList[2] = 'Apple'; $.physicals.girl.foodList[3] = 'Apricot'; $.physicals.girl.foodList[4] = 'Avocado'; $.physicals.girl.foodList[5] = 'Banana'; $.physicals.girl.foodList[6] = 'Bilberry'; $.physicals.girl.foodList[7] = 'Blackberry'; $.physicals.girl.foodList[8] = 'Blackcurrant'; $.physicals.girl.foodList[9] = 'Black sapote'; $.physicals.girl.foodList[10] = 'Blueberry'; $.physicals.girl.foodList[11] = 'Boysenberry'; $.physicals.girl.foodList[12] = 'Breadfruit'; $.physicals.girl.foodList[13] = "Buddha's hand"; $.physicals.girl.foodList[14] = 'Cactus pear'; $.physicals.girl.foodList[15] = 'Crab apple'; $.physicals.girl.foodList[16] = 'Currant'; $.physicals.girl.foodList[17] = 'Cherry'; $.physicals.girl.foodList[18] = 'Cherimoya'; $.physicals.girl.foodList[19] = 'Chico fruit'; $.physicals.girl.foodList[20] = 'Cloudberry'; $.physicals.girl.foodList[21] = 'Coconut'; $.physicals.girl.foodList[22] = 'Cranberry'; $.physicals.girl.foodList[23] = 'Damson'; $.physicals.girl.foodList[24] = 'Date'; $.physicals.girl.foodList[25] = 'Dragonfruit'; $.physicals.girl.foodList[26] = 'Durian'; $.physicals.girl.foodList[27] = 'Elderberry'; $.physicals.girl.foodList[28] = 'Feijoa'; $.physicals.girl.foodList[29] = 'Fig'; $.physicals.girl.foodList[30] = 'Goji berry'; $.physicals.girl.foodList[31] = 'Gooseberry'; $.physicals.girl.foodList[32] = 'Grape'; $.physicals.girl.foodList[33] = 'Grewia asiatica'; $.physicals.girl.foodList[34] = 'Raisin'; $.physicals.girl.foodList[35] = 'Grapefruit'; $.physicals.girl.foodList[36] = 'Guava'; $.physicals.girl.foodList[37] = 'Hala Fruit'; $.physicals.girl.foodList[38] = 'Honeyberry'; $.physicals.girl.foodList[39] = 'Huckleberry'; $.physicals.girl.foodList[40] = 'Jabuticaba'; $.physicals.girl.foodList[41] = 'Jackfruit'; $.physicals.girl.foodList[42] = 'Jambul'; $.physicals.girl.foodList[43] = 'Japanese plum'; $.physicals.girl.foodList[44] = 'Jostaberry'; $.physicals.girl.foodList[45] = 'Jujube'; $.physicals.girl.foodList[46] = 'Juniper berry'; $.physicals.girl.foodList[47] = 'Kiwano'; $.physicals.girl.foodList[48] = 'Kiwifruit'; $.physicals.girl.foodList[49] = 'Kumquat'; $.physicals.girl.foodList[50] = 'Lemon'; $.physicals.girl.foodList[51] = 'Lime'; $.physicals.girl.foodList[52] = 'Loganberry'; $.physicals.girl.foodList[53] = 'Loquat'; $.physicals.girl.foodList[54] = 'Longan'; $.physicals.girl.foodList[55] = 'Lychee'; $.physicals.girl.foodList[56] = 'Mango'; $.physicals.girl.foodList[57] = 'Mangosteen'; $.physicals.girl.foodList[58] = 'Marionberry'; $.physicals.girl.foodList[59] = 'Melon'; $.physicals.girl.foodList[60] = 'Cantaloupe'; $.physicals.girl.foodList[61] = 'Galia melon'; $.physicals.girl.foodList[62] = 'Honeydew'; $.physicals.girl.foodList[63] = 'Watermelon'; $.physicals.girl.foodList[64] = 'Miracle fruit'; $.physicals.girl.foodList[65] = 'Monstera Delisiousa'; $.physicals.girl.foodList[66] = 'Mulberry'; $.physicals.girl.foodList[67] = 'Nance'; $.physicals.girl.foodList[68] = 'Nectarine'; $.physicals.girl.foodList[69] = 'Orange'; $.physicals.girl.foodList[70] = 'Blood orange'; $.physicals.girl.foodList[71] = 'Clementine'; $.physicals.girl.foodList[72] = 'Mandarine'; $.physicals.girl.foodList[73] = 'Tangerine'; $.physicals.girl.foodList[74] = 'Papaya'; $.physicals.girl.foodList[75] = 'Passionfruit'; $.physicals.girl.foodList[76] = 'Peach'; $.physicals.girl.foodList[77] = 'Pear'; $.physicals.girl.foodList[78] = 'Persimmon'; $.physicals.girl.foodList[79] = 'Plantain'; $.physicals.girl.foodList[80] = 'Plum'; $.physicals.girl.foodList[81] = 'Prune'; $.physicals.girl.foodList[82] = 'Pineapple'; $.physicals.girl.foodList[83] = 'Pineberry'; $.physicals.girl.foodList[84] = 'Plumcot'; $.physicals.girl.foodList[85] = 'Pomegranate'; $.physicals.girl.foodList[86] = 'Pomelo'; $.physicals.girl.foodList[87] = 'Purple mangosteen'; $.physicals.girl.foodList[88] = 'Quince'; $.physicals.girl.foodList[89] = 'Raspberry'; $.physicals.girl.foodList[90] = 'Salmonberry'; $.physicals.girl.foodList[91] = 'Rambutan'; $.physicals.girl.foodList[92] = 'Redcurrant'; $.physicals.girl.foodList[93] = 'Salal berry'; $.physicals.girl.foodList[94] = 'Salak'; $.physicals.girl.foodList[95] = 'Satsuma'; $.physicals.girl.foodList[96] = 'Soursop'; $.physicals.girl.foodList[97] = 'Star apple'; $.physicals.girl.foodList[98] = 'Star fruit'; $.physicals.girl.foodList[99] = 'Strawberry'; $.physicals.girl.foodList[100] = 'Surinam cherry'; $.physicals.girl.foodList[101] = 'Tamarillo'; $.physicals.girl.foodList[102] = 'Tamarind'; $.physicals.girl.foodList[103] = 'Tangelo'; $.physicals.girl.foodList[104] = 'Tayberry'; $.physicals.girl.foodList[105] = 'Ugli fruit'; $.physicals.girl.foodList[106] = 'White currant'; $.physicals.girl.foodList[107] = 'White sapote'; $.physicals.girl.foodList[108] = 'Yuzu'; $.physicals.girl.foodList[109] = 'Bell pepper'; $.physicals.girl.foodList[110] = 'Chile pepper'; $.physicals.girl.foodList[111] = 'Corn kernel'; $.physicals.girl.foodList[112] = 'Cucumber'; $.physicals.girl.foodList[113] = 'Eggplant'; $.physicals.girl.foodList[114] = 'Jalapeño'; $.physicals.girl.foodList[115] = 'Olive'; $.physicals.girl.foodList[116] = 'Pea'; $.physicals.girl.foodList[117] = 'Pumpkin'; $.physicals.girl.foodList[118] = 'Squash'; $.physicals.girl.foodList[119] = 'Tomato'; $.physicals.girl.foodList[120] = 'Zucchini'; $.physicals.girl.foodList[121] = 'asparagus'; $.physicals.girl.foodList[122] = 'apple'; $.physicals.girl.foodList[123] = 'avocado'; $.physicals.girl.foodList[124] = 'alfalfa'; $.physicals.girl.foodList[125] = 'almond'; $.physicals.girl.foodList[126] = 'arugula'; $.physicals.girl.foodList[127] = 'artichoke'; $.physicals.girl.foodList[128] = 'applesauce'; $.physicals.girl.foodList[129] = 'antelope'; $.physicals.girl.foodList[130] = 'bruscetta'; $.physicals.girl.foodList[131] = 'bacon'; $.physicals.girl.foodList[132] = 'black beans'; $.physicals.girl.foodList[133] = 'bagels'; $.physicals.girl.foodList[134] = 'baked beans'; $.physicals.girl.foodList[135] = 'bbq'; $.physicals.girl.foodList[136] = 'bison'; $.physicals.girl.foodList[137] = 'barley'; $.physicals.girl.foodList[138] = 'beer'; $.physicals.girl.foodList[139] = 'bisque'; $.physicals.girl.foodList[140] = 'bluefish'; $.physicals.girl.foodList[141] = 'bread'; $.physicals.girl.foodList[142] = 'broccoli'; $.physicals.girl.foodList[143] = 'buritto'; $.physicals.girl.foodList[144] = 'babaganoosh'; $.physicals.girl.foodList[145] = 'cabbage'; $.physicals.girl.foodList[146] = 'cake'; $.physicals.girl.foodList[147] = 'carrots'; $.physicals.girl.foodList[148] = 'carne asada'; $.physicals.girl.foodList[149] = 'celery'; $.physicals.girl.foodList[150] = 'cheese'; $.physicals.girl.foodList[151] = 'chicken'; $.physicals.girl.foodList[152] = 'catfish'; $.physicals.girl.foodList[153] = 'cheeseburger'; $.physicals.girl.foodList[154] = 'chips'; $.physicals.girl.foodList[155] = 'chocolate'; $.physicals.girl.foodList[156] = 'chowder'; $.physicals.girl.foodList[157] = 'clams'; $.physicals.girl.foodList[158] = 'coffee'; $.physicals.girl.foodList[159] = 'cookie'; $.physicals.girl.foodList[160] = 'corn'; $.physicals.girl.foodList[161] = 'cupcake'; $.physicals.girl.foodList[162] = 'crab'; $.physicals.girl.foodList[163] = 'curry'; $.physicals.girl.foodList[164] = 'cereal'; $.physicals.girl.foodList[165] = 'chimichanga'; $.physicals.girl.foodList[166] = 'dates'; $.physicals.girl.foodList[167] = 'dips'; $.physicals.girl.foodList[168] = 'duck'; $.physicals.girl.foodList[169] = 'dumpling'; $.physicals.girl.foodList[170] = 'donuts'; $.physicals.girl.foodList[171] = 'eggs'; $.physicals.girl.foodList[172] = 'enchilada'; $.physicals.girl.foodList[173] = 'eggroll'; $.physicals.girl.foodList[174] = 'english muffin'; $.physicals.girl.foodList[175] = 'edamame'; $.physicals.girl.foodList[176] = 'eel sushi'; $.physicals.girl.foodList[177] = 'fajita'; $.physicals.girl.foodList[178] = 'falafel'; $.physicals.girl.foodList[179] = 'fish'; $.physicals.girl.foodList[180] = 'franks'; $.physicals.girl.foodList[181] = 'fondu'; $.physicals.girl.foodList[182] = 'french toast'; $.physicals.girl.foodList[183] = 'french dip'; $.physicals.girl.foodList[184] = 'garlic'; $.physicals.girl.foodList[185] = 'ginger'; $.physicals.girl.foodList[186] = 'gnocchi'; $.physicals.girl.foodList[187] = 'goose'; $.physicals.girl.foodList[188] = 'granola'; $.physicals.girl.foodList[189] = 'grapes'; $.physicals.girl.foodList[190] = 'green beans'; $.physicals.girl.foodList[191] = 'guacamole'; $.physicals.girl.foodList[192] = 'gumbo'; $.physicals.girl.foodList[193] = 'grits'; $.physicals.girl.foodList[194] = 'graham crackers'; $.physicals.girl.foodList[195] = 'ham'; $.physicals.girl.foodList[196] = 'halibut'; $.physicals.girl.foodList[197] = 'hamburger'; $.physicals.girl.foodList[198] = 'honey'; $.physicals.girl.foodList[199] = 'huenos rancheros'; $.physicals.girl.foodList[200] = 'hash browns'; $.physicals.girl.foodList[201] = 'hot dogs'; $.physicals.girl.foodList[202] = 'haiku roll'; $.physicals.girl.foodList[203] = 'hummus'; $.physicals.girl.foodList[204] = 'ice cream'; $.physicals.girl.foodList[205] = 'irish stew'; $.physicals.girl.foodList[206] = 'indian food'; $.physicals.girl.foodList[207] = 'italian bread'; $.physicals.girl.foodList[208] = 'jambalaya'; $.physicals.girl.foodList[209] = 'jelly'; $.physicals.girl.foodList[210] = 'jam'; $.physicals.girl.foodList[211] = 'jerky'; $.physicals.girl.foodList[212] = 'jalapeño'; $.physicals.girl.foodList[213] = 'kale'; $.physicals.girl.foodList[214] = 'kabobs'; $.physicals.girl.foodList[215] = 'ketchup'; $.physicals.girl.foodList[216] = 'kiwi'; $.physicals.girl.foodList[217] = 'kidney beans'; $.physicals.girl.foodList[218] = 'kingfish'; $.physicals.girl.foodList[219] = 'lobster'; $.physicals.girl.foodList[220] = 'lamb'; $.physicals.girl.foodList[221] = 'linguine'; $.physicals.girl.foodList[222] = 'lasagna'; $.physicals.girl.foodList[223] = 'meatballs'; $.physicals.girl.foodList[224] = 'moose'; $.physicals.girl.foodList[225] = 'milk'; $.physicals.girl.foodList[226] = 'milkshake'; $.physicals.girl.foodList[227] = 'noodles'; $.physicals.girl.foodList[228] = 'ostrich'; $.physicals.girl.foodList[229] = 'pizza'; $.physicals.girl.foodList[230] = 'pepperoni'; $.physicals.girl.foodList[231] = 'porter'; $.physicals.girl.foodList[232] = 'pancakes'; $.physicals.girl.foodList[233] = 'quesadilla'; $.physicals.girl.foodList[234] = 'quiche'; $.physicals.girl.foodList[235] = 'reuben'; $.physicals.girl.foodList[236] = 'spinach'; $.physicals.girl.foodList[237] = 'spaghetti'; $.physicals.girl.foodList[238] = 'tater tots'; $.physicals.girl.foodList[239] = 'toast'; $.physicals.girl.foodList[240] = 'venison'; $.physicals.girl.foodList[241] = 'waffles'; $.physicals.girl.foodList[242] = 'wine'; $.physicals.girl.foodList[243] = 'walnuts'; $.physicals.girl.foodList[244] = 'yogurt'; $.physicals.girl.foodList[245] = 'ziti'; $.physicals.girl.foodList[246] = 'zucchini'; $.physicals.girl.foodList[247] = 'string bean'; $.physicals.girl.foodList[248] = 'birthday cake'; $.physicals.girl.foodList[249] = 'pear'; $.physicals.girl.foodList[250] = 'steak'; $.physicals.girl.foodList[251] = 'peanut'; $.physicals.girl.foodList[252] = 'hot dog'; $.physicals.girl.willAccept = function willAccept(what, src) { /* Returns true iff this is willing to accept what arriving from src. * * This function (or its overrides) MUST NOT have any kind of * observable side-effect (making noise, causing some other action, * etc.). */ return what === this.food; }; Object.setOwnerOf($.physicals.girl.willAccept, $.physicals.Maximilian); Object.setOwnerOf($.physicals.girl.willAccept.prototype, $.physicals.Maximilian); $.physicals.girl.movable = false; $.physicals.girl.attempts = 0; ================================================ FILE: core/core_46_$.secuityCourse.js ================================================ /** * @license * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Security course demo for Code City. */ ////////////////////////////////////////////////////////////////////// // AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION! ////////////////////////////////////////////////////////////////////// $.securityCourse = {}; Object.setOwnerOf($.securityCourse, $.physicals.Neil); $.securityCourse.StoreHost = function StoreHost() { /* A $.servers.http.Host subclass for per-user stores for the security * course. */ $.servers.http.Host.call(this); var user = Object.getOwnerOf(this); if (!($.user.isPrototypeOf(user))) { throw new TypeError('new store must be owned by a $.user'); } var hostname = user.name.toLowerCase(); if (hostname in $.securityCourse.storeHosts) { throw new RangeError('a store named ' + hostname + ' already exists'); } else if (hostname in $.hosts.root.subdomains) { throw new RangeError('the subdomain ' + hostname + ' is already in use'); } (function inner() { // Run set-up with non-privileged perms. setPerms(user); var store = Object.create($.securityCourse.storePagePrototype); store.name = user.name + "'s Store"; this['/'] = store; }).call(this); $.securityCourse.storeHosts[hostname] = this; $.hosts.root.addSubdomain(hostname, this); }; Object.setOwnerOf($.securityCourse.StoreHost, $.physicals.Maximilian); Object.setPrototypeOf($.securityCourse.StoreHost.prototype, $.servers.http.Host.prototype); Object.setOwnerOf($.securityCourse.StoreHost.prototype, $.physicals.Maximilian); $.securityCourse.StoreHost.prototype.destroy = function destroy() { if (!(this instanceof $.securityCourse.StoreHost)) { throw new TypeError('destroy must be called on a StoreHost'); } var callerPerms = Thread.callers()[0].callerPerms; if(Object.getOwnerOf(this) !== callerPerms) { throw new PermissionError('can only be deleted by owner'); } $.hosts.root.deleteSubdomain(this); var stores = $.securityCourse.storeHosts; for (var key in stores) { if (stores[key] === this) { delete stores[key]; } } }; Object.setOwnerOf($.securityCourse.StoreHost.prototype.destroy, $.physicals.Maximilian); Object.setOwnerOf($.securityCourse.StoreHost.prototype.destroy.prototype, $.physicals.Maximilian); $.securityCourse.storePagePrototype = {}; Object.setOwnerOf($.securityCourse.storePagePrototype, $.physicals.Neil); $.securityCourse.storePagePrototype.www = function www(request, response) { // This is a routing function. There's nothing interesting here. Honest. var prop = { 'basket': 'wwwBasket', 'confirm': 'wwwConfirm', }[request.parameters.page] || 'wwwHome'; $.jssp.eval(this, prop, request, response); }; Object.setOwnerOf($.securityCourse.storePagePrototype.www, $.physicals.Maximilian); Object.setOwnerOf($.securityCourse.storePagePrototype.www.prototype, $.physicals.Neil); $.securityCourse.storePagePrototype.name = 'Security Store'; $.securityCourse.storePagePrototype.inventory = []; Object.setOwnerOf($.securityCourse.storePagePrototype.inventory, $.physicals.Neil); $.securityCourse.storePagePrototype.inventory[0] = {}; Object.setOwnerOf($.securityCourse.storePagePrototype.inventory[0], $.physicals.Neil); $.securityCourse.storePagePrototype.inventory[0].name = 'Beach ball'; $.securityCourse.storePagePrototype.inventory[0].price = '2.75'; $.securityCourse.storePagePrototype.inventory[0].id = 'yYrq3jVfWK'; $.securityCourse.storePagePrototype.inventory[0].public = true; $.securityCourse.storePagePrototype.inventory[0].img = 'beachball.png'; $.securityCourse.storePagePrototype.inventory[1] = {}; Object.setOwnerOf($.securityCourse.storePagePrototype.inventory[1], $.physicals.Neil); $.securityCourse.storePagePrototype.inventory[1].name = 'Flip flops'; $.securityCourse.storePagePrototype.inventory[1].price = '8.50'; $.securityCourse.storePagePrototype.inventory[1].id = 'GSaYngk5Jn'; $.securityCourse.storePagePrototype.inventory[1].public = true; $.securityCourse.storePagePrototype.inventory[1].img = 'flipflops.png'; $.securityCourse.storePagePrototype.inventory[2] = {}; Object.setOwnerOf($.securityCourse.storePagePrototype.inventory[2], $.physicals.Neil); $.securityCourse.storePagePrototype.inventory[2].name = 'Nuclear waste'; $.securityCourse.storePagePrototype.inventory[2].price = '666'; $.securityCourse.storePagePrototype.inventory[2].id = 'iu9i5GvLeJ'; $.securityCourse.storePagePrototype.inventory[2].public = false; $.securityCourse.storePagePrototype.inventory[2].img = 'radioactive.png'; $.securityCourse.storePagePrototype.inventory[3] = {}; Object.setOwnerOf($.securityCourse.storePagePrototype.inventory[3], $.physicals.Neil); $.securityCourse.storePagePrototype.inventory[3].name = 'Guitar'; $.securityCourse.storePagePrototype.inventory[3].price = '24.30'; $.securityCourse.storePagePrototype.inventory[3].id = 'uazSOLHfkt'; $.securityCourse.storePagePrototype.inventory[3].public = true; $.securityCourse.storePagePrototype.inventory[3].img = 'guitar.png'; $.securityCourse.storePagePrototype.wwwHome = '<% include(\'header\'); %>\n

<%= this.name %> Home

\n\n
\n\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

\n \n

<%=item.name%>
\n
<%=item.price%>
\n
Quantity:
\n

\n<% } %>\n\n

\n \n

\n
\n \n<% include(\'footer\'); %>'; $.securityCourse.storePagePrototype.wwwBasket = '<% include(\'header\'); %>\n

<%= this.name %> Basket

\n\n\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\n \n \n \n \n<% } %>\n
<%=item.name%><%=quant%> x <%=item.price%> = <%=lineTotal%>
\n\n

Total: <%=total%>

\n\n
\n\n\'>\n\n\n

\n Name: \n

\n

\n Credit card:
\n (Don\'t enter a real card number, \'123\' is fine.)\n

\n

\n \n

\n
\n \n<% include(\'footer\'); %>'; $.securityCourse.storePagePrototype.wwwConfirm = "<% include('header'); %>\n

<%= this.name %> Confirm

\n\n

Thank you <%=request.parameters.name%>!

\n

Your credit card has been billed for <%=request.parameters.total%>.

\n

Your order will be shipped as soon as this store's massive security holes have been patched.

\n\n<% include('footer'); %>"; $.securityCourse.storePagePrototype.escape = $.utils.html.escape; $.securityCourse.storePagePrototype.header = '\n \n Security Store\n \n \n \n '; $.securityCourse.storePagePrototype.footer = '
\n
\n \n \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\n\n \n engEDU Security Course\n \n \n \n \n \n \n

engEDU Security Course

\n \n <% if (!storeKey) { %>\n

\n

\n To join the course, click \n \n
\n

\n <% } %>\n\n <% if (Object.getOwnPropertyNames(storeHosts).length) { %>\n

\n \n \n \n \n <%\n for (var hostName in storeHosts) {\n var storeName = storeHosts[hostName][\'/\'].name;\n %>\n \n \n \n <% } %>\n \n <% } %>\n
Stores in this class
\n <%= $.securityCourse.storePagePrototype.escape(storeName) %>\n " target="_blank" rel="noopener">Code\n <% if (hostName === storeKey) { %>\n \n
\n \n
\n
\n

\n <% } %>\n

\n \n

\n \n'; $.securityCourse.storeHosts = (new 'Object.create')(null); $.hosts.root['/securitycourse'] = $.securityCourse; ================================================ FILE: core/core_99_startup.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Start core database. Note that, unlike most of the * rest of the files in the core/ directory, this is hand-written. * * It assumed this file will be used when starting a full database * dump; for that, a file in database/, generated by dump, will * restart listeners intead. */ /* Optional (but recommended) configuration. The web server is * capable of guessing its own hostname, but will be more efficient * and secure if its configuration is specified explicitly. */ /* Set .hostname to the canonical hostname (including the port number, * if non-default). */ // $.hosts.root.hostname = 'example.codecity.world'; // $.hosts.root.hostname = 'localhost:8080'; /* If your host has more than one name, set .hostRegExp to a regular * expression that matches all valid name+port combinations for this * host. It is recommended that it end with /$/, but do NOT start it * with /^/ unless you want to break wildcard subdomains. Make sure * it matches .hostname! */ // Accept either of two different hostnames. // $.hosts.root.hostRegExp = /example.codecity.world$|codecity.example.com$/; // Match any TLD and optional port. // $.hosts.root.hostRegExp = /example.codecity.\w+(?::\d+)?$/; /* Set .pathToSubdomain to true if you don't have a wildcard DNS entry * and wildcard TLS certificate for your hostname (false if you do); * this will enable accessing pages usually served on subdomains (such * as the code editor) via the root hostname instead. * * Normally the nginx reverse proxy sends a CodeCity-pathToSubdomain * header which will automatically enable or disable this feature, but * you can override it here. */ // $.hosts.root.pathToSubdomain = false; // Set up. $.system.onStartup(); // Tidy up. $.clock.movable = true; $.clock.moveTo($.startRoom); $.clock.movable = false; $.tutorial.moveTo($.startRoom); $.tutorial.reset(); $.pot.moveTo($.startRoom); $.pot.stage = 0; $.seed.moveTo($.startRoom); $.thrower.moveTo($.startRoom); $.cage.moveTo($.physicals['Genetics Lab']); $.assistant.moveTo($.startRoom); ================================================ FILE: core/dump_spec.json ================================================ [ { "options": {"skipBindings": ["lastModifiedTime", "lastModifiedUser"]} }, { "header": [ "/**", " * @license", " * Copyright Google LLC", " *", " * Licensed under the Apache License, Version 2.0 (the \"License\");", " * you may not use this file except in compliance with the License.", " * You may obtain a copy of the License at", " *", " * http://www.apache.org/licenses/LICENSE-2.0", " *", " * Unless required by applicable law or agreed to in writing, software", " * distributed under the License is distributed on an \"AS IS\" BASIS,", " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.", " * See the License for the specific language governing permissions and", " * limitations under the License.", " */", "", "/**", " * @fileoverview ", " */", "", "//////////////////////////////////////////////////////////////////////", "// AUTO-GENERATED CODE FROM DUMP. EDIT WITH CAUTION!", "//////////////////////////////////////////////////////////////////////", "\n" ], "filename": "../var/dump/core_00_es5.js", "headerSubs": { "": "2017", "": [ "Load builtins and add polyfills to bring the server's partial", " * JavaScript implementation up to ECMAScript 5.1 (or close to it)." ] }, "contents": [ "Object", "Function", "Array", "String", "Boolean", "Number", "Date", "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "Math", "JSON", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "escape", "isFinite", "isNaN", "parseFloat", "parseInt", "unescape" ] }, { "filename": "../var/dump/core_00_es6.js", "headerSubs": { "": "2017", "": [ "Load builtins and add polyfills to bring the server's partial", " * JavaScript implementation to include some features of ECMAScript 6." ] }, "contents": [ "Object.is", "Object.assign", "Object.setPrototypeOf", "Array.from", "Array.prototype.find", "Array.prototype.findIndex", "String.prototype.endsWith", "String.prototype.includes", "String.prototype.repeat", "String.prototype.startsWith", "Number.isFinite", "Number.isNaN", "Number.isSafeInteger", "Number.EPSILON", "Number.MAX_SAFE_INTEGER", "Math.sign", "Math.trunc", "WeakMap" ] }, { "filename": "../var/dump/core_00_es7.js", "headerSubs": { "": "2017", "": [ "Load builtins and add polyfills to bring the server's partial", " * JavaScript implementation to include some features of ECMAScript 7." ] }, "contents": [ "Array.prototype.includes" ] }, { "filename": "../var/dump/core_00_esx.js", "headerSubs": { "": "2017", "": [ "Load builtins and add polyfills for Code City-specific extensions to", " * JavaScript." ] }, "contents": [ "Object.getOwnerOf", "Object.setOwnerOf", "Thread", "PermissionError", "Array.prototype.join", "suspend", "setTimeout", "clearTimeout" ] }, { "filename": "core_10_base.js", "headerSubs": { "": "2017", "": "Database core for Code City." }, "prune": ["$.system.onStartup.thread_"], "contents": [ "perms", "setPerms", {"path": "$", "do": "DONE"}, "$.root", {"path": "$.physicals", "do": "DONE"}, {"path": "$.physicals.Maximilian", "do": "DONE"}, {"path": "$.physicals.Neil", "do": "DONE"}, "$.system", "user", {"path": "$.utils", "do": "DONE"}, {"path": "$.utils.validate", "do": "DONE"}, {"path": "$.servers", "do": "DONE"} ] }, { "filename": "core_11_$.utils.js", "headerSubs": { "": "2020", "": "Basic utilities for Code City." }, "contents": [ "$.utils", "$.utils.array", "$.utils.object", "$.utils.string" ] }, { "filename": "core_12_$.utils.code.js", "headerSubs": { "": "2018", "": "Code utilities for Code City." }, "contents": ["$.utils.code"] }, { "filename": "core_13_$.Selector.js", "headerSubs": { "": "2018", "": "Selector implementation for Code City core." }, "pruneRest": ["$.Selector.cache_", "$.Selector.sortByBadness.cache_"], "contents": [ "$.Selector", "$.utils.Binding", {"path": "$.Selector.cache_", "do": "DONE"}, {"path": "$.Selector.sortByBadness.cache_", "do": "DONE"} ] }, { "filename": "core_20_$.utils.html.js", "headerSubs": { "": "2018", "": "HTML utilities for Code City." }, "contents": ["$.utils.html"] }, { "filename": "core_21_$.jssp.js", "headerSubs": { "": "2017", "": "JavaScript Server Pages for Code City." }, "contents": ["$.jssp"] }, { "filename": "core_22_$.connection.js", "headerSubs": { "": "2017", "": "Connection object for Code City." }, "contents": ["$.connection"] }, { "filename": "core_23_$.servers.http.js", "headerSubs": { "": "2017", "": "Webserver for Code City." }, "contents": [ "$.utils.url", "$.servers.http", {"path": "$.servers.http.hosts", "do": "DONE"} ] }, { "filename": "core_24_$.hosts.js", "headerSubs": { "": "2017", "": "Host objects for Code City." }, "contents": [ {"path": "$.hosts", "do": "DONE"}, {"path": "$.hosts.root", "do": "DONE"}, {"path": "$.hosts.root.subdomains", "do": "DONE"}, "$.hosts.root['/']", "$.hosts.root['/mirror']", "$.hosts.root['/robots.txt']", "$.hosts.system", "$.hosts.dummy", "$.hosts.root.subdomains.system", "$.hosts.root.subdomains.connect", "$.hosts.root.subdomains.login", "$.hosts.root.subdomains.mobwrite", "$.hosts.root.subdomains.static", "$.hosts.root.subdomains.system", {"path": "$.servers.http.hosts[0]", "do": "DONE"} ] }, { "filename": "core_25_$.db.tempId.js", "headerSubs": { "": "2018", "": "Temporary ID database for Code City." }, "contents": [ {"path": "$.db", "do": "DONE"}, "$.db.tempId", {"path": "$.db.tempId.tempIds_", "do": "DONE"}, {"path": "$.db.tempId.cleanThread_", "do": "DECL"} ] }, { "filename": "core_25_$.userDatabase.js", "headerSubs": { "": "2017", "": "User database for Code City." }, "contents": [ "$.userDatabase", {"path": "$.userDatabase.byMd5", "do": "DONE"} ] }, { "filename": "core_26_inline_editor.js", "headerSubs": { "": "2017", "": "Inline code editor for Code City." }, "contents": [ {"path": "$.hosts.code", "do": "DONE"}, "$.hosts.code['/inlineEdit']", {"path": "$.hosts.root.subdomains.code", "do": "DONE"} ] }, { "filename": "core_27_editor.js", "headerSubs": { "": "2018", "": "Web-based code explorer/editor for Code City." }, "contents": [ "$.hosts.code" ] }, { "filename": "core_28_$.servers.eval.js", "headerSubs": { "": "2020", "": "Eval server for Code City." }, "contents": [ "$.servers.eval" ] }, { "filename": "core_30_$.utils.command.js", "headerSubs": { "": "2017", "": "Command parser for Code City" }, "contents": ["$.utils.command"] }, { "filename": "core_31_$.utils_world.js", "headerSubs": { "": "2017", "": "World-related utils for Code City." }, "contents": [ "$.utils.commandMenu", "$.utils.replacePhysicalsWithName" ] }, { "filename": "core_32_physical.js", "headerSubs": { "": "2017", "": "Physical object prototype for Code City." }, "contents": [ "$.physical", {"path": "$.physicals", "do": "DONE"}, {"path": "$.physicals['Physical object prototype']", "do": "DONE"}, "$.utils.validate.physicals", "$.garbage" ] }, { "filename": "core_33_world.js", "headerSubs": { "": "2017", "": "Generic physical object types for Code City." }, "contents": [ "$.user", "$.room", "$.thing", "$.container", {"path": "$.physicals['User prototype']", "do": "DONE"}, {"path": "$.physicals['Room prototype']", "do": "DONE"}, {"path": "$.physicals['Thing prototype']", "do": "DONE"}, {"path": "$.physicals['Container prototype']", "do": "DONE"} ] }, { "filename": "core_34_$.servers.login.js", "headerSubs": { "": "2021", "": "Login service backend server for Code City." }, "contents": [ "$.servers.login" ] }, { "filename": "core_34_$.servers.telnet.js", "headerSubs": { "": "2017", "": "Telnet server for Code City." }, "pruneRest": ["$.servers.telnet.connected"], "contents": [ "$.servers.telnet", {"path": "$.servers.telnet.connected", "do": "DONE"} ] }, { "headerSubs": { "": "2017", "": "Initial starting room for Code City." }, "filename": "core_40_$.startRoom.js", "prune": ["$.clock.thread_"], "contents": [ {"path": "$.startRoom", "do": "DONE"}, "$.startRoom{proto}", "$.startRoom{owner}", "$.startRoom.location", {"path": "$.startRoom.contents_", "do": "DONE"}, {"path": "$.startRoom.contents_.forObj", "do": "DONE"}, {"path": "$.startRoom.contents_.forKey", "do": "DONE"}, "$.startRoom.name", "$.startRoom.description", "$.startRoom.roll", "$.clock", {"path": "$.clock.thread_", "do": "DONE"} ] }, { "headerSubs": { "": "2018", "": "Translation room and tutorial demo for Code City." }, "filename": "core_41_deutsche_zimmer.js", "contents": [ "$.physicals['Das deutsche Zimmer']", "$.tutorial", {"path": "$.tutorial.location", "do": "DECL"}, {"path": "$.tutorial.user", "do": "DECL"}, {"path": "$.tutorial.thread", "do": "DECL"}, {"path": "$.tutorial.step", "do": "DECL"}, {"path": "$.tutorial.room", "do": "DECL"}, {"path": "$.tutorial.origFunc", "do": "DECL"}, {"path": "$.physicals.tutorial", "do": "DONE"} ] }, { "filename": "core_42_plant.js", "headerSubs": { "": "2018", "": "Plant demo for Code City." }, "contents": [ "$.seed", {"path": "$.seed.location", "do": "DECL"}, {"path": "$.physicals['Generic Seed']", "do": "DONE"}, "$.pot", {"path": "$.pot.location", "do": "DECL"}, {"path": "$.pot.seed", "do": "DECL"}, {"path": "$.pot.stage", "do": "DECL"}, "$.pot.stages", {"path": "$.physicals['flower pot']", "do": "DONE"}, "$.thrower", {"path": "$.thrower.location", "do": "DECL"}, {"path": "$.thrower.savedSvg", "do": "DECL"}, {"path": "$.physicals['a flame thrower']", "do": "DONE"} ] }, { "filename": "core_43_genetics_lab.js", "headerSubs": { "": "2020", "": "Genetics lab demo for Code City." }, "contents": [ "$.physicals['Genetics Lab']", {"path": "$.physicals['Genetics Lab'].contents_", "do": "DONE"}, {"path": "$.physicals['Genetics Lab'].contents_.forObj", "do": "DONE"}, {"path": "$.physicals['Genetics Lab'].contents_.forKey", "do": "DONE"}, "$.cage", {"path": "$.cage.location", "do": "DECL"}, {"path": "$.physicals.cage", "do": "DONE"}, "$.physicals['Genetic Mouse Prototype']", "$.hosts.genetics", "$.hosts.root.subdomains.genetics" ] }, { "filename": "core_44_$.assistant.js", "headerSubs": { "": "2020", "": "Voice-activated assistant demo for Code City." }, "contents": [ "$.assistant", {"path": "$.assistant.location", "do": "DECL"}, {"path": "$.assistant.lastActivated", "do": "DECL"}, {"path": "$.physicals.assistant", "do": "DONE"} ] }, { "filename": "core_45_Challenge_Room.js", "headerSubs": { "": "2020", "": "Challenge room demo for Code City." }, "contents": [ "$.physicals['Challenge room']", "$.physicals['light switch']", "$.physicals.chest", "$.physicals.safe", "$.physicals.food", "$.physicals.girl" ] }, { "filename": "core_46_$.secuityCourse.js", "headerSubs": { "": "2021", "": "Security course demo for Code City." }, "contents": [ "$.securityCourse", {"path": "$.securityCourse.storeHosts", "do": "DONE"}, {"path": "$.hosts.root['/securitycourse']", "do": "DONE"} ] }, { "options": {"skipBindings": []} }, { "filename": "../database/db_00_core_lastModified.js", "headerSubs": { "": "2020", "": "Edit history info for Code City core." }, "contents": [ "Object", "Function", "Array", "String", "Boolean", "Number", "Date", "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "Math", "JSON", "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent", "escape", "isFinite", "isNaN", "parseFloat", "parseInt", "unescape", "Object.is", "Object.assign", "Object.setPrototypeOf", "Array.from", "Array.prototype.find", "Array.prototype.findIndex", "String.prototype.endsWith", "String.prototype.includes", "String.prototype.repeat", "String.prototype.startsWith", "Number.isFinite", "Number.isNaN", "Number.isSafeInteger", "Number.EPSILON", "Number.MAX_SAFE_INTEGER", "Math.sign", "Math.trunc", "WeakMap", "Array.prototype.includes", "Object.getOwnerOf", "Object.setOwnerOf", "Thread", "PermissionError", "Array.prototype.join", "suspend", "setTimeout", "clearTimeout", "perms", "setPerms", "$.root", "$.system", "user", "$.utils", "$.utils.array", "$.utils.object", "$.utils.string", "$.utils.code", "$.Selector", "$.utils.Binding", "$.utils.html", "$.jssp", "$.connection", "$.utils.url", "$.servers.http", "$.hosts.root['/']", "$.hosts.root['/mirror']", "$.hosts.root['/robots.txt']", "$.hosts.system", "$.hosts.dummy", "$.hosts.root.subdomains.connect", "$.hosts.root.subdomains.login", "$.hosts.root.subdomains.mobwrite", "$.hosts.root.subdomains.static", "$.hosts.root.subdomains.system", "$.db.tempId", "$.userDatabase", "$.hosts.code['/inlineEdit']", "$.hosts.code", "$.servers.eval", "$.utils.command", "$.utils.commandMenu", "$.utils.replacePhysicalsWithName", "$.physical", "$.utils.validate.physicals", "$.garbage", "$.user", "$.room", "$.thing", "$.container", "$.servers.login", "$.servers.telnet", "$.startRoom{proto}", "$.startRoom{owner}", "$.startRoom.location", "$.startRoom.name", "$.startRoom.description", "$.startRoom.roll", "$.clock", "$.physicals['Das deutsche Zimmer']", "$.tutorial", "$.seed", "$.pot", "$.pot.stages", "$.thrower", "$.physicals['Genetics Lab']", "$.cage", "$.physicals['Genetic Mouse Prototype']", "$.hosts.genetics", "$.hosts.root.subdomains.genetics", "$.assistant", "$.physicals['Challenge room']", "$.physicals['light switch']", "$.physicals.chest", "$.physicals.safe", "$.physicals.food", "$.physicals.girl", "$.securityCourse", "$.hosts.root['/securitycourse']" ] }, { "filename": "../database/db_01_world.js", "headerSubs": { "": "2017", "": "Main database for google.codecity.world." }, "contents": [ "$.servers.http.Host.prototype.access", "$.hosts.root.access", "$.hosts.system.access", "$.db.tempId.tempIds_", "$" ] }, { "options": {"treeOnly": false} }, { "filename": "../database/db_99_leftovers.js", "header": "", "rest": true } ] ================================================ FILE: database/README ================================================ On startup, if no .city database file exists, the server will read and execute all .js files in this directory in asciibetical order. The following naming convention has been established to keep things organised: core*.js - The Code City core. db*.js - A dumped databse, if available, less core. test*.js - Any tests to be run against the databse. ================================================ FILE: database/codecity.cfg ================================================ { "databaseDirectory": "./", "checkpointInterval": 60, "checkpointAtShutdown": true, "checkpointMinFiles": 10, "checkpointMaxDirectorySize": 2048 } ================================================ FILE: docs/setup.md ================================================ # Setting up a Code City Instance This document describes how to recreate a Code City server from bare metal. For reference, the starting point is a Google Cloud Platform account in good standing. ## Google Compute Engine Setup We recommend running your Code City server on a [Google Compute Engine](https://cloud.google.com/compute) (GCE) virtual machine[[?]]( https://en.wikipedia.org/wiki/Virtual_machine) (VM)—it’s reliable, minimal hassle, and, thanks to [Google Cloud Platform’s “Always Free” tier](https://cloud.google.com/free), can be (very nearly) free! ### Create a GCE instance This will create a dedicated GCE instance (VM) on which to run Code City. You can skip this step if you intend to run your instance on your own machine or another cloud provider’s hardware. Before you begin: the GCE instance (VM) you create will run using the permissions of a service account[[?]]( https://cloud.google.com/iam/docs/service-accounts). There is a “Compute Engine default service account” which will work fine but has quite broad permissions. You may wish to create a service account with more limited permissions, to reduce the amount of damage an attacker can do if they compromise your Code City instance and gain control of the VM on which it runs. This is especially so if your GCP project contains other resources (user data, etc.) which you wish to protect. See [Appendix A: Creating a Service Account]( #appendix-a-creating-a-service-account) for instructions. 1. Go to the [Google Compute Engine console](https://console.cloud.google.com/compute/instances). 0. Under VM Instances, click the create instance button ![blue icon with white plus](instance-new.svg). Enter details as follows: * Name: choose a name for the instance. (This can be any name, but we recommend you use a name matching your intended domain name—e.g., `google.codecity.world` runs on an instance named `google`.) * Region: choose a region near where you expect your users to be. Note that [instance pricing varies by zone](https://cloud.google.com/compute/vm-instance-pricing). * Zone: choose any. * Machine type: choose an appropriate size. * [GCP’s “Always Free” tier][always-free] offers one free `f1-micro` instance in any of `us-west1`, `us-central1` or `us-east1`. This size will be sufficient for many smaller organisations/groups. * Because of the architecture of the Code City server, there is unlikely to be any benefit to having more than two vCPUs (and one is generally sufficient). * Container: no. * Boot disk: under “Public images”, choose: * Operating system: Debian * Version: choose the most recent version—“Debian GNU/Linux 10 (buster)” as of this writing. * Boot disk type: Standard persistent disk. * Size: the default 10GB is likely to be sufficient for most cases, but the “Always Free” program offers up to 30GB (total, not per-instance) of persistent disk free of charge. * Identity and API access: * Service account: use the default “Compute Engine default service account” or select the one you created by following the instructions in [appendix A]( #appendix-a-creating-a-service-account). * Access scopes: Allow default access. * Firewall: Allow both HTTP and HTTPS traffic. * Management: * Recommended: tick “Enable deletion protection” to make it harder to inadvertently delete your Code City instance. * Security: * Recommended: tick “Turn on Secure Boot”. * SSH Keys: you can add your ssh public key(s) here if you wish; doing so will cause them to be automatically added to the corresponding `~userid/.ssh/authorized_keys` file, but note: * Keys added here apply only to this GCE instance. If you expect your project to have multiple instances you may prefer to add your SSH keys on [the Compute Engine metadata page]( https://pantheon.corp.google.com/compute/metadata/sshKeys) instead: keys added there will have access to all the project's GCE instances by default (i.e., unless you tick "Block project-wide SSH keys" on a particular instance). * Even if you don’t add any SSH keys now you will in any case be able to SSH to the machine from [GCE instances page]( https://console.cloud.google.com/compute/instances). * Disks: * Recommended: **un**tick “Delete boot disk when instance deleted” so that if you _do_ delete your instance you can recreate it easily and without losing user data. * Networking: * Under Network interfaces, click the pencil icon next to the default interface. * External IP: ignore this section for now. * Public DNS PTR Record: optionally click “Enable” and enter the [domain name](#set-up-an-ip-address-and-domain-name) you intend to use for your instance, e.g. example.codecity.world. * Click “Done” to end editing the network interface. 0. Double-check the monthly cost estimate (at the top of the page) to ensure it is reasonable. 0. Click “create” and you will be taken back to the VM instances dashboard. After a few minutes, you should see your new instance is ready, and has internal and external IP addresses. 0. Under “Connect”, click on “SSH” for your instance. 0. Verify instance is running Debian 10: ``` $ uname -a Linux instancename 4.19.0-9-cloud-amd64 #1 SMP Debian 4.19.118-2+deb10u1 (2020-06-07) x86_64 GNU/Linux ``` [always-free]: https://cloud.google.com/free/docs/gcp-free-tier#always-free-usage-limits [service-account]: https://cloud.google.com/iam/docs/creating-managing-service-accounts #### Reserve a Static IP Address For users to be able to access your instance from the Internet, it will need a static IP address[[?]]( https://en.wikipedia.org/wiki/IP_address) (like 192.0.2.1) so that traffic can be routed to it. 1. Go to the [Networking / External IP addresses console](https://console.cloud.google.com/networking/addresses). 0. Click “+ Reserve Static Address”. Enter details as follows: * Name: can be any value, but we recommend you use the same name as for your instance. This is just used to identify the address reservation. * Description: enter any text you like—e.g.: “Static IP address for example.codecity.world.” * Network Service Tier: choose either. See [description of options](https://cloud.google.com/network-tiers/) and [pricing information](https://cloud.google.com/network-tiers/pricing). * IP vesion: IPv4. * Type: Regional. * Region: choose the same region as your instance was created in. * Attached to: choose your instance from the drop-down. 0. Click “Reserve”. 0. Make a note of the external address (like 192.0.2.1) which you have just reserved for your instance. ### Give Your Instance a Domain Name The Domain Name System[[?]]( https://en.wikipedia.org/wiki/Domain_Name_System) is a distributed global database that maps domain names (like `example.org`) to IP addresses (like 192.0.2.1). In order for users to be able to access your instance without having to know the numeric static IP address you reserved in the previous section, you must create a human-readable domain mame[[?]]( https://en.wikipedia.org/wiki/Domain_name) for it. The details of this process are outside of the scope of this document, but we have the following observations and recommendations: * Setting up DNS involves two distinct entities: a domain name registrar[[?]]( https://en.wikipedia.org/wiki/Domain_name_registrar), from whom you can purchase a domain name (like `example.org`), and a DNS provider, who runs the name servers[[?]]( https://en.wikipedia.org/wiki/Name_server) that resolve individual DNS entries (like `www.example.com`) to specific numeric IP addresses like the one created in the previous section. In many cases both these services will be provided by the same company, but many organisations will typically run their own DNS servers, or outsource it to a [managed DNS provider]( https://en.wikipedia.org/wiki/List_of_managed_DNS_providers). * If you are using your own domain name (e.g., codecity.example.org) this will be done through your DNS provider’s configuration console or via your internal organisational DNS service configuration. * Alternatively we may in some cases be able to offer you the use of a Code City subdomain (e.g., example.codecity.world), in which case we will take care of this step for you. Contact us for details. * Because of the [same origin policy], if you’d like to allow individual (not fully trusted) users of your instance to be able to create their own web pages / servers, we *strongly* recommend that you use a wildcard DNS record[[?]]( https://en.wikipedia.org/wiki/Wildcard_DNS_record), so that each user can serve their content on an isolated subdomain (like username.example.codecity.world). * You will need to create (or arrange to have created) two separate DNS "A" records for your domain name: * The main entry, e.g. `example.codecity.world`, type `A`, resolving to your instance's IP address, and * The wildcard entry, e.g. `*.example.codecity.world`, also type `A`, resolving to the same IP address. * To facilitate obtaining the necessary wildcard certificate[[?]]( https://en.wikipedia.org/wiki/Wildcard_certificate), we recommend you use a [DNS provider who easily integrates with Let’s Encrypt DNS validation][dns-providers], such as [Google Cloud DNS](https://cloud.google.com/dns/), if possible. [same origin policy]: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy [dns-providers]: https://community.letsencrypt.org/t/dns-providers-who-easily-integrate-with-lets-encrypt-dns-validation/86438 ### Recommended: schedule regular, automatic backups of your instance’s disk It’s always best to back up! Even though the Code City server regularly checkpoints its database to the instance’s persistent disk, setting up regular snapshotting of that disk will give you a separate backup of the whole system in case of disaster. Snapshots are [not free], but [are cheap]. A few dollars a month buys a lot of peace of mind! [not free]: https://cloud.google.com/compute/disks-image-pricing#persistentdisk [are cheap]: https://cloud.google.com/compute/disks-image-pricing#persistent_disk_snapshots_storage_charges First, create a snapshot schedule: 1. Go to the [GCE Snapshots page]( https://console.cloud.google.com/compute/snapshots) and click on the “Snapshot Schedules” tab. 0. Click on Create Snapshot Schedule. Enter details as follows: * Name: choose a name for the schedule, e.g. `daily-14`. * Description: anything, e.g. “Daily snapshots, kept for 14 days”. * Snapshot location: Regional. * Region: choose the same region as your instance. * Schedule frequency: hourly, daily or weekly as you prefer; for this example: daily. (N.B.: more frequent snapshots will result in more data to be stored and thus higher costs.) * Start time: any. Snapshotting will not affect the running instance, so choose whatever time of day you wish. * Auto-delete snapshots after: choose a suitable period of time; for this example: 14 days. * Deletion rule: as you wish: “keep snapshots” better protects against data loss in the event that your instance is *inadvertently* deleted; “delete snapshots after _N_ days” better protects against continuing to be charged fees after you *deliberately* delete your instance. * Enable VSS: no. (Not applicable to non-Windows instances.) * Snapshot labels: not needed. 0. Click “Create” to create the schedule. Now apply the schedule to your instance’s persistent disk: 4. Go to the [GCE Disks page]( https://console.cloud.google.com/compute/disks). 0. Click on the name of the persistent disk for your instance. (By default it will have the same name you gave to your instance.) 0. Click on “Edit” at the top of the screen. 0. Under Snapshot schedule, select the schedule you created in steps 1–3. 0. Click Save. ## Set Up Machine and Install Code City These instructions assume you are using a GCE instance running Debian GNU/Linux 10 "buster", but feel free to adapt to your particular set-up. 1. Log into your instance. (See instructions in first section if using GCE.) 0. If your machine has less than 2GB of memory (check with `free -h`; the very first number shown is total RAM), you will need to create a swap file (this is mandatory on `f1-micro` instances): ``` sudo -i fallocate -l 2G /swapfile chmod 600 /swapfile mkswap /swapfile swapon /swapfile swapon -s sh -c 'echo "/swapfile none swap sw 0 0" >> /etc/fstab' exit ``` 0. Check for and install system updates, then install [nginx](https://en.wikipedia.org/wiki/Nginx) and [git](https://git-scm.com/): ``` sudo apt-get update sudo apt-get upgrade –y sudo apt-get install -y nginx git ``` 0. Optionally install a text editor of your choice. Debian comes with [`vim`](https://www.vim.org/) and [`nano`](https://www.nano-editor.org/) preinstalled; Emacs users might feel more at home with the lightweight editors [`mg`](https://github.com/hboetes/mg), [`jove`](https://github.com/jonmacs/jove) or [`zile`](https://www.gnu.org/software/zile/), or opt for `emacs-nox` which is GNU Emacs without X Windows bindings. ``` sudo apt-get install mg ``` 0. Install [node.js](https://nodejs.org/). Code City depends on version 12, which is more recent than the version included in Debian 10, so we will obtain it via [NodeSource]( https://github.com/nodesource/distributions): ``` sudo -i curl -sL https://deb.nodesource.com/setup_12.x | bash - apt-get install -y nodejs exit ``` 0. Verify the correct version of node is installed: ``` $ node –-version v12.18.4 ``` (Actual version may be later than 12.18.) ### Get TLS Certificates In order to allow incoming HTTPS connections, you will need an TLS[[?]](https://en.wikipedia.org/wiki/Transport_Layer_Security) server certificate[[?]]( https://en.wikipedia.org/wiki/Public_key_certificate#TLS/SSL_server_certificate ). There are two types: * An ordinary certificate covers one or more specific domain names, like `www.example.org`. * A wildcard certificate includes one or more wildcard domains, like `*.example.org`. You will need to get a TLS certificate covering the [set of DNS entries you [created earlier](#set-up-an-ip-address-and-domain-name). If (as recommended) you created a wildcard DNS entry, you will also need a corresponding wildcard TLS certificate. There are various ways to get a TLS certificate, but a free and easy way is to use [Certbot](https://certbot.eff.org/) to get one from [Let’s Encrypt](https://letsencrypt.org/). That’s what we’ll do here. #### Getting a wildcard certificate To use Certbot to get a wildcard certificate, you will need to use the [`dns-01` challenge]( https://letsencrypt.org/docs/challenge-types/#dns-01-challenge), which requires being able to create DNS TXT records[[?]]( https://en.wikipedia.org/wiki/TXT_record) for your domain name. Here’s an example of how to do this if using Google Cloud DNS; see [full instructions on the certbot website]( https://certbot.eff.org/lets-encrypt/debianbuster-nginx) if you use another provider. 1. Install certbot and the required plug-ins: ``` sudo apt-get install -y certbot python3-certbot-dns-google ``` 0. Obtain credentials from your DNS provider, to allow Certbot to create TXT records, proving to Let’s Encrypt that you control your domain. It [should be possible to skip this step]( https://certbot-dns-google.readthedocs.io/en/stable/#credentials) when using Google Cloud DNS and running Certbot on GCE instance, but alas [due to a bug]( https://github.com/certbot/certbot/issues/7933) this doesn’t yet work in Debian 10. 1. Go to the [Service Accounts]( https://console.cloud.google.com/iam-admin/serviceaccounts) tab of the IAM & Admin section of the GCP console. 0. Find the service account under which your GCE instance runs; unless you elected otherwise above, this will be the one named “Compute Engine default service account”. Click on the email address for the key to open the details pane. 0. Click on the keys tab. 0. From the Add Key pop-up menu, select “Create new key”. * Choose Key Type: JSON. * Click “Create”. 0. Your browser will download a file with a name of the form scp projectID–XXXXXXXXXXXX.json. Now, transfer this file to your GCE instance using [`scp`](https://en.wikipedia.org/wiki/Secure_copy) **on your local machine**, e.g. scp projectID–XXXXXXXXXXXX.json example.codecity.world:service-account.json, or by pasting it into a terminal window, as follows: * Open the `.json` file you downloaded in step 2.iv. in a text editor, select the whole contents and copy it to the clipboard. * **On your instance**, enter the command `cat - > service-account.json ` * Paste the contents of the `.json` into the SSH window. * Type `^D` to indicate end of file. 0. This credentials file will be needed when initially obtaining the TLS certificate as well as every few months when [Certbot will automatically renew it]( https://certbot.eff.org/docs/using.html#automated-renewals), so move it to a safe place and protect it from tampering: ``` sudo mv service-account.json /etc/service-account.json sudo chown root:root /etc/service-account.json sudo chmod 600 /etc/service-account.json ``` 0. Request a certificate for both the base domain name for your instance and the corresponding wildcard entry: ``` sudo certbot certonly --dns-google \ --dns-google-credentials /etc/service-account.json \ --post-hook 'systemctl reload nginx' \ -d 'example.codecity.world,*.example.codecity.world' ``` If you have more than one DNS entry pointing at your instance, just add further comma-separated entries to the list after the `-d` directive. (N.B.: No spaces between entries in this list!) * Enter your email address when prompted. * Agree the terms of service. * Optionally agree to share your email address with the EFF. #### Getting a non-wildcard certificate This process is a little simpler and does not require the ability to modify DNS TXT records. 1. Install certbot (only): ``` sudo apt-get install -y certbot ``` 0. Request a certificate for the base domain name for your instance (only): ``` sudo certbot certonly --webroot --webroot-path /var/www/html \ --post-hook 'systemctl reload nginx' \ -d example.codecity.world ``` * Enter your email address at the prompt * Agree the terms of service. * Optionally agree to share your email address with the EFF. ### Install Code City 1. Create an account for Code City to run under. This is to isolate it from any other users/services on the machine, and contain the damage in the event that the server sandbox be compromised. We’ll call the account `codecity` here, but any username is fine: ``` sudo useradd -rms /bin/bash codecity ``` 0. Become the code city account: ``` sudo -iu codecity ``` 0. Clone the [Code City repo](https://github.com/google/CodeCity). (If you are a project collaborator, see below for [instructions on how to use SSH instad of HTTPS](#git-code-city-by-ssh-instead-of-https).) ``` git clone https://github.com/google/CodeCity.git ``` 0. Install required NPMs: ``` (cd CodeCity/server && npm ci --only=prod) (cd CodeCity/login && npm ci --only=prod) ``` 0. Exit from the `codecity` account. We’re done with it for now, and we need to be able to sudo, which that account (deliberately) does not have permission to do. ``` exit ``` ### Configure NGINX On Debian, per-host `nginx` configuration files are stored in `/etc/nginx/sites-available` and enabled by symlinking them into `/etc/nginx-sites-enabled`. There is a `default` config supplied by the `nginx` package, which should be disabled (unless you have already modified it to serve other virutal hosts). 1. Install the NGINX configuration file. If you have a wildcard DNS record and corresponding wildcard TLS certificate, use the “subdomain” configuration: ``` sudo cp ~codecity/CodeCity/etc/cc-subdomain.conf \ /etc/nginx/sites-available/codecity ``` Otherwise, use the “onedomain” configuration: ``` sudo cp ~codecity/CodeCity/etc/cc-onedomain.conf \ /etc/nginx/sites-available/codecity ``` 0. Edit /etc/nginx/sites-enabled to replace INSTANCENAME with the name(s) of your instance. (See comments for details. You may use another editor instead of nano if you wish!) ``` sudo nano /etc/nginx/sites-available/codecity ``` 0. Enable the new configuration and reload (or restart) NGINX: ``` sudo rm /etc/nginx/sites-enabled/default sudo ln -s /etc/nginx/sites-available/codecity \ /etc/nginx/sites-enabled/codecity sudo systemctl reload-or-restart nginx ``` ### Create an API Key for OAuth The usual set-up for public Code City instances is to use [OAuth 2.0](https://oauth.net/2/) via Google’s OAuth service for logins. This step will set up the necessary credentials to allow users to log in to your instance using their Google (Gmail) account. You can skip this step if you intend to use a different login mechanism. This must be done after installing nginx and CodeCity and obtaining a TLS certificate because it depends on `logo-auth.png` being served by nginx. 1. Optionally replace `~codecity/CodeCity/static/logo-auth.png` with a logo representing your instance or organisation. It should be a 120x120px PNG image. 0. Make sure you can access your desired logo using your web browser. If you are using a wildcard DNS configuration, it should be accessible via a URL like static.example.codecity.world/logo-auth.png; for a single-domain configuration it will instead be example.codecity.world/static/logo-auth.png. Make a note of this URL. 0. Go to [APIs & Services > OAuth consent screen]( https://console.cloud.google.com/apis/credentials/consent). Enter details as follows: * Email address: select a suitable contact email address or Google Group for users of your service. * Product name: this should include the name of your organisation; it may optionally contain the name “Code City”; it should not include “Google” or the like. N.B.: the same details are used for all services offered via a given Google Cloud Platform account. * Homepage URL: this could be your organisation’s homepage or the URL of the front page for your instance (perhaps example.codecity.world or codecity.yourdomain.tld) * Product logo URL: Should point at the URL for your your logo, as determined in step 2 above. * Privacy policy URL: Provide a link to your privacy policy. * Terms of service URL: may be left blank. 0. Go to the [APIs & Services > Credentials console](https://console.cloud.google.com/apis/credentials). 0. Click “Create credentials”; choose OAuth client ID. Enter details as follows: * Application type: Web application * Name: a suitable full name for your instance, (e.g. “Code City for Springfield Highschool”). * Authorized JavaScript origins: may be left blank. * Authorized redirect URIs: for wildcard DNS configurations this will be of the form `https://login.example.codecity.world/`; for single-domain configurations it will instead be `https://example.codecity.world/login/`. 0. Click Save. 0. Now click on the newly-created client ID. Make a note of the Client ID (it will be a long string like “00000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com”) and the Client Secret (a shorter but similarly opaque jumble of characters). You will need these later. See also the [complete GCP OAuth 2.0 documentation]( https://support.google.com/cloud/answer/6158849) for more information. ### Configure Code City 1. Become the code city account: ``` sudo -iu codecity ``` 0. Create a config file for loginServer: * Run loginServer once to create an empty config file: ``` (cd ~/CodeCity/login && ./loginServer) ``` Open `~/CodeCity/login/loginServer.cfg` in the text editor of your choice. * Set `connectUrl` to the URL for the connect server. If using a wildcard DNS entry for your instance, it will be the `connect.` subdomain of your instance’s name; otherwise it will be the `/connect` path on your instance. For example: * With wildcard DNS: `https://connect.example.codecity.world/` * Without wildcard DNS:`https://example.codecity.world/connect/` * Set `staticUrl` to the URL nginx will serve static content on. This works similarly to the previous entry, e.g.: * With wildcard DNS: `https://static.example.codecity.world/` * Without wildcard DNS:`https://example.codecity.world/static/` * Set `clientID` and `clientSecret` to the values obtained earlier from [Google’s API Console]( https://console.developers.google.com/apis). * Set `cookieDomain` to your instance’s base domain name, e.g.: `example.codecity.world`. * Set `password` to a secret, random string. If you don’t have a convenient way to generate one locally, you can copy a [random string from random.org]. * Optionally, set `emailRegexp` to a [JavaScript regexp] matching email addresses which should be permitted to log in to your instance—e.g., `^.*@myorganisation\\.org$`. 0. Create and edit a config file for connectServer: * Run connectServer once to create an empty config file: ``` (cd ~/CodeCity/connect && ./connectServer) ``` Open `~/CodeCity/connect/connectServer.cfg` in the text editor of your choice. * Set `loginUrl` to the URL for the login server, e.g.: * With wildcard DNS: `https://login.example.codecity.world/` * Without wildcard DNS:`https://example.codecity.world/login/` * Set `staticUrl` and `password` to the _same_ values used in `loginServer.cfg`. 0. Modify the configuration for the in-core HTTP server: * Open the file `~/CodeCity/core/core_99_startup.js` in the text editor of your choice. Find the optional configuration section near the top of the file. * Set `$.hosts.root.hostname` to your instance’s domain name—e.g., $.hosts.root.hostname = 'example.codecity.world'; * Set `$.hosts.root.pathToSubdomain = false;` if you are using a wildcard DNS entry for your instance; otherwise set it to `true`. * If you have more than one DNS entry for your instance, set `$.hosts.root.hostRegExp` according to the instructions provided. 0. Save the file, exit your editor and exit from the `codecity` account. ``` exit ``` [JavaScript regexp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions [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 ### Configure Systemd and Start Code City Servers 1. Install the systemd config files: ``` sudo cp ~codecity/CodeCity/etc/*.service /etc/systemd/system ``` 0. Check the contents of `/etc/systemd/system/codecity.service`, …`codecity-login.service` and …`codecity-connect.service`; verify paths, usernames etc. all match the values created in previous steps. 0. Enable Code City services with systemd: ``` sudo systemctl enable --now codecity ``` 0. Verify you can connect to your new Code City instance by pointing your web browser its domain name—e.g., `https://example.codecity.world`. Congratulations, you're done! ## Appendix A: Creating a Service Account To protect any other Google Cloud Platform services you run against the consequences of your Code City instance being compromised, you can have the GCE VM it runs on use only the limited permissions of a custom service account, rather than the extensive permissions held by the Compute Engine default service account. To do this there are three steps: 1. Creating one or more roles for the service account. 0. Creating a service account 0. Applying the service account to the GCE instance. ### Create Role(s) You should create one role for running CodeCity instances on GCE, and optionally create a second role if you intend to have your GCE instance [obtain wildcard TLS certificates using certbot via the ACME HTTP-01 challenge](#getting-a-wildcard-certificate). 1. Go to the [Roles tab of IAM & Admin]( https://console.cloud.google.com/iam-admin/roles). 0. Create a role for running a Code City instance by clicking “+ Create Role” then enter details as follows: * Title: “CodeCity Instance”. * Description: “Base role for all CodeCity instances. Created on: …”. * ID: `instance`. * Add the following permissions by clicking “+ Add Permissions” button, typing the name of the permission into the “Filter table” field (*not* the “Filter permissions by role” field), selecting required permission, and clicking Add: * `compute.globalOperations.get` * `compute.zoneOperations.get` * `logging.logEntries.create` * Click “Create”. 0. Optionally create a second role for obtaining wildcard certs by again clicking “+ Create Role” and entering: * Title: “CodeCity Cert-via-DNS” * Description: “Add-on permission to allow an instance to update its own wildcard letsencrypt SSL cert via an ACME dns-01 challenge. Created on: …”. * ID: `dnscert`. * Add the following permisions: * `dns.changes.create` * `dns.changes.get` * `dns.managedZones.list` * `dns.resourceRecordSets.create` * `dns.resourceRecordSets.delete` * `dns.resourceRecordSets.list` * `dns.resourceRecordSets.update` * Click “Create”. ### Create a Service Account Now you can create a service account for your instance. 1. Go to the [Service Accounts tab of IAM & Admin]( https://console.cloud.google.com/iam-admin/serviceaccounts). 0. Click “+ Create Servce Account” and enter details as follows: * Service account name: choose and appropriate name such as “CodeCity instance” or “instance-myInstanceName”. * Service account ID: modify suggested ID if desired. * Service account description: “Service account for the example.codecity.world instance” or similar. 0. Click “Create”. * Where it says “Select a role”, select “CodeCity Instance”. * If you intend to use certbot to obtain a wildcare DNS cert, click “+ Add Another Role” and select “CodeCity Cert-via-DNS”. 0. Click “Continue”. 0. Click “Done. ### Use the Service Account to run your GCE Instance If you have not yet done so, simply [follow the instructions to create a GCE instance for Code City](#create-a-gce-instance) and, when you get to the “Identity and API access” section of the creation wizard, select the service account you created previously. Otherwise, if you have already created your GCE instance, configure it to use the newly-create service account as follows: 1. Go to the [VM instances tab]( https://console.cloud.google.com/compute/instances). 0. Select the VM instance you created previously. 0. Click the stop button at the top of the page to stop it, if it is running. 0. Click the name of your instance to view its “VM instnace details” page. 0. Click “Edit”. 0. Scroll down to “Service account” and select the service account you created previously. ## Appendix B: Remote Debugging If you need to debug the server because it has stopped responding to network activity, here’s how to do that: 1. SSH in to the GCE instance and enable the inspector on the running server: * $ sudo kill -s SIGUSR1 `pidof codecity` 0. Look in /var/log/daemon.log for a message like: ``` Feb 26 01:22:49 google codecity[19464]: Debugger listening on ws://127.0.0.1:9229/8df977b7-024d-464d-84c2-44321dd5b398 Feb 26 01:22:49 google codecity[19464]: For help, see: https://nodejs.org/en/docs/inspector ``` Note the port number (in this case 9229). 0. SSH in to the GCE instance again, enabling port forwarding: ``` ssh -L 9229:localhost:9229 google.codecity.world ``` * The initial 9229 can be replaced with a local port number of your choice. * The `:localhost:` directive ensures that only processes running on your local machine can make use of the port forward. 0. Open the inspector in Chrome by going to [`chrome://inspect`](chrome://inspect). (Based on [node.js debugging documentation]( https://nodejs.org/en/docs/guides/debugging-getting-started/) and [a related blog post]( https://hackernoon.com/debugging-node-without-restarting-processes-bd5d5c98f200).) ## Appendix C: Additional Instructions for Code City Collaborators ### GIT Code City by SSH instead of HTTPS During early development, the Code City repository was private so it was necessary to do the `git clone` by SSH instead of HTTPS. We continue to do this on our production instance to allow commits to the `prod` branch to be made from there if necessary. To avoid putting SSH private keys on the instance, we use SSH agent forwarding. This would mostly be automatic except that we also need to be able to use our personal credentials as the user `codecity`. The solution is adapted [from Server Fault]( https://serverfault.com/questions/107187). #### Preparation (do once) 1. Add your SSH public key (ideally, one from a hardware token or the like) to [your GitHub account](https://github.com/settings/keys). 0. Verify that you can ssh to GitHub from your local workstation: ``` ssh -T git@github.com ``` Output should look like “Hi username! You've successfully authenticated, but GitHub does not provide shell access.” 0. Edit `~/.ssh/config` to add the following directive, if not already present: ``` ForwardAgent yes ``` This will enable agent forwarding by default. #### When setting up a CodeCity GCE instance These instructions replace step 3 of [Install & Configure Code City](#install--configure-code-city). 4. Ensure that your SSH public key can be used to log in to the instance. This can be done in two ways: * Preferred: add it to [the Compute Engine metadata page]( https://pantheon.corp.google.com/compute/metadata/sshKeys). * Alternatively: add it to the instance at creation or by editing the instance on [the GCE instances page]( https://console.cloud.google.com/compute/instances). * Alternatively: log into the instance initially using the browser-based SSH available via the GCE console. Use the text editor of your choice to append your SSH public key to `~/.ssh/authorized_keys`. 0. Ensure you can ssh to your instance from the command line of your local machine. Use `-A` to enable agent forwarding (`ssh -A example.codecity.world`) or add `ForwardAgent yes` to your `~/.ssh/config` file. 0. From your instance, verify that agent forwarding is working: ``` ssh -T git@github.com ``` (Expected output similar to step 2 above above.) 0. Install the acl package: ``` sudo apt-get install -y acl ``` 0. On your instance, after creating the `codecity` user, add the following to your `.bashrc` or `.bash_login`: ``` setfacl -m codecity:x $(dirname "$SSH_AUTH_SOCK") setfacl -m codecity:rw "$SSH_AUTH_SOCK" ``` 0. Modify the machine’s sudo config to tell sudo not to wipe `SSH_AUTH_SOCK` from the environment: ``` sudo visudo -f /etc/sudoers.d/ssh-agent-forwarding ``` * Add the line ``` Defaults env_keep+=SSH_AUTH_SOCK ``` then save and exit. 0. When becoming the codecity user, be sure to use “`sudo -iu codecity`” instead of “`sudo su - cc`”—the latter will clear the needed `SSH_AUTH_SOCK` environment variable. 0. Install Code City using the SSH repository path: ``` git clone git@github.com:google/CodeCity.git ``` #### Getting SSL Certificates Google-internal GCE instances are by default firewalled to prevent inbound access from the Internet; this causes Certbot’s ACME checks to fail. The preferred solution is to use the DNS-01 challenge, even if no wildcard cert is required. ================================================ FILE: etc/apache.conf ================================================ # Template for Apache configuration. # HTTP should redirect to HTTPS. RewriteEngine On RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L] # '.academy' should redirect to '.world'. ServerName XXXXX.codecity.academy RewriteEngine On RewriteRule ^/?(.*) https://XXXXX.codecity.world/$1 [R,L] SSLEngine on Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/XXXXX.codecity.world/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/XXXXX.codecity.world/privkey.pem # '.games' should redirect to '.world'. ServerName XXXXX.codecity.games RewriteEngine On RewriteRule ^/?(.*) https://XXXXX.codecity.world/$1 [R,L] SSLEngine on Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/XXXXX.codecity.world/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/XXXXX.codecity.world/privkey.pem ServerName XXXXX.codecity.world Alias /static /home/cc/CodeCity/static Options Indexes Includes FollowSymLinks AllowOverride All Require all granted ProxyPass /login http://localhost:7781/login ProxyPassReverse /login http://localhost:7781/login ProxyPass /connect http://localhost:7782/connect ProxyPassReverse /connect http://localhost:7782/connect ProxyPass /mobwrite http://localhost:7783/mobwrite ProxyPassReverse /mobwrite http://localhost:7783/mobwrite # Must be last, or else it will grab all requests. ProxyPass /static ! ProxyPass / http://localhost:7780/ ProxyPassReverse / http://localhost:7780/ ErrorLog /home/cc/error.log CustomLog /home/cc/access.log combined SSLEngine on Include /etc/letsencrypt/options-ssl-apache.conf SSLCertificateFile /etc/letsencrypt/live/XXXXX.codecity.world/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/XXXXX.codecity.world/privkey.pem ================================================ FILE: etc/cc-localhost.conf ================================================ # Nginx configuration for Code City on localhost. # Warning: This configuration is insecure, users can hijack each other's perms. # # The easiest way to use this file is to leave it unedited and instead # start nginx using bin/nginx-dev, which will dynamically create # suitable config files on the fly. # Configuration applying to all servers. error_page 502 503 504 =503 /static/503.html; # Configuration applying to all proxy forwarding. proxy_set_header Host $http_host; proxy_set_header Forwarded $proxy_add_forwarded; # See below. proxy_set_header CodeCity-pathToSubdomain "?1"; proxy_pass_header Server; proxy_next_upstream_tries 1; proxy_max_temp_file_size 0; proxy_connect_timeout 10s; proxy_send_timeout 10s; proxy_read_timeout 10s; server { # Listen on port 8080 for both IPv6 and IPv4. listen [::]:8080 ipv6only=off; location / { # Proxy to Code City port 7780. proxy_pass http://127.0.0.1:7780/; } location /static/ { # Static files. autoindex on; index index.html; # Edit to be full path to CodeCity directory. # E.g. /home/userid/src/CodeCity root REPOSITORY; } location /login { # Proxy to loginServer.js port 7781. proxy_pass http://127.0.0.1:7781/login; } location /connect { # Proxy to connectServer.js port 7782. proxy_pass http://127.0.0.1:7782/connect; } location /mobwrite { # Proxy to mobwrite_server.py port 7783. proxy_pass http://127.0.0.1:7783/mobwrite; } } # Configuration for generating Forwarded: header, based on example from # https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/ # # Conceal the IP address of incoming connections by default, as it is # PII and we try to avoid giving users any chance to get their hands # on each other's PII. To enable inclusion of actual IP addresses of # incoming connections in the Forwarded header, uncomment the first # two matchers below. map $remote_addr $proxy_forwarded_for { # IPv4 addresses can be sent as-is. # ~^[0-9.]+$ "for=$remote_addr"; # IPv6 addresses need to be bracketed and quoted. # ~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\""; # Unix domain socket names cannot be represented in RFC 7239 syntax. default "for=unknown"; } # Append host and proto. map $proxy_forwarded_for $proxy_forwarded_elem { default "$proxy_forwarded_for;host=\"$http_host\";proto=$scheme"; } map $http_forwarded $proxy_add_forwarded { # If the incoming Forwarded header is syntactically valid, append to it. "~^(,[ \\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"; # Otherwise, replace it. default "$proxy_forwarded_elem"; } ================================================ FILE: etc/cc-onedomain.conf ================================================ # Nginx configuration for Code City using a single domain. # Warning: This configuration is insecure, users can hijack each other's perms. # Configuration applying to all servers. error_page 502 503 504 =503 /static/503.html; # Configuration applying to all proxy forwarding. proxy_set_header Host $http_host; proxy_set_header Forwarded $proxy_add_forwarded; # See below. proxy_set_header CodeCity-pathToSubdomain "?1"; proxy_pass_header Server; proxy_next_upstream_tries 1; proxy_max_temp_file_size 0; proxy_connect_timeout 10s; proxy_send_timeout 10s; proxy_read_timeout 10s; # Redirect all http traffic to https, except for ACME HTTP-01 challenges. server { # Listen on port 80 for both IPv6 and IPv4. listen [::]:80 ipv6only=off; location / { return 301 https://$host$request_uri; } # Serve ACME challenge files to enable automatic Certbot SSL # certificate renewals using HTTP-01 challenges. location /.well-known/ { # Serve these from the usual Debain default path so it doesn't # matter whether this config file is installed yet or not, and to # avoid having certbot have to write to /home/codecity/ root /var/www/html; } } # Code City configuration server { # Listen on port 443 for both IPv6 and IPv4. listen [::]:443 ssl ipv6only=off; # Replace INSTANCENAME with the domain name of your instance. Make # sure that the resulting filenames point at the certificate files # created by certbot. ssl_certificate /etc/letsencrypt/live/INSTANCENAME/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/INSTANCENAME/privkey.pem; # Canonicalise to a single domain. # # Replace INSTANCENAME (both places) with the domain name of your # instance. If you have more than one domain name for you instance, # put the canonical one here. if ( $host != INSTANCENAME ) { return 301 https://INSTANCENAME$request_uri; } location / { # Proxy to Code City port 7780. proxy_pass http://127.0.0.1:7780/; } location /static/ { # Static files. autoindex on; index index.html; # If requried, edit to be full path to CodeCity directory. Nginx # will add /static/ automatically since that's the location. # E.g.: /home/codecity/CodeCity; root /home/codecity/CodeCity; } location /login { # Proxy to loginServer.js port 7781. proxy_pass http://127.0.0.1:7781/login; } location /connect { # Proxy to connectServer.js port 7782. proxy_pass http://127.0.0.1:7782/connect; } location /mobwrite { # Proxy to mobwrite_server.py port 7783. proxy_pass http://127.0.0.1:7783/mobwrite; } } # Configuration for generating Forwarded: header, based on example from # https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/ # # Conceal the IP address of incoming connections by default, as it is # PII and we try to avoid giving users any chance to get their hands # on each other's PII. To enable inclusion of actual IP addresses of # incoming connections in the Forwarded header, uncomment the first # two matchers below. map $remote_addr $proxy_forwarded_for { # IPv4 addresses can be sent as-is. # ~^[0-9.]+$ "for=$remote_addr" # IPv6 addresses need to be bracketed and quoted. # ~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\""; # Unix domain socket names cannot be represented in RFC 7239 syntax. default "for=unknown"; } # Append host and proto. map $proxy_forwarded_for $proxy_forwarded_elem { default "$proxy_forwarded_for;host=\"$http_host\";proto=$scheme"; } map $http_forwarded $proxy_add_forwarded { # If the incoming Forwarded header is syntactically valid, append to it. "~^(,[ \\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"; # Otherwise, replace it. default "$proxy_forwarded_elem"; } ================================================ FILE: etc/cc-subdomain.conf ================================================ # Nginx configuration for Code City using multiple subdomains. # Configuration applying to all servers. # Replace INSTANCENAME with the domain name of your instance; make # sure the result is prefixed with the 'static' subdomain. # E.g.: static.example.codecity.world error_page 502 503 504 =503 https://static.INSTANCENAME/503.html; # Configuration applying to all proxy forwarding. proxy_set_header Host $http_host; proxy_set_header Forwarded $proxy_add_forwarded; # See below. proxy_set_header CodeCity-pathToSubdomain "?0"; proxy_pass_header Server; proxy_next_upstream_tries 1; proxy_max_temp_file_size 0; proxy_connect_timeout 10s; proxy_send_timeout 10s; proxy_read_timeout 10s; # Redirect all http traffic to https. server { # Listen on port 80 for both IPv6 and IPv4. listen [::]:80 ipv6only=off; return 301 https://$host$request_uri; } # Code City configuration server { # Listen on port 443 for both IPv6 and IPv4. listen [::]:443 ssl ipv6only=off; # Replace INSTANCENAME with the domain name of your instance. Make # sure that the resulting filenames point at the certificate files # created by certbot. ssl_certificate /etc/letsencrypt/live/INSTANCENAME/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/INSTANCENAME/privkey.pem; # # Canonicalise to a single domain. # # # # Replace regular expression with one that matches all non-canonical # # domains. # if ( $host ~ ^example\.codecity\.(academy|games)$ ) { # # Replace INSTANCENAME with the canonical domain name of your instance. # # E.g.: https://example.codecity.world$request_uri # return 301 https://INSTANCENAME$request_uri; # } # # Replace regular expression with one that matches all non-canonical # # subdomains. # if ( $host ~ ^(.*)\.example\.codecity\.(academy|games)$ ) { # # Replace INSTANCENAME with the canonical domain name of your instance. # # E.g.: https://$1.example.codecity.world$request_uri # return 301 https://$1.INSTANCENAME$request_uri; # } location / { # Proxy to Code City port 7780. proxy_pass http://127.0.0.1:7780/; } } # Login server. server { listen [::]:443 ssl; # Replace INSTANCENAME with the domain name of your instance; make # sure the result is prefixed with the 'login' subdomain. # E.g.: login.example.codecity.world server_name login.INSTANCENAME; location / { # Proxy to loginServer.js port 7781. proxy_pass http://127.0.0.1:7781/; } } # Connect server. server { listen [::]:443 ssl; # Replace INSTANCENAME with the domain name of your instance; make # sure the result is prefixed with the 'connect' subdomain. # E.g.: connect.example.codecity.world server_name connect.INSTANCENAME; location / { # Proxy to connectServer.js port 7782. proxy_pass http://127.0.0.1:7782/; } } # MobWrite server. server { listen [::]:443 ssl; # Replace INSTANCENAME with the domain name of your instance; make # sure the result is prefixed with the 'mobwrite' subdomain. # E.g.: mobwrite.example.codecity.world server_name mobwrite.INSTANCENAME; location / { # Proxy to mobwrite_server.py port 7783. proxy_pass http://127.0.0.1:7783/mobwrite; } } # Static file server. server { listen [::]:443 ssl; # Replace INSTANCENAME with the domain name of your instance; make # sure the result is prefixed with the 'static' subdomain. # E.g.: static.example.codecity.world server_name static.INSTANCENAME; location / { autoindex on; index index.html; # If required, edit to be full path to CodeCity static directory. # E.g. /home/codecity/CodeCity/static root /home/codecity/CodeCity/static; } } # Configuration for generating Forwarded: header, based on example from # https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/ # # Conceal the IP address of incoming connections by default, as it is # PII and we try to avoid giving users any chance to get their hands # on each other's PII. To enable inclusion of actual IP addresses of # incoming connections in the Forwarded header, uncomment the first # two matchers below. map $remote_addr $proxy_forwarded_for { # IPv4 addresses can be sent as-is. # ~^[0-9.]+$ "for=$remote_addr" # IPv6 addresses need to be bracketed and quoted. # ~^[0-9A-Fa-f:.]+$ "for=\"[$remote_addr]\""; # Unix domain socket names cannot be represented in RFC 7239 syntax. default "for=unknown"; } # Append host and proto. map $proxy_forwarded_for $proxy_forwarded_elem { default "$proxy_forwarded_for;host=\"$http_host\";proto=$scheme"; } map $http_forwarded $proxy_add_forwarded { # If the incoming Forwarded header is syntactically valid, append to it. "~^(,[ \\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"; # Otherwise, replace it. default "$proxy_forwarded_elem"; } ================================================ FILE: etc/codecity-connect.service ================================================ [Unit] Description=Code City Connect Server Documentation=https://github.com/google/CodeCity After=network.target [Service] SyslogIdentifier=cc-connect WorkingDirectory=/home/codecity/CodeCity/connect User=codecity Group=codecity ExecStart=@/home/codecity/CodeCity/connect/connectServer cc-connect Restart=on-failure ================================================ FILE: etc/codecity-login.service ================================================ [Unit] Description=Code City Login Server Documentation=https://github.com/google/CodeCity After=network.target [Service] SyslogIdentifier=cc-login WorkingDirectory=/home/codecity/CodeCity/login User=codecity Group=codecity ExecStart=@/home/codecity/CodeCity/login/loginServer cc-login Restart=on-failure ================================================ FILE: etc/codecity-mobwrite.service ================================================ [Unit] Description=Code City Login Server Documentation=https://github.com/google/CodeCity After=network.target [Service] SyslogIdentifier=cc-mobwrite WorkingDirectory=/home/codecity/CodeCity/mobwrite User=codecity Group=codecity ExecStart=@/usr/bin/python2 cc-mobwrite /home/codecity/CodeCity/mobwrite/mobwrite_server.py Restart=on-failure ================================================ FILE: etc/codecity.service ================================================ [Unit] Description=Code City Documentation=https://github.com/google/CodeCity After=network.target Wants=codecity-login.service codecity-connect.service codecity-mobwrite.service [Service] SyslogIdentifier=codecity WorkingDirectory=/home/codecity/CodeCity/database User=codecity Group=codecity ExecStart=@/home/codecity/CodeCity/server/codecity codecity codecity.cfg Restart=on-failure [Install] WantedBy=multi-user.target ================================================ FILE: etc/gcloud-snapshot ================================================ #!/bin/bash # Put this file in /etc/cron.daily/ to effect automatic daily snapshots. # # Must also have installed gcloud-snapshot.sh from: # # https://github.com/jacksegal/google-compute-snapshot/ # # and enabled the "compute engine" cloud API access scope for this # instance. /usr/local/sbin/gcloud-snapshot.sh -d 30 ================================================ FILE: login/login.html ================================================ Code City Login
Sign in
================================================ FILE: login/loginServer ================================================ #!/usr/bin/env node /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Node.js server that provides Google auth services to Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; const crypto = require('crypto'); const forwardedParse = require('forwarded-parse'); const fs = require('fs').promises; const {google} = require('googleapis'); const http = require('http'); const net = require('net'); const {URL, format: urlFormat} = require('url'); const oauth2Api = google.oauth2('v2'); // Configuration constants. const configFileName = 'loginServer.cfg'; // Global variables let CFG = null; const /** !Object */ clients = {}; const DEFAULT_CFG = { // Internal port for this HTTP server. Nginx hides this from users. httpPort: 7781, // URL of connect page (absolute or relative). connectUrl: 'https://connect.example.codecity.world/', // URL of static folder (absolute or relative). staticUrl: 'https://static.example.codecity.world/', // Google's API client ID. clientId: '00000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' + '.apps.googleusercontent.com', // Google's API client secret. clientSecret: 'yyyyyyyyyyyyyyyyyyyyyyyy', // Root domain. cookieDomain: 'example.codecity.world', // Regexp on email addresses that must pass to allow access. emailRegexp: '.*', // Port number for the login service backend. backendPort: 7776, /* List of fields, from data object returned by * oauth2Api.userinfo.v2.me.get, to pass along in the request the * login service backend. * * Available fieldnames, and the types and meanings of their values: * - id: string - the user's OAuth (GAIA) ID as a numeric string. * If salt is set (below), the .id will be salted and hashed with * sha512 before being sent to the login backend service. * - email: string - the user's email address. * - verified_email: boolean - has the user's email address been verified? * - name: string - the user's full name. * - given_name: string - the user's given name. * - family_name: string - the user's family name. * - picture: string - URL pointing to the user's profile picture. * - hd: string - the hosted domain, for GSuite accounts. */ backendFields: ['id'], /* Random salt for OAuth IDs. If set to '' the .id field received * from the Oauth server will be hashed but not salted. If set to * undefined (or not set) the .id wil be sent plaintext. */ salt: 'zzzzzzzzzzzzzzzz' }; /** * Serve an error to the given ServerResult. Also log information * about the failed IncomingMessage to the console. * @param {!http.IncomingMessage} request The request which triggered the error. * @param {!http.ServerResponse} response The ServerResult to send error to. * @param {number} statusCode the HTTP response code to be served. * @param {string} message An additional message to include in the result. * @return {void} */ function sendError(request, response, statusCode, message) { console.log('%s %s (Host: %s): %d %s', request.method, request.url.replace(/=[^&]*(?=&|$)/g, '=…'), request.headers.host, statusCode, message); response.writeHead(statusCode).end(message); } /** * Load a file from disk, add substitutions, and serve to the web. * @param {!IncomingMessage} request The request being answered. * @param {!http.ServerResponse} response The ServerResult to send the file to. * @param {string} filename Name of template file on disk. * @param {!Object} subs Object-map of replacement strings. */ async function serveFile(request, response, filename, subs) { let /** string */ data; try { data = String(await fs.readFile(filename, 'utf8')); } catch (err) { sendError(request, response, 500, `Unable to load file ${filename}: ${err}`); return; } // Inject substitutions. for (const name in subs) { data = data.replace(new RegExp(name, 'g'), subs[name]); } // Serve page to user. response.statusCode = 200; response.setHeader('Content-Type', 'text/html'); response.end(data); } /** * Send a string to the login service backend and return any data * received in response. * @param {string} query Data string to send to backend. * @return {!Promise} a promise yeilding the data received. */ async function pingBackend(query) { let result = ''; return new Promise((resolve, reject) => { const socket = net.createConnection({port: CFG.backendPort}); socket.on('connect', () => { socket.end(query); }); socket.on('error', (error) => { socket.destroy(); reject(error); }); socket.on('data', (data) => { result += String(data); }); socket.on('end', () => { resolve(result); }); }); } /** * Handles HTTP requests from web server. * @param {!Object} request HTTP server request object * @param {!Object} response HTTP server response object. */ async function handleRequest(request, response) { if (request.connection.remoteAddress !== '127.0.0.1') { sendError(request, response, 403, `Connection from ${request.connection.remoteAddress} denied.`); return; } // Determine what URL the client contacted us on. let proto = 'http'; // What proto we are actually listening to. let host = request.headers.host; // Host header we actually received. // See if the first reverse proxy knows better. const forwarded = request.headers.forwarded; if (forwarded) { try { const forwards = forwardedParse(forwarded); if (forwards[0]) { if (forwards[0].proto) proto = forwards[0].proto; if (forwards[0].host) host = forwards[0].host; } } catch (e) { sendError(request, response, 400, `Forwarded header: ${e.name}: ${e.message} of "${forwarded}"`); return; } } const url = new URL(request.url, `${proto}://${host}`); const loginUrl = urlFormat(url, {fragment: false, search: false}); // Get an authentication client for our interactions with Google. if (!clients[loginUrl]) { // Create client for login URL not seen before. clients[loginUrl] = new google.auth.OAuth2( CFG.clientId, CFG.clientSecret, loginUrl); } const oauth2Client = clients[loginUrl]; // No auth code? Serve login.html. const code = url.searchParams.get('code'); if (!code) { // Compute Google's login URL, including deciding where to // redirect to afterwards. const options = {scope: 'email'}; if (url.searchParams.has('after')) { options.state = url.searchParams.get('after'); } else if (url.searchParams.has('loginThenClose')) { options.state = CFG.staticUrl + 'login-close.html'; } else { options.state = CFG.connectUrl; } const subs = { '<<>>': oauth2Client.generateAuthUrl(options), '<<>>': CFG.staticUrl }; serveFile(request, response, 'login.html', subs); return; } // Handle the result of an OAuth login. let tokens; try { ({tokens} = await oauth2Client.getToken(code)); } catch (err) { sendError(request, response, 500, `Google OAuth2 fail: ${err}`); return; } // Now tokens contains an access_token and an optional // refresh_token. Save them. oauth2Client.setCredentials(tokens); let data; try { ({data} = await oauth2Api.userinfo.v2.me.get({auth: oauth2Client})); } catch (err) { sendError(request, response, 500, `Google Userinfo fail: ${err}`); return; } // Check email address is allowed. const emailRegexp = new RegExp(CFG.emailRegexp || '.*'); if (!emailRegexp.test(data.email)) { sendError(request, response, 403, `Login denied for ${data.email}`); return; } // FYI: If present, data.hd contains the GSfE domai, // e.g. 'students.gissv.org', or 'sjsu.edu'. We aren't using it // now, but this might be used to filter users. // Convert the OAuth (GAIA) ID into one unique for Code City. Use // CFG.salt to salt the sha512hash. If .salt === '', then .id will // still be hashed but not salted. // TODO(cpcallen): it would be more secure to append salt to id. if (('id' in data) && CFG.salt !== undefined) { data.id = crypto.createHash('sha512') .update(CFG.salt + data.id).digest('hex'); } // Contact login service backend if configured. let cookie; if (CFG.backendPort) { // Construct object to be passed to login service backend. const loginData = {}; for (const name of CFG.backendFields || ['id']) { if (name in data) loginData[name] = data[name]; } // Ping the login service backend. try { cookie = await pingBackend(JSON.stringify(loginData) + '\n'); } catch (err) { sendError(request, response, 500, `Login service backend fail: ${err}`); return; } } else { // Just use the (probably salted and hashed) id value like we used to. cookie = data.id; } if (!cookie) { sendError('Login service backend did not return a valid cookie'); return; } // Login successful. Issue ID cookie. if (!url.searchParams.has('state')) { sendError(request, response, 500, 'Login successful but loginServer forgot where to redirect to.'); return; } const domain = CFG.cookieDomain ? `Domain=${CFG.cookieDomain}; ` : ''; const redirectUrl = url.searchParams.get('state'); response.writeHead(302, { // Temporary redirect. 'Set-Cookie': `ID=${cookie}; HttpOnly; ${domain}Path=/`, 'Location': redirectUrl, }); response.end('Login OK. Redirecting.'); console.log('Accepted xxxx' + cookie.substring(cookie.length - 4)); } /** * Read the JSON configuration file and return it. If none is * present, write a stub and throw an error. */ async function readConfigFile(filename) { let data; try { data = await fs.readFile(filename, 'utf8'); } catch (err) { console.log(`Configuration file ${filename} not found. ` + 'Creating new file.'); data = JSON.stringify(DEFAULT_CFG, null, 2) + '\n'; await fs.writeFile(filename, data, 'utf8'); } CFG = JSON.parse(data); if (CFG.salt === DEFAULT_CFG.salt) { throw Error( `Configuration file ${filename} not configured. ` + 'Please edit this file.'); } if (!CFG.connectUrl.endsWith('/')) CFG.connectUrl += '/'; if (!CFG.staticUrl.endsWith('/')) CFG.staticUrl += '/'; } /** * Read configuration and start up the HTTP server. */ async function startup() { await readConfigFile(configFileName); // Start an HTTP server. const server = http.createServer(handleRequest); server.listen(CFG.httpPort, 'localhost', () => { console.log(`Login server listening on port ${CFG.httpPort}`); }); } startup(); ================================================ FILE: login/package.json ================================================ { "name": "codecity-login", "version": "0.0.0", "description": "Login server for the Code City project", "main": "loginServer.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/google/CodeCity.git" }, "author": "Google", "license": "Apache-2.0", "bugs": { "url": "https://github.com/google/CodeCity/issues" }, "homepage": "https://github.com/google/CodeCity#readme", "dependencies": { "forwarded-parse": "^2.1.1", "googleapis": "^59.0.0" }, "devDependencies": {} } ================================================ FILE: minimal/core_01_minimal.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Minimal database for Code City. * @author fraser@google.com (Neil Fraser) */ var user = null; var $ = {}; // System object: $.system $.system = {}; $.system.log = new 'CC.log'; $.system.checkpoint = new 'CC.checkpoint'; $.system.shutdown = new 'CC.shutdown'; $.system.connectionListen = new 'CC.connectionListen'; $.system.connectionUnlisten = new 'CC.connectionUnlisten'; $.system.connectionWrite = new 'CC.connectionWrite'; $.system.connectionClose = new 'CC.connectionClose'; // Physical object prototype: $.physical $.physical = {}; $.physical.name = 'Physical object prototype'; $.physical.description = ''; $.physical.location = null; $.physical.contents_ = null; $.physical.getContents = function() { return this.contents_ || []; }; $.physical.addContents = function(thing) { var contents = this.getContents(); contents.indexOf(thing) === -1 && contents.push(thing); this.contents_ = contents; }; $.physical.removeContents = function(thing) { var contents = this.getContents(); var index = contents.indexOf(thing); if (index !== -1) { contents.splice(index, 1); } this.contents_ = contents; }; $.physical.moveTo = function(dest) { var src = this.location; src && src.removeContents && src.removeContents(this); this.location = dest; dest && dest.addContents && dest.addContents(this); }; $.physical.look = function() { user.tell(this.name); user.tell(this.description); var contents = this.getContents(); if (contents.length) { var text = []; for (var i = 0; i < contents.length; i++) { text[i] = String(contents[i].name || contents[i]); } user.tell('Contents: ' + text.join(', ')); } }; $.physical.look.dobj = 'this'; // Thing prototype: $.thing $.thing = Object.create($.physical); $.thing.name = 'Thing prototype'; $.thing.get = function() { this.moveTo(user); user.tell('You pick up ' + this.name + '.'); if (user.location) { user.location.announce(user.name + ' picks up ' + this.name + '.'); } }; $.thing.get.dobj = 'this'; $.thing.drop = function() { this.moveTo(user.location); user.tell('You drop ' + this.name + '.'); if (user.location) { user.location.announce(user.name + ' drops ' + this.name + '.'); } }; $.thing.drop.dobj = 'this'; // Room prototype: $.room $.room = Object.create($.physical); $.room.name = 'Room prototype'; $.room.announce = function(text) { var contents = this.getContents(); for (var i = 0; i < contents.length; i++) { var thing = contents[i]; if (thing !== user && thing.tell) { thing.tell(text); } } }; // User prototype: $.user $.user = Object.create($.physical); $.user.name = 'User prototype'; $.user.connection = null; $.user.say = function(text) { user.tell('You say: ' + text); if (user.location) { user.location.announce(user.name + ' says: ' + text); } }; $.user.say.dobj = 'any'; $.user.eval = function(code) { user.tell(eval(code)); }; $.user.eval.dobj = 'any'; $.user.tell = function(text) { if (this.connection) { this.connection.write(text); } }; $.user.quit = function() { if (this.connection) { this.connection.close(); } }; $.user.quit.dobj = 'none'; // Command parser. $.execute = function(command) { var argstr = command.trim(); var verbstr = argstr; var dobjstr = ''; var dobj = null; var space = command.indexOf(' '); if (space !== -1) { verbstr = argstr.substring(0, space).trim(); dobjstr = argstr.substring(space).trim(); } if (!verbstr) { return; } if (dobjstr) { if (dobjstr === 'me') { dobj = user; } else if (dobjstr === 'here') { dobj = user.location; } else { var objects = [user].concat(user.getContents()); if (user.location && user.location.getContents) { objects.push(user.location); objects = objects.concat(user.location.getContents()); } for (var i = 0; i < objects.length; i++) { var obj = objects[i]; if (obj.name && obj.name.toLowerCase().startsWith(dobjstr.toLowerCase())) { dobj = obj; break; } } } } // Collect all objects which could host the verb. var hosts = [user, user.location, dobj]; for (var i = 0; i < hosts.length; i++) { var host = hosts[i]; if (!host) { continue; } // Check every verb on each object for a match. for (var prop in host) { var func = host[prop]; if (prop === verbstr && typeof func === 'function' && func.dobj) { if (func.dobj === 'any' || (func.dobj === 'this' && dobj === host) || (func.dobj === 'none' && !dobj)) { return host[prop](dobjstr); } } } } user.tell('Command not understood.'); }; // Database of users so that connections can bind to a user. $.userDatabase = Object.create(null); $.connection = {}; $.connection.onConnect = function() { this.user = null; this.buffer = ''; this.write('Welcome. Type name of user to connect as (Alpha or Beta).'); }; $.connection.onReceive = function(text) { this.buffer += text.replace(/\r/g, ''); var lf; while ((lf = this.buffer.indexOf('\n')) !== -1) { this.onReceiveLine(this.buffer.substring(0, lf)); this.buffer = this.buffer.substring(lf + 1); } }; $.connection.onReceiveLine = function(text) { if (this.user) { user = this.user; $.execute(text); return; } // Remainder of function handles login. text = text.trim().toLowerCase(); if ($.userDatabase[text]) { this.user = $.userDatabase[text]; if (this.user.connection) { this.user.connection.close(); $.system.log('Rebinding connection to ' + this.user.name); } else { $.system.log('Binding connection to ' + this.user.name); } this.user.connection = this; this.write('Connected as ' + this.user.name); user = this.user; $.execute('look here'); if (user.location) { user.location.announce(user.name + ' connects.'); } } else { this.write('Unknown user.'); } }; $.connection.onEnd = function() { if (this.user) { if (user.location) { user.location.announce(user.name + ' disconnects.'); } if (this.user.connection === this) { $.system.log('Unbinding connection from ' + this.user.name); this.user.connection = null; } this.user = null; } }; $.connection.write = function(text) { $.system.connectionWrite(this, text + '\n'); }; $.connection.close = function() { $.system.connectionClose(this); }; // Set up a room, two users, and a rock. (function () { var hangout = Object.create($.room); hangout.name = 'Hangout'; hangout.description = 'A place to hang out, chat, and program.'; var alpha = Object.create($.user); alpha.name = 'Alpha'; $.userDatabase[alpha.name.toLowerCase()] = alpha; alpha.description = 'Looks a bit Canadian.'; alpha.moveTo(hangout); var beta = Object.create($.user); beta.name = 'Beta'; $.userDatabase[beta.name.toLowerCase()] = beta; beta.description = 'Mostly harmless.'; beta.moveTo(hangout); var rock = Object.create($.thing); rock.name = 'Rock'; rock.description = 'Suspiciously cube shaped, made of granite.'; rock.moveTo(hangout); $.system.connectionListen(7777, $.connection); })(); ================================================ FILE: minimal/minimal.cfg ================================================ { "databaseDirectory": "./", "checkpointInterval": 0, "checkpointAtShutdown": false } ================================================ FILE: minimal/readme.txt ================================================ Minimal Database. This database demonstrates a very minimal Code City instance. It contains: * Two users (Alpha and Beta) * One room (Hangout) * One object (Rock) Run the database with: node codecity.js minimal Telnet to port 7777 Type either 'Alpha' or 'Beta' to connect as one of the two users. Once connected, the valid commands are: * say * eval * look [me|here|alpha|beta|hangout|rock] * get rock * drop rock * quit ================================================ FILE: mobwrite/mobwrite.cfg ================================================ ; --------------------- ; Settings for MobWrite ; --------------------- ; How long (in seconds) to compute a diff before giving up. ; Set to 0 to compute indefinitely. DIFF_TIMEOUT = 0.1 ; Demo usage should limit the maximum size of any text. ; Set to 0 to disable limit. MAX_CHARS = 100000 ; Delete any view which hasn't been accessed in a while. ; Format: {seconds|minutes|hours|days} TIMEOUT_VIEW = 30 minutes ; Delete any text which hasn't been accessed in a while. ; TIMEOUT_TEXT should be longer than the length of TIMEOUT_VIEW TIMEOUT_TEXT = 1 days ; How verbose the log should be. ; Choose from: CRITICAL, ERROR, WARNING, INFO, DEBUG LOGGING = DEBUG ; Port to listen on. LOCAL_PORT = 7783 ; Restrict all Telnet connections to come from this location. ; Set to "" to allow connections from anywhere. CONNECTION_ORIGIN = 127.0.0.1 ; Name of cookie that must be present, otherwise code 410 is returned. ; This is in the form of a regexp. Set to blank to disable feature. REQUIRED_COOKIE = ID ================================================ FILE: mobwrite/mobwrite_core.py ================================================ # Copyright 2009 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Core functions for a MobWrite client/server in Python. """ __author__ = "fraser@google.com (Neil Fraser)" import datetime import logging import re import diff_match_patch as dmp_module class Configuration(dict): def initConfig(self, filename): """Parse the config file and setup the preferences. Args: filename: Path to the config file. Raises: If the config is invalid, this function will thow an error. """ global MAX_CHARS, TIMEOUT_VIEW, TIMEOUT_TEXT def readConfigFile(filename): self.clear() lineRegex = re.compile("^(\w+)\s*=\s*(.+)$") # Attempt to open the file. try: f = open(filename) except: return # Parse the file. try: for line in f: line = line.strip() # Comment lines start with a ; if len(line) > 0 and not line.startswith(";"): r = lineRegex.match(line) if r: self[r.group(1)] = r.group(2) finally: f.close() def toTime(value): (quantity, unit) = value.split(None, 1) quantity = int(quantity) if (unit == "seconds"): delta = datetime.timedelta(seconds=quantity) elif (unit == "minutes"): delta = datetime.timedelta(minutes=quantity) elif (unit == "hours"): delta = datetime.timedelta(hours=quantity) elif (unit == "days"): delta = datetime.timedelta(days=quantity) else: raise "Config: Unknown time value." return delta readConfigFile(filename) # Set each of the configuration parameters. # If a parameter is not present, a reasonable default is specified here. # If a configuration is invalid, throw an error. DMP.Diff_Timeout = float(self.get("DIFF_TIMEOUT", 0.1)) MAX_CHARS = int(self.get("MAX_CHARS", 100000)) TIMEOUT_VIEW = toTime(self.get("TIMEOUT_VIEW", "30 minutes")) TIMEOUT_TEXT = toTime(self.get("TIMEOUT_TEXT", "1 days")) logLevel = self.get("LOGGING", "INFO") if logLevel == "CRITICAL": LOG.setLevel(logging.CRITICAL) elif logLevel == "ERROR": LOG.setLevel(logging.ERROR) elif logLevel == "WARNING": LOG.setLevel(logging.WARNING) elif logLevel == "INFO": LOG.setLevel(logging.INFO) elif logLevel == "DEBUG": LOG.setLevel(logging.DEBUG) else: raise "Config: Unknown logging level." LOG.info("Read %d settings from %s" % (len(self), filename)) class TextObj: # An object which stores a text. # Object properties: # .name - The unique name for this text, e.g 'proposal' # .text - The text itself. def __init__(self, *args, **kwargs): # Setup this object self.name = kwargs.get("name") self.text = None def setText(self, newtext): # Scrub the text before setting it. if newtext != None: # Normalize linebreaks to LF. newtext = re.sub(r"(\r\n|\r|\n)", "\n", newtext) # Keep the text within the length limit. if MAX_CHARS != 0 and len(newtext) > MAX_CHARS: newtext = newtext[-MAX_CHARS:] LOG.warning("Truncated text to %d characters." % MAX_CHARS) if self.text != newtext: self.text = newtext class ViewObj: # An object which contains one user's view of one text. # Object properties: # .username - The name for the user, e.g 'fraser' # .filename - The name for the file, e.g 'proposal' # .shadow - The last version of the text sent to client. # .backup_shadow - The previous version of the text sent to client. # .shadow_client_version - The client's version for the shadow (n). # .shadow_server_version - The server's version for the shadow (m). # .backup_shadow_server_version - the server's version for the backup # shadow (m). # .edit_stack - List of unacknowledged edits sent to the client. # .delta_ok - Did the previous delta match the text length. def __init__(self, *args, **kwargs): # Setup this object self.username = kwargs["username"] self.filename = kwargs["filename"] self.shadow_client_version = kwargs.get("shadow_client_version", 0) self.shadow_server_version = kwargs.get("shadow_server_version", 0) self.backup_shadow_server_version = kwargs.get("backup_shadow_server_version", 0) self.shadow = kwargs.get("shadow", u"") self.backup_shadow = kwargs.get("backup_shadow", u"") self.edit_stack = [] self.delta_ok = True class MobWrite: def parseRequest(self, data): """Parse the raw MobWrite commands into a list of specific actions. See: http://code.google.com/p/google-mobwrite/wiki/Protocol Args: data: A multi-line string of MobWrite commands. Returns: A list of actions, each action is a dictionary. Typical action: {"username":"fred", "filename":"report", "mode":"delta", "data":"=10+Hello-7=2", "force":False, "server_version":3, "client_version":3, "echo_username":False } """ # Passing a Unicode string is an easy way to cause numerous subtle bugs. if type(data) != str: LOG.critical("parseRequest data type is %s" % type(data)) return [] if not (data.endswith("\n\n") or data.endswith("\r\r") or data.endswith("\n\r\n\r") or data.endswith("\r\n\r\n")): # There must be a linefeed followed by a blank line. # Truncated data. Abort. LOG.warning("Truncated data: '%s'" % data) return [] # Parse the lines actions = [] username = None filename = None server_version = None echo_username = False for line in data.splitlines(): if not line: # Terminate on blank line. break if line.find(":") != 1: # Invalid line. continue (name, value) = (line[:1], line[2:]) # Parse out a version number for file, delta or raw. version = None if ("FfDdRr".find(name) != -1): div = value.find(":") if div > 0: try: version = int(value[:div]) except ValueError: LOG.warning("Invalid version number: %s" % line) continue value = value[div + 1:] else: LOG.warning("Missing version number: %s" % line) continue if name == "u" or name == "U": # Remember the username. username = value # Client may request explicit usernames in response. echo_username = (name == "U") elif name == "f" or name == "F": # Remember the filename and version. filename = value server_version = version elif name == "n" or name == "N": # Nullify this file. filename = value if username and filename: action = {} action["username"] = username action["filename"] = filename action["mode"] = "null" actions.append(action) else: # A delta or raw action. action = {} if name == "d" or name == "D": action["mode"] = "delta" elif name == "r" or name == "R": action["mode"] = "raw" else: action["mode"] = None if name.isupper(): action["force"] = True else: action["force"] = False action["server_version"] = server_version action["client_version"] = version action["data"] = value action["echo_username"] = echo_username if username and filename and action["mode"]: action["username"] = username action["filename"] = filename actions.append(action) return actions def applyPatches(self, viewobj, diffs, action): """Apply a set of patches onto the view and text objects. This function must be enclosed in a lock or transaction since the text object is shared. Args: viewobj: The user's view to be updated. diffs: List of diffs to apply to both the view and the server. action: Parameters for how forcefully to make the patch; may be modified. """ # Expand the fragile diffs into a full set of patches. patches = DMP.patch_make(viewobj.shadow, diffs) # First, update the client's shadow. viewobj.shadow = DMP.diff_text2(diffs) viewobj.backup_shadow = viewobj.shadow viewobj.backup_shadow_server_version = viewobj.shadow_server_version # Second, deal with the server's text. textobj = viewobj.textobj if textobj.text is None: # A view is sending a valid delta on a file we've never heard of. textobj.setText(viewobj.shadow) action["force"] = False LOG.debug("Set content: '%s'" % viewobj) else: if action["force"]: # Clobber the server's text if a change was received. if patches: mastertext = viewobj.shadow LOG.debug("Overwrote content: '%s'" % viewobj) else: mastertext = textobj.text else: (mastertext, results) = DMP.patch_apply(patches, textobj.text) LOG.debug("Patched (%s): '%s'" % (",".join(["%s" % (x) for x in results]), viewobj)) textobj.setText(mastertext) # Global Diff/Match/Patch object. DMP = dmp_module.diff_match_patch() # Global logging object. LOG = logging.getLogger("mobwrite") # Configuration object. CFG = Configuration() ================================================ FILE: mobwrite/mobwrite_core_test.py ================================================ #!/usr/bin/python2 # Copyright 2006 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import unittest import mobwrite_core # Force a module reload so to make debugging easier (at least in PythonWin). reload(mobwrite_core) class MobWriteCoreTest(unittest.TestCase): def setUp(self): mobwrite_core.LOG.setLevel(logging.ERROR) mobwrite_core.logging.basicConfig() def tearDown(self): mobwrite_core.logging.shutdown() def testParseRequest(self): mobwrite = mobwrite_core.MobWrite() actions = mobwrite.parseRequest("") self.assertEquals([], actions) actions = mobwrite.parseRequest("""u:fred f:3:report d:2:=10+Hello-7=2 """) self.assertEquals([{"username":"fred", "filename":"report", "mode":"delta", "data":"=10+Hello-7=2", "force":False, "server_version":3, "client_version":2, "echo_username":False }], actions) actions = mobwrite.parseRequest("""U:fred f:3:report R:2:Hello World """) self.assertEquals([{"username":"fred", "filename":"report", "mode":"raw", "data":"Hello World", "force":True, "server_version":3, "client_version":2, "echo_username":True }], actions) actions = mobwrite.parseRequest("""U:fred N:report """) self.assertEquals([{"username":"fred", "filename":"report", "mode":"null", }], actions) if __name__ == "__main__": unittest.main() ================================================ FILE: mobwrite/mobwrite_server.py ================================================ #!/usr/bin/python2 # Copyright 2006 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This file is MobWrite's server-side daemon. Runs in the background listening to a port, accepting synchronization sessions from clients. """ __author__ = "fraser@google.com (Neil Fraser)" import datetime import glob import os import re import sys import time import thread import urllib from BaseHTTPServer import BaseHTTPRequestHandler from BaseHTTPServer import HTTPServer import mobwrite_core # Demo usage should limit the maximum number of connected views. # Set to 0 to disable limit. MAX_VIEWS = 10000 # Dictionary of all text objects. texts = {} # Lock to prevent simultaneous changes to the texts dictionary. lock_texts = thread.allocate_lock() class TextObj(mobwrite_core.TextObj): # A persistent object which stores a text. # Object properties: # .lock - Access control for writing to the text on this object. # .views - Count of views currently connected to this text. # .lasttime - The last time that this text was modified. # Inherited properties: # .name - The unique name for this text, e.g 'proposal'. # .text - The text itself. def __init__(self, *args, **kwargs): # Setup this object mobwrite_core.TextObj.__init__(self, *args, **kwargs) self.views = 0 self.lasttime = datetime.datetime.now() self.lock = thread.allocate_lock() # lock_texts must be acquired by the caller to prevent simultaneous # creations of the same text. assert lock_texts.locked(), "Can't create TextObj unless locked." global texts texts[self.name] = self def setText(self, newText): mobwrite_core.TextObj.setText(self, newText) self.lasttime = datetime.datetime.now() def cleanup(self): # General cleanup task. if self.views > 0: return terminate = False # Lock must be acquired to prevent simultaneous deletions. self.lock.acquire() try: if self.lasttime < datetime.datetime.now() - mobwrite_core.TIMEOUT_TEXT: mobwrite_core.LOG.info("Expired text: '%s'" % self) terminate = True if terminate: # Terminate in-memory copy. global texts lock_texts.acquire() try: try: del texts[self.name] except KeyError: mobwrite_core.LOG.error("Text object not in text list: '%s'" % self) finally: lock_texts.release() finally: self.lock.release() def fetch_textobj(name, view): # Retrieve the named text object. Create it if it doesn't exist. # Add the given view into the text object's list of connected views. # Don't let two simultaneous creations happen, or a deletion during a # retrieval. lock_texts.acquire() try: if texts.has_key(name): textobj = texts[name] mobwrite_core.LOG.debug("Accepted text: '%s'" % name) else: textobj = TextObj(name=name) mobwrite_core.LOG.debug("Creating text: '%s'" % name) textobj.views += 1 finally: lock_texts.release() return textobj # Dictionary of all view objects. views = {} # Lock to prevent simultaneous changes to the views dictionary. lock_views = thread.allocate_lock() class ViewObj(mobwrite_core.ViewObj): # A persistent object which contains one user's view of one text. # Object properties: # .lasttime - The last time that a web connection serviced this object. # .textobj - The shared text object being worked on. # Inherited properties: # .username - The name for the user, e.g 'fraser' # .filename - The name for the file, e.g 'proposal' # .shadow - The last version of the text sent to client. # .backup_shadow - The previous version of the text sent to client. # .shadow_client_version - The client's version for the shadow (n). # .shadow_server_version - The server's version for the shadow (m). # .backup_shadow_server_version - the server's version for the backup # shadow (m). # .edit_stack - List of unacknowledged edits sent to the client. # .delta_ok - Did the previous delta match the text length. def __init__(self, *args, **kwargs): # Setup this object mobwrite_core.ViewObj.__init__(self, *args, **kwargs) self.lasttime = datetime.datetime.now() self.textobj = fetch_textobj(self.filename, self) # lock_views must be acquired by the caller to prevent simultaneous # creations of the same view. assert lock_views.locked(), "Can't create ViewObj unless locked." global views views[(self.username, self.filename)] = self def cleanup(self): # General cleanup task. # Delete myself if I've been idle too long. # Don't delete during a retrieval. lock_views.acquire() try: if self.lasttime < datetime.datetime.now() - mobwrite_core.TIMEOUT_VIEW: mobwrite_core.LOG.info("Idle out: '%s'" % self) global views try: del views[(self.username, self.filename)] except KeyError: mobwrite_core.LOG.error("View object not in view list: '%s'" % self) self.textobj.views -= 1 finally: lock_views.release() def nullify(self): self.lasttime = datetime.datetime.min self.cleanup() def fetch_viewobj(username, filename): # Retrieve the named view object. Create it if it doesn't exist. # Don't let two simultaneous creations happen, or a deletion during a # retrieval. lock_views.acquire() try: key = (username, filename) if views.has_key(key): viewobj = views[key] viewobj.lasttime = datetime.datetime.now() mobwrite_core.LOG.debug("Accepting view: '%s'" % viewobj) else: if MAX_VIEWS != 0 and len(views) > MAX_VIEWS: viewobj = None mobwrite_core.LOG.critical("Overflow: Can't create new view.") else: viewobj = ViewObj(username=username, filename=filename) mobwrite_core.LOG.debug("Creating view: '%s'" % viewobj) finally: lock_views.release() return viewobj class DaemonMobWrite(BaseHTTPRequestHandler, mobwrite_core.MobWrite): def do_POST(self): connection_origin = mobwrite_core.CFG.get("CONNECTION_ORIGIN", "") if connection_origin and self.client_address[0] != connection_origin: raise IOError("Connection refused from %s (only %s allowed)." % (self.client_address[0], connection_origin)) mobwrite_core.LOG.info("Connection accepted from " + self.client_address[0]) required_cookie = mobwrite_core.CFG.get("REQUIRED_COOKIE", "") if required_cookie and (('Cookie' not in self.headers) or (not re.search(r'(^|;)\s*%s=\w' % required_cookie, self.headers['Cookie']))): self.send_headers(410) self.wfile.write("Required cookie not found.\n") return # Read the POST data. content_length = int(self.headers['Content-Length']) data = self.rfile.read(content_length) div = data.find("q=") if div == -1: self.send_headers(400) self.wfile.write("'q=' parameter not found in data:\n") self.wfile.write(data) return data = data[div + 2:] data = urllib.unquote(data) self.send_headers(200) self.wfile.write(self.handleRequest(data)) self.wfile.write("\n") # Terminating blank line. # Goodbye mobwrite_core.LOG.debug("Disconnecting.") def send_headers(self, code): origin = self.headers['Origin'] self.send_response(code) self.send_header('Content-type', 'text/plain') self.send_header('Access-Control-Allow-Origin', origin) self.send_header('Access-Control-Allow-Credentials', 'true') self.end_headers() def handleRequest(self, text): actions = self.parseRequest(text) return self.doActions(actions) def doActions(self, actions): output = [] viewobj = None last_username = None last_filename = None for action_index in xrange(len(actions)): # Use an indexed loop in order to peek ahead one step to detect # username/filename boundaries. action = actions[action_index] username = action["username"] filename = action["filename"] # Fetch the requested view object. if not viewobj: viewobj = fetch_viewobj(username, filename) if viewobj is None: # Too many views connected at once. # Send back nothing. Pretend the return packet was lost. return "" viewobj.delta_ok = True textobj = viewobj.textobj if action["mode"] == "null": # Nullify the text. mobwrite_core.LOG.debug("Nullifying: '%s'" % viewobj) textobj.lock.acquire() try: textobj.setText(None) finally: textobj.lock.release() viewobj.nullify(); viewobj = None continue if (action["server_version"] != viewobj.shadow_server_version and action["server_version"] == viewobj.backup_shadow_server_version): # Client did not receive the last response. Roll back the shadow. mobwrite_core.LOG.warning("Rollback from shadow %d to backup shadow %d" % (viewobj.shadow_server_version, viewobj.backup_shadow_server_version)) viewobj.shadow = viewobj.backup_shadow viewobj.shadow_server_version = viewobj.backup_shadow_server_version viewobj.edit_stack = [] # Remove any elements from the edit stack with low version numbers which # have been acked by the client. x = 0 while x < len(viewobj.edit_stack): if viewobj.edit_stack[x][0] <= action["server_version"]: del viewobj.edit_stack[x] else: x += 1 if action["mode"] == "raw": # It's a raw text dump. data = urllib.unquote(action["data"]).decode("utf-8") mobwrite_core.LOG.info("Got %db raw text: '%s'" % (len(data), viewobj)) viewobj.delta_ok = True # First, update the client's shadow. viewobj.shadow = data viewobj.shadow_client_version = action["client_version"] viewobj.shadow_server_version = action["server_version"] viewobj.backup_shadow = viewobj.shadow viewobj.backup_shadow_server_version = viewobj.shadow_server_version viewobj.edit_stack = [] if action["force"] or textobj.text is None: # Clobber the server's text. textobj.lock.acquire() try: if textobj.text != data: textobj.setText(data) mobwrite_core.LOG.debug("Overwrote content: '%s'" % viewobj) finally: textobj.lock.release() elif action["mode"] == "delta": # It's a delta. mobwrite_core.LOG.info("Got '%s' delta: '%s'" % (action["data"], viewobj)) if action["server_version"] != viewobj.shadow_server_version: # Can't apply a delta on a mismatched shadow version. viewobj.delta_ok = False mobwrite_core.LOG.warning("Shadow version mismatch: %d != %d" % (action["server_version"], viewobj.shadow_server_version)) elif action["client_version"] > viewobj.shadow_client_version: # Client has a version in the future? viewobj.delta_ok = False mobwrite_core.LOG.warning("Future delta: %d > %d" % (action["client_version"], viewobj.shadow_client_version)) elif action["client_version"] < viewobj.shadow_client_version: # We've already seen this diff. pass mobwrite_core.LOG.warning("Repeated delta: %d < %d" % (action["client_version"], viewobj.shadow_client_version)) else: # Expand the delta into a diff using the client shadow. try: diffs = mobwrite_core.DMP.diff_fromDelta(viewobj.shadow, action["data"]) except ValueError: diffs = None viewobj.delta_ok = False mobwrite_core.LOG.warning("Delta failure, expected %d length: '%s'" % (len(viewobj.shadow), viewobj)) viewobj.shadow_client_version += 1 if diffs != None: # Textobj lock required for read/patch/write cycle. textobj.lock.acquire() try: self.applyPatches(viewobj, diffs, action) finally: textobj.lock.release() # Generate output if this is the last action or the username/filename # will change in the next iteration. if ((action_index + 1 == len(actions)) or actions[action_index + 1]["username"] != username or actions[action_index + 1]["filename"] != filename): print_username = None print_filename = None if action["echo_username"] and last_username != username: # Print the username if the previous action was for a different user. print_username = username if last_filename != filename or last_username != username: # Print the filename if the previous action was for a different user # or file. print_filename = filename output.append(self.generateDiffs(viewobj, print_username, print_filename, action["force"])) last_username = username last_filename = filename # Dereference the view object so that a new one can be created. viewobj = None return "".join(output) def generateDiffs(self, viewobj, print_username, print_filename, force): output = [] if print_username: output.append("u:%s\n" % print_username) if print_filename: output.append("F:%d:%s\n" % (viewobj.shadow_client_version, print_filename)) textobj = viewobj.textobj mastertext = textobj.text if viewobj.delta_ok: if mastertext is None: mastertext = "" # Create the diff between the view's text and the master text. diffs = mobwrite_core.DMP.diff_main(viewobj.shadow, mastertext) mobwrite_core.DMP.diff_cleanupEfficiency(diffs) text = mobwrite_core.DMP.diff_toDelta(diffs) if force: # Client sending 'D' means number, no error. # Client sending 'R' means number, client error. # Both cases involve numbers, so send back an overwrite delta. viewobj.edit_stack.append((viewobj.shadow_server_version, "D:%d:%s\n" % (viewobj.shadow_server_version, text))) else: # Client sending 'd' means text, no error. # Client sending 'r' means text, client error. # Both cases involve text, so send back a merge delta. viewobj.edit_stack.append((viewobj.shadow_server_version, "d:%d:%s\n" % (viewobj.shadow_server_version, text))) viewobj.shadow_server_version += 1 mobwrite_core.LOG.info("Sent '%s' delta: '%s'" % (text, viewobj)) else: # Error; server could not parse client's delta. # Send a raw dump of the text. viewobj.shadow_client_version += 1 if mastertext is None: mastertext = "" viewobj.edit_stack.append((viewobj.shadow_server_version, "r:%d:\n" % viewobj.shadow_server_version)) mobwrite_core.LOG.info("Sent empty raw text: '%s'" % viewobj) else: # Force overwrite of client. text = mastertext text = text.encode("utf-8") text = urllib.quote(text, "!~*'();/?:@&=+$,# ") viewobj.edit_stack.append((viewobj.shadow_server_version, "R:%d:%s\n" % (viewobj.shadow_server_version, text))) mobwrite_core.LOG.info("Sent %db raw text: '%s'" % (len(text), viewobj)) viewobj.shadow = mastertext for edit in viewobj.edit_stack: output.append(edit[1]) return "".join(output) def cleanup_thread(): # Every minute cleanup. while True: mobwrite_core.LOG.info("Running cleanup task.") for v in views.values(): v.cleanup() for v in texts.values(): v.cleanup() timeout = datetime.datetime.now() - mobwrite_core.TIMEOUT_TEXT time.sleep(60) def main(): mobwrite_core.CFG.initConfig("./mobwrite.cfg") # Start up a thread that does timeouts and cleanup. thread.start_new_thread(cleanup_thread, ()) port = int(mobwrite_core.CFG.get("LOCAL_PORT", 3017)) mobwrite_core.LOG.info("Listening on port %d..." % port) s = HTTPServer(("", port), DaemonMobWrite) try: s.serve_forever() except KeyboardInterrupt: mobwrite_core.LOG.info("Shutting down.") s.socket.close() if __name__ == "__main__": mobwrite_core.logging.basicConfig() main() mobwrite_core.logging.shutdown() ================================================ FILE: server/code.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Utilities for manipulating JavaScript code. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; /** * A collection of useful regular expressions. * @const */ var regexps = {}; /** * Matches (globally) escape sequences found in string and regexp * literals, like '\n' or '\x20' or '\u1234'. * @const */ regexps.escapes = /\\(?:["'\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g; /** * Matches a single-quoted string literal, like "'this one'" and * "'it\\'s'". * @const */ regexps.singleQuotedString = new RegExp("'(?:[^'\\\\\\r\\n\\u2028\\u2029]|" + regexps.escapes.source + ")*'", 'g'); /** * Matches a double-quoted string literal, like '"this one"' and * '"it\'s"'. * @const */ regexps.doubleQuotedString = new RegExp('"(?:[^"\\\\\\r\\n\\u2028\\u2029]|' + regexps.escapes.source + ')*"', 'g'); /** * Matches a string literal, like "'this one' and '"that one"' as well * as "the 'string literal' substring of this longer string" too. * @const */ regexps.string = new RegExp('(?:' + regexps.singleQuotedString.source + '|' + regexps.doubleQuotedString.source + ')', 'g'); /** * Matches exaclty a string literal, like "'this one'" but notably not * " 'this one' " (because it contains other characters not part of * the literal). * @const */ regexps.stringExact = new RegExp('^' + regexps.string.source + '$'); /** * RegExp matching a valid JavaScript identifier (strictly an * IdentifierName, which does not exclude ReservedWord). Note that * this is fairly conservative, because ANY Unicode letter can appear * in an identifier - but the full regexp is absurdly complicated. * @const */ regexps.identifier = /[A-Za-z_$][A-Za-z0-9_$]*/g; /** * RegExp matching exactly a valid JavaScript identifier. See note * for .identifier, above. * @const */ regexps.identifierExact = new RegExp('^' + regexps.identifier.source + '$'); /** * Convert a string representation of a string literal to a string. * Basically does eval(s), but safely and only if s is a string literal. * @param {string} s A string consisting of exactly a string literal. * @return {string} The string value of the literal s. */ var parseString = function(s) { if (!regexps.stringExact.test(s)) { throw new TypeError(quote(s) + ' is not a string literal'); }; return s.slice(1, -1).replace(regexps.escapes, function(esc) { switch (esc[1]) { case "'": case '"': case '/': case '\\': return esc[1]; case '0': return '\0'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case 'u': case 'x': return String.fromCharCode(parseInt(esc.slice(2), 16)); default: // RegExp in call to replace has accepted something we // don't know how to decode. throw new Error('unknown escape sequence "' + esc + '"??'); } }); }; /** * Convert a string into a string literal. We use single or double * quotes depending on which occurs less frequently in the string to * be escaped (prefering single quotes if it's a tie). Strictly * speaking we only need to escape backslash, \r, \n, \u2028 (line * separator), \u2029 (paragraph separator) and whichever quote * character we're using, but for output readability we escape all the * control characters. * * TODO(cpcallen): Consider using optimised algorithm from Node.js's * util.format (see strEscape function in * https://github.com/nodejs/node/blob/master/lib/util.js). * @param {string} str The string to convert. * @return {string} The value s as a eval-able string literal. */ var quote = function(str) { if (count(str, "'") > count(str, '"')) { // More 's. Use "s. return '"' + str.replace(quote.doubleRE, quote.replace) + '"'; } else { // Equal or more "s. Use 's. return "'" + str.replace(quote.singleRE, quote.replace) + "'"; } }; /** * Regexp for characters to be escaped in a single-quoted string. */ quote.singleRE = /[\x00-\x1f\\\u2028\u2029']/g; /** * Regexp for characters to be escaped in a single-quoted string. */ quote.doubleRE = /[\x00-\x1f\\\u2028\u2029"]/g; /** * Replacer function (for either case) * @param {string} c Single UTF-16 code unit ("character") string to * be replaced. * @return {string} Multi-character string containing escaped * representation of c. */ quote.replace = function(c) { return quote.replacements[c]; }; /** * Map of replacements for quote function. */ quote.replacements = { '\x00': '\\0', '\x01': '\\x01', '\x02': '\\x02', '\x03': '\\x03', '\x04': '\\x04', '\x05': '\\x05', '\x06': '\\x06', '\x07': '\\x07', '\x08': '\\b', '\x09': '\\t', '\x0a': '\\n', '\x0b': '\\v', '\x0c': '\\f', '\x0d': '\\r', '\x0e': '\\x0e', '\x0f': '\\x0f', '"': '\\"', "'": "\\'", '\\': '\\\\', '\u2028': '\\u2028', '\u2029': '\\u2029', }; /** * Count non-overlapping occurrences of searchString in str. * * There are many possible implementations; using .split works pretty * well but this is slightly faster at time of writing. See * https://jsperf.com/count-the-number-of-characters-in-a-string for * latest performance measurements. * @param {string} str The string to be searched. * @param {string} searchString The string to count occurrences of. * @return {number} The number of occurrences of searchString in str. */ var count = function(str, searchString) { var index = 0; for(var count = 0; ; count++) { index = str.indexOf(searchString, index); if (index === -1) return count; index += searchString.length; } }; exports.quote = quote; exports.regexps = regexps; exports.parseString = parseString; // For unit testing only! exports.testOnly = { count: count, } ================================================ FILE: server/codecity ================================================ #!/usr/bin/env node /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview A virtual world of collaborative coding. * @author fraser@google.com (Neil Fraser) */ 'use strict'; const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const Interpreter = require('./interpreter'); const Parser = require('./parser').Parser; const Serializer = require('./serialize'); var CodeCity = {}; CodeCity.databaseDirectory = ''; CodeCity.interpreter = null; CodeCity.config = null; /** * Start a running instance of Code City. May be called on a command line. * @param {string=} configFile Path and filename of configuration file. * If not present, look for the configuration file as a command line parameter. */ CodeCity.startup = function(configFile) { // process.argv is a list containing: ['node', 'codecity', 'db/google.cfg'] configFile = configFile || process.argv[2]; if (!configFile) { console.error('Configuration file not found.\n' + 'Usage: node %s ', process.argv[1]); process.exit(1); } var contents = CodeCity.loadFile(configFile); CodeCity.config = CodeCity.parseJson(contents); // Find the most recent database file. var dir = CodeCity.config.databaseDirectory || './'; if (dir[0] === '/') { CodeCity.databaseDirectory = dir; } else { CodeCity.databaseDirectory = path.join(path.dirname(configFile), dir); } if (!fs.existsSync(CodeCity.databaseDirectory)) { console.error('Database directory not found: ' + CodeCity.databaseDirectory); process.exit(1); } // Find the most recent database file. var checkpoint = CodeCity.allCheckpoints()[0]; // Load the interpreter. if (checkpoint) { var filename = path.join(CodeCity.databaseDirectory, checkpoint); CodeCity.interpreter = CodeCity.loadCheckpoint(filename); } else { // Database not found, load one or more startup files instead. console.log('Unable to find database file in %s, looking for startup ' + 'file(s) instead.', CodeCity.databaseDirectory); CodeCity.interpreter = CodeCity.loadStartup(CodeCity.databaseDirectory); } // Checkpoint at regular intervals. // TODO: Let the interval be configurable from the database. var interval = CodeCity.config.checkpointInterval || 600; CodeCity.config.checkpointInterval = interval; if (interval > 0) { setInterval(CodeCity.checkpoint, interval * 1000); } console.log('Load complete. Starting Code City.'); CodeCity.interpreter.start(); }; /** * Create an Interpreter instance with desired options and initialise * it with custom builtins. * @return {!Interpreter} */ CodeCity.makeInterpreter = function() { var intrp = new Interpreter({ trimEval: true, trimProgram: true, methodNames: true, stackLimit: 10000, }); CodeCity.initSystemFunctions(intrp); CodeCity.initLibraryFunctions(intrp); return intrp; }; /** * Create an Interpreter instance and deserialise a .city checkpoint * into it. * @param {string} filename The filename of the .city file to read. * @return {!Interpreter} */ CodeCity.loadCheckpoint = function(filename) { var intrp = CodeCity.makeInterpreter(); var flatpack = CodeCity.parseJson(CodeCity.loadFile(filename)); Serializer.deserialize(flatpack, intrp); console.log('Checkpoint %s loaded.', filename); return intrp; }; /** * Create an Interpreter instance and load startup .js files into it. * @param {string} dir The directory containing startup files to be read. * @return {!Interpreter} */ CodeCity.loadStartup = function(dir) { var intrp = CodeCity.makeInterpreter(); var fileCount = 0; var files = fs.readdirSync(dir); for (var i = 0; i < files.length; i++) { if (files[i].match(/^(core|db|test).*\.js$/)) { var filename = path.join(dir, files[i]); var contents = CodeCity.loadFile(filename); console.log('Loading startup file %s', filename); intrp.createThreadForSrc(contents); fileCount++; } } if (fileCount === 0) { console.error('Unable to find startup file(s) in %s', dir); process.exit(1); } console.log('Loaded %d startup file(s) from %s', fileCount, dir); return intrp; }; /** * Open a file and read its contents. Die if there's an error. * @param {string} filename * @return {string} File contents. */ CodeCity.loadFile = function(filename) { // Load the specified file from disk. try { return fs.readFileSync(filename, 'utf8').toString(); } catch (e) { console.error('Unable to open file: %s', filename); console.info(e); process.exit(1); } }; /** * Parse text as JSON value. Die if there's an error. * @param {string} text * @return {*} JSON value. */ CodeCity.parseJson = function(text) { // Convert from text to JSON. try { return JSON.parse(text); } catch (e) { console.error('Syntax error in parsing JSON'); console.info(e); process.exit(1); } }; /** * Return a list of all currently saved checkpoints, ordered from most * to least recent. * @return {!Array} Array of filenames for checkpoints. */ CodeCity.allCheckpoints = function() { var files = fs.readdirSync(CodeCity.databaseDirectory); files = files.filter((file) => CodeCity.allCheckpoints.regexp_.test(file)); files.sort().reverse(); return files; }; CodeCity.allCheckpoints.regexp_ = /^\d{4}-\d\d-\d\dT\d\d\.\d\d\.\d\d(\.\d{1,3})?Z?\.city$/; /** * Delete as many checkpoints as needed until there's room to fit a new one. */ CodeCity.deleteCheckpointsIfNeeded = function() { var checkpoints = CodeCity.allCheckpoints(); var minFiles = Math.max(0, CodeCity.config.checkpointMinFiles || 0); if (!checkpoints.length || checkpoints.length < minFiles) { return; // Not enough checkpoints saved. } // Look up size of last checkpoint. var lastCheckpointSize = CodeCity.fileSize(checkpoints[checkpoints.length - 1]); var directorySize = checkpoints.reduce((sum, fileName) => sum + CodeCity.fileSize(fileName), 0); // Budget for a possible 10% growth. var estimateNext = directorySize + lastCheckpointSize * 1.1; var maxSize = CodeCity.config.checkpointMaxDirectorySize * 1024 * 1024; if (typeof maxSize !== 'number') { maxSize = Infinity; } if (estimateNext < maxSize) { return; // There's room. } // Choose and delete one file. var deleteFile = CodeCity.chooseCheckpointToDelete(checkpoints); var fullPath = path.join(CodeCity.databaseDirectory, deleteFile); console.log('Deleting checkpoint ' + fullPath); fs.unlinkSync(fullPath); // Do it again, until no delete is needed. CodeCity.deleteCheckpointsIfNeeded(); }; /** * Given a list of checkpoint filenames, choose one to delete. * See https://neil.fraser.name/software/backup/ * @param {!Array} checkpoints Array of checkpoint filenames. * @return {string} Filename of checkpoint to delete. */ CodeCity.chooseCheckpointToDelete = function(checkpoints) { // Convert all filenames (e.g. '2018-11-09T18.49.50.548Z.city') // into ISO-8601 format (e.g. '2018-11-09T18:49:50.548Z'), // then parse as milliseconds. var checkpointTimes = checkpoints.map((name) => Date.parse(name.slice(0, -5).replace('.', ':').replace('.', ':'))); var currentTime = Date.now(); var totalTime = currentTime - checkpointTimes[checkpointTimes.length - 1]; var interval = CodeCity.config.checkpointInterval * 1000; // Planning to delete one checkpoint. var checkpointCount = checkpoints.length - 1; // Compute ideal times. var missing = Math.max(totalTime / interval - checkpointCount, 0); var decayRate = (missing + 1) ** (1 / checkpointCount); var idealTimes = new Array(checkpointTimes.length); for (var n = 0; n < checkpointTimes.length; n++) { idealTimes[n] = currentTime - (interval * (n + decayRate ** n - 1)); } // Choose one backup for deletion. // Compute the cumulative error from the right side. Store in array. var rightDiff = new Array(checkpointTimes.length); var accumulator = 0; for (var n = checkpointTimes.length - 1; n >= 1; n--) { accumulator += Math.abs(checkpointTimes[n] - idealTimes[n]); rightDiff[n] = accumulator; } // Compute the cumulative error from the left side (with backups shifted by // one position, as would happen after a deletion). // Use rightDiff array to compute total error for each possible deletion. accumulator = 0; var minDiff = Infinity; var minIndex = 0; for (var n = 1; n < checkpointTimes.length - 1; n++) { accumulator += Math.abs(checkpointTimes[n - 1] - idealTimes[n]); var diff = accumulator + rightDiff[n + 1]; if (diff < minDiff) { // Smallest total error yet. Save this candidate. minDiff = diff; minIndex = n; } } return checkpoints[minIndex]; }; /** * Find the size of a file in the current database directory. * @param {string} fileName Name of file. * @return {number} Number of bytes in file. */ CodeCity.fileSize = function(fileName) { var fullPath = path.join(CodeCity.databaseDirectory, fileName); return fs.statSync(fullPath).size; }; /** * Save the database to disk. * @param {boolean} sync True if Code City intends to shutdown afterwards. * False if Code City is running this in the background. */ CodeCity.checkpoint = function(sync) { console.log('Checkpointing...'); CodeCity.deleteCheckpointsIfNeeded(); try { CodeCity.interpreter.pause(); var json = Serializer.serialize(CodeCity.interpreter); } finally { sync || CodeCity.interpreter.start(); } // JSON.stringify(json) would work, but adding linebreaks so that every // object is on its own line makes the output more readable. var text = []; for (var i = 0; i < json.length; i++) { text.push(JSON.stringify(json[i])); } text = '[' + text.join(',\n') + ']'; var filename = (new Date()).toISOString().replace(/:/g, '.') + '.city'; filename = path.join(CodeCity.databaseDirectory, filename); var tmpFilename = filename + '.partial'; try { fs.writeFileSync(tmpFilename, text); fs.renameSync(tmpFilename, filename); console.log('Checkpoint ' + filename + ' complete.'); } catch (e) { console.error('Checkpoint failed! ' + e); } finally { // Attempt to remove partially-written checkpoint if it still exists. try { fs.unlinkSync(tmpFilename); } catch (e) { } } }; /** * Shutdown Code City. Checkpoint the database before terminating. * Optional parameter is exit code (if numeric) or signal to (re-)kill * process with (if string). Re-killing after checkpointing allows * systemd to accurately determine cause of death. Defaults to 0. * @param {string|number=} code Exit code or signal. */ CodeCity.shutdown = function(code) { if (CodeCity.config.checkpointAtShutdown !== false) { CodeCity.checkpoint(true); } if (typeof code === 'string') { process.kill(process.pid, code); } else { process.exit(code || 0); } }; /** * Print one line to the log. Allows for interpolated strings. * @param {...*} var_args Arbitrary arguments for console.log. */ CodeCity.log = function(var_args) { console.log.apply(console, arguments); }; /** * Initialize user-callable system functions. * These are not part of any JavaScript standard. * BUG(#280): provide (new) NativeFunction wrappers. * @param {!Interpreter} intrp The Interpreter instance to initialize. */ CodeCity.initSystemFunctions = function(intrp) { intrp.createNativeFunction('CC.log', CodeCity.log, false); intrp.createNativeFunction('CC.checkpoint', CodeCity.checkpoint, false); intrp.createNativeFunction('CC.shutdown', function(code) { CodeCity.shutdown(Number(code)); }, false); }; /** * Initialize user-callable library functions. * These are not part of any JavaScript standard. * @param {!Interpreter} intrp The Interpreter instance to initialize. */ CodeCity.initLibraryFunctions = function(intrp) { new intrp.NativeFunction({ id: 'CC.acorn.parse', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var code = args[0]; var perms = state.scope.perms; if (typeof code !== 'string') { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'argument to parse must be a string'); } try { var ast = Parser.parse(code); } catch (e) { throw intrp.errorNativeToPseudo(e, perms); } return intrp.nativeToPseudo(ast, perms); } }); new intrp.NativeFunction({ id: 'CC.acorn.parseExpressionAt', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var code = args[0]; var offset = args[1]; var perms = state.scope.perms; if (typeof code !== 'string') { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'first argument to parseExpressionAt must be a string'); } if (typeof offset !== 'number') { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'second argument to parseExpressionAt must be a number'); } try { var ast = Parser.parseExpressionAt(code, offset); } catch (e) { throw intrp.errorNativeToPseudo(e, perms); } return intrp.nativeToPseudo(ast, perms); } }); new intrp.NativeFunction({ id: 'CC.hash', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var hash = String(args[0]); var data = args[1]; var perms = state.scope.perms; var hashes = crypto.getHashes(); if (!hashes.includes(hash)) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'first argument to hash must be one of:\n' + hashes.map(function(h) {return " '" + h + "'\n";}).join('')); } if (typeof data !== 'string') { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'second argument to hash must be a string'); } try { return String(crypto.createHash(hash).update(data).digest('hex')); } catch (e) { throw intrp.errorNativeToPseudo(e, perms); } } }); }; /////////////////////////////////////////////////////////////////////////////// // Main program. // If this file is executed form a command line, startup Code City. // Otherwise, if it is required as a library, do nothing. if (require.main === module) { CodeCity.startup(); // SIGTERM and SIGINT shut down server. process.once('SIGTERM', CodeCity.shutdown.bind(null, 'SIGTERM')); process.once('SIGINT', CodeCity.shutdown.bind(null, 'SIGINT')); // SIGHUP forces checkpoint. process.on('SIGHUP', CodeCity.checkpoint.bind(null, false)); } /////////////////////////////////////////////////////////////////////////////// // Exports module.exports = CodeCity; ================================================ FILE: server/compile ================================================ #!/bin/bash # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Run the Closure Compiler, in --checks-only mode, on the Code City # server (and optionally server unit tests as well). # Compile tests, which also compile server: readonly ENTRY_POINT=tests/run.js # Aternatively, compile server alone: # readonly ENTRY_POINT=codecity.js # List of arguments to feed to compiler - flags and filenames. args=(-O=ADVANCED_OPTIMIZATIONS --checks-only --module_resolution=NODE --process_common_js_modules --assume_function_wrapper --dependency_mode=PRUNE --externs=externs/node.js --externs=externs/WeakRef.js --hide_warnings_for=node_modules/acorn node_modules/acorn/package.json node_modules/acorn/**.mjs iterable_weakmap.js iterable_weakset.js registry.js parser.js interpreter.js serialize.js code.js selector.js dumper.js codecity priorityqueue.js dump tests/*.js ) # Set current directory to the one containing this script. cd "$(dirname "${BASH_SOURCE[0]}")" # Temporarily symlink extern declarations for node builtins into # node_modules/, and add their .js and package.json files to args. declare -a builtins for path in externs/*; do if [[ -d "${path}" && -f "${path}/package.json" ]]; then builtins+=("$(basename "${path}")") fi done for builtin in "${builtins[@]}"; do link="node_modules/${builtin}" if [[ -e "${link}" ]]; then if [[ -L "${link}" ]]; then rm "${link}" # Remove old symlink. else echo "$0: aborting because ${link} already exists and is not a symlink" \ 1>&2 exit 1 fi fi ln -s "../externs/${builtin}" "${link}" args+=("${link}"/{*.js,package.json}) done google-closure-compiler "${args[@]}" --entry_point="${ENTRY_POINT}" return="$?" # Remove extern symlinks. for builtin in "${builtins[@]}"; do link="node_modules/${builtin}" if [[ ! -L "${link}" ]]; then echo "$0: aborting because ${link} is no longer a symlink" 1>&2 exit 1 fi rm "${link}" done exit ${return} ================================================ FILE: server/config.txt ================================================ Documentation for config file options: "databaseDirectory": string Relative path from this config file to the database directory. Defaults to "./" (current directory). "checkpointInterval": number Number of seconds between regular checkpoints. If 0, then no regular checkpoints. Defaults to 600 (10 minutes). TODO: Move this configuration option into the database. "checkpointAtShutdown": boolean If true, save a checkpoint when the server shuts down. If false, don't save a checkpoint, which results in lost data. Defaults to true. "checkpointMinFiles": number Minimum number of checkpoint files in a directory. While there are fewer than this number, then no checkpoints will be deleted. Defaults to 0. "checkpointMaxDirectorySize": number Maximum number of megabytes allowed for checkpoints in checkpoint directory. If this value is exceeded and checkpointMinFiles is also satisfied, then one or more old checkpoints will be deleted to make room for the next checkpoint. Defaults to Infinity. ================================================ FILE: server/dump ================================================ #!/usr/bin/env node /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Infrastructure to save the state of an Interpreter as * eval-able JS. Mainly a wrapper around Dumper, handling * the application of a dupmp configuration. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; var code = require('./code'); var CodeCity = require('./codecity'); var Do = require('./dumper').Do; var Dumper = require('./dumper').Dumper; var DumperOptions = require('./dumper').DumperOptions; var Writable = require('./dumper').Writable; var fs = require('fs'); var Interpreter = require('./interpreter'); var path = require('path'); var Selector = require('./selector'); /** * Dump an Interpreter using a given dump specification. * @param {!Interpreter} intrp1 An interpreter initialised exactly as * the one the ouptut JS will be executed by. * @param {!Interpreter} intrp2 An interpreter containing state * modifications (relative to intrp1) to be dumped. * @param {!Array} config The dump specification. * @param {string=} directory A directory relative to which * non-absolute filenames in config should be written. If none is * supplied then they will be treated as relative to the current * directory. * @param {boolean=} verbose Print message describing what is being done. */ var dump = function(intrp1, intrp2, config, directory, verbose) { var dumper = new Dumper(intrp1, intrp2, {verbose: verbose}); if (verbose) console.log('Dumper initialised.'); // Skip everything that's explicitly mentioned in the config, so // that paths won't get dumped until it's their turn. for (var item, i = 0; (item = config[i]); i++) { if (!item.contents) continue; for (var entry, j = 0; (entry = item.contents[j]); j++) { dumper.skip(entry.selector); } } var /** string */ header = ''; // Dump the specified paths, in order. for (var item, i = 0; (item = config[i]); i++) { if ('options' in item) { // An OptionsItem. dumper.setOptions(item.options); continue; } // A FileItem. var filename = item.filename; if (verbose) console.log('Dumping to %s...', filename); if (directory !== undefined && !path.isAbsolute(filename)) { filename = path.normalize(path.join(directory, filename)); } var outputStream = new SyncWriter(filename); dumper.setOptions({output: outputStream}); for (var selector, j = 0; (selector = item.prune[j]); j++) { dumper.prune(selector); } for (var selector, j = 0; (selector = item.pruneRest[j]); j++) { dumper.pruneRest(selector); } if (item.header !== undefined) header = item.header; var fileHeader = header; for (var key in item.headerSubs) { fileHeader = fileHeader.replace(key, item.headerSubs[key]); } if (fileHeader) dumper.write(fileHeader); if (item.contents) { for (var entry, j = 0; (entry = item.contents[j]); j++) { if (verbose) console.log('Dumping: %s', entry.selector); dumper.unskip(entry.selector); dumper.dumpBinding(entry.selector, entry.do); dumper.write('\n'); } } if (item.rest) { if (verbose) console.log('Dumping rest.'); dumper.dump(); } outputStream.end(); } }; /** * Convert a dump plan from an !Array to * !Array, with validataion and a few conversions: * * - Whereas as in the input, paths will will be represented by * selector strings, in the corresponding output the properties will * be Selectors. The SpecConfigEntry path: will become .selector in * the corresponding COnfigEntry. * * - Whereas the input will specify do: values as strings * (e.g. "RECURSE"), the output will have Do enum values * (e.g. Do.RECURSE) instead. * * - A plain selector string ss, appearing in the contents: array of a * SpecFileItem, will be replaced by the ContentEntry * {selector: new Selector(ss), do: Do.RECURSE, reorder: false}. * * - All optional boolean-valued properties will be normalised to * exist, defaulting to false. * * @param {*} spec The dump plan to be validated. If this is not an * !Array, TypeError will be thrown. * @return {!Array} */ var configFromSpec = function(spec) { var /** !Array */ config = []; /** @type {function(string, number=)} */ function reject(message, j) { var prefix = 'spec[' + i + ']'; if (j !== undefined) prefix = prefix + '.contents[' + j + ']'; if (message[0] !== '.') prefix = prefix + ' '; throw new TypeError(prefix + message); } if (!Array.isArray(spec)) { throw new TypeError('spec must be an array of SpecConfigItems'); } for (var i = 0; i < spec.length; i++) { var item = spec[i]; if (typeof item !== 'object' || item === null) { reject('not a SpecConfigItem object'); } if ('filename' in item) { // It's a SpecFileItem. var /** (string|undefined) */ header; var /** !Object */ headerSubs = {}; var /** !Array */ prune = []; var /** !Array */ pruneRest = []; var /** !Array */ contents = []; if (typeof item.filename !== 'string') { // TODO(cpcallen): add better filename validity check? reject('.filename is not a string'); } else if (!Array.isArray(item.contents) && item.contents !== undefined) { reject('.contents is not an array'); } else if (typeof item.rest !== 'boolean' && item.rest !== undefined) { reject('.rest is not a boolean'); } if (item.header instanceof Array) { header = item.header.join('\n'); } else if (typeof item.header === 'string' || item.header === undefined) { header = item.header; } else { reject('.header is not string or array of strings'); } if (item.headerSubs instanceof Object) { for (var key in item.headerSubs) { var value = item.headerSubs[key]; if (value instanceof Array) { headerSubs[key] = value.join('\n'); } else if (typeof value === 'string') { headerSubs[key] = value; } else { reject('.headerSubs.' + key + ' is not a string'); } } } else if (item.headerSubs !== undefined) { reject('.headerSubs is not an object'); } if ('prune' in item) { if (!Array.isArray(item.prune)) { reject('.prune is not an array'); } for (var j = 0; j < item.prune.length; j++) { prune.push(new Selector(item.prune[j])); } } if ('pruneRest' in item) { if (!Array.isArray(item.pruneRest)) { reject('.pruneRest is not an array'); } for (j = 0; j < item.pruneRest.length; j++) { pruneRest.push(new Selector(item.pruneRest[j])); } } if ('contents' in item) { for (j = 0; j < item.contents.length; j++) { var entry = item.contents[j]; if (typeof entry === 'string') { var selector = new Selector(entry); contents.push({selector: selector, do: Do.RECURSE, reorder: false}); continue; } else if (typeof entry !== 'object' || entry === null) { reject('not a SpecContentEntry object', j); } else if (typeof entry.path !== 'string') { reject('.path not a vaid selector string', j); } else if (!Do.hasOwnProperty(entry.do)) { reject('.do: ' + entry.do + ' is not a valid Do value', j); } else if (typeof entry.reorder !== 'boolean' && entry.reorder !== undefined) { reject('.reorder must be boolean or omitted', j); } contents.push({ selector: new Selector(entry.path), do: Do[entry.do], reorder: Boolean(entry.reorder), }); } } else if (!item.rest) { reject('must specify one of .contents or .rest'); } config.push({ filename: item.filename, header: header, headerSubs: headerSubs, prune: prune, pruneRest: pruneRest, contents: contents, // Possibly empty. rest: Boolean(item.rest), }); } else if ('options' in item) { // It's a SpecOptionsItem. if (typeof item.options !== 'object') { reject('.options is not a DumperOptions object'); // TODO(cpcallen): additional type checks? } config.push({options: item.options}); } else { reject('is neither a SpecFileItem nor a SpecOptionsItem'); } } return config; }; /** * A synchronous writable stream, with an API that is a simplified * subset of stream.Writable. * @constructor * @struct * @implements Writable * @param {string} filename The file to write to. */ var SyncWriter = function(filename) { /** @type {number|null} */ this.fd = fs.openSync(filename, 'w', 0o600); }; /** * Write string to file. * @override * @param {string} s String to write. * @returns {void} */ SyncWriter.prototype.write = function(s) { if (this.fd === null) throw Error('stream already ended'); fs.writeSync(this.fd, s); }; /** * Close file. * @returns {void} */ SyncWriter.prototype.end = function() { if (this.fd === null) throw Error('stream already ended'); fs.closeSync(this.fd); this.fd = null; }; /////////////////////////////////////////////////////////////////////////////// // Data types used to specify a dump configuration. /////////////////////////////////////////////////////////////////////////////// // For internal use; strict types: /** * A processed-and-ready-to-use configuration entry. * @typedef {!OptionsItem|!FileItem} */ var ConfigItem; /** * A processed-and-ready-to-use configuration entry setting general * options. * @typedef {{copyright: (string|!Array|undefined), * options: !DumperOptions}} */ var OptionsItem; /** * A processed-and-ready-to-use configuration entry for a single * output file. * @typedef {{filename: string, * header: (string|undefined), * headerSubs: !Object, * prune: !Array, * pruneRest: !Array, * contents: !Array, * rest: boolean}} */ var FileItem; /** * The type of the values of .contents entries of a ConfigEntry. * * - selector: is a Selector identifying the variable or property * binding this entry applies to. * * - do: is a Do value speciifying how much of selector to dump. * * - reorder: is a boolean specifying whether it is acceptable to * allow property or set/map entry entries to be created (by the * output JS) in a different order than they apear in the * interpreter instance being serialised. If false, output may * contain placeholder entries like: * * var obj = {}; * obj.foo = undefined; // placeholder * obj.bar = function() { ... }; * * to allow obj.foo to be defined later while still preserving * property order. * * @typedef {{selector: !Selector, * do: Do, * reorder: boolean}} */ var ContentEntry = function() {}; ////////////////////////////////////////////////////////////////////// // For dump_spec.json use; loose, JSON-compatible types: /** @typedef {!SpecOptionsItem|!SpecFileItem} */ var SpecConfigItem; /** * An OptionsItem, but with Selectors represented by selector strings. * * @typedef {{options: !DumperOptions}} */ var SpecOptionsItem; /** * A FileItem represented as plain old JavaScript object (i.e., as * ouptut by JSON.parse): * * - Do values are reprsesented by the coresponding strings (e.g., * "RECURSE" instead of Do.RECURSE). * - For convenience, header: and the values of headerSubs: may be an * arrays of strings, which will be joined with newlines. * - Contents entries can be just a selector string, which will be * treated as Do.RECURSE. * * @typedef {{filename: string, * header: (string|!Array|undefined), * headerSubs: (!Object|string)>|undefined), * prune: (!Array|undefined), * pruneRest: (!Array|undefined), * contents: (!Array|undefined), * rest: (boolean|undefined)}} */ var SpecFileItem; /** * Like a ContentEntry, but with a string instead of a Do value. * @typedef {{path: string, * do: string, * reorder: (boolean|undefined)}} */ var SpecContentEntry; /////////////////////////////////////////////////////////////////////////////// // Main program. /////////////////////////////////////////////////////////////////////////////// if (require.main === module) { if (process.argv.length < 4) { console.log( 'usage: dump <.city file> '); process.exit(1); } var cityFile = process.argv[2]; var planFile = process.argv[3]; var dir = process.argv[4]; var intrp = CodeCity.loadCheckpoint(cityFile); var specText = fs.readFileSync(planFile); const spec = JSON.parse(String(specText)); var config = configFromSpec(spec); dump(CodeCity.makeInterpreter(), intrp, config, dir, /*verbose:*/ true); }; /////////////////////////////////////////////////////////////////////////////// // Exports. /////////////////////////////////////////////////////////////////////////////// exports.configFromSpec = configFromSpec; exports.Do = Do; exports.dump = dump; ================================================ FILE: server/dumper.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview The Dumper class (and related helpers) to diff the * state of (parts or all of) two Interpreter objects, outputing * eval-able JS code to convert the one into the other. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; var code = require('./code'); var Interpreter = require('./interpreter'); var PriorityQueue = require('./priorityqueue').PriorityQueue; var Selector = require('./selector'); var util = require('util'); /////////////////////////////////////////////////////////////////////////////// // Dumper. /** * Dumper compares the state of two Interpreter instances, for the * purpose of generating eval-able JS that would update part or all(*) * of the first to the same state as the second. This can be used to * dump the state of an Interpreter by comparing it against a pristine * Interpreter instance, or to produce a software patch by comparing a * long-running Interpreter against a previous version of itself or * against the target to which the patch will be applied. * * (*) Limitations: since there is no way to construct arbitrary stack * frames by evaling JS source code, it is not at present possible to * dump the state of threads. This could be rectified in future by * providing host functions for creating/modifying the stack frames * associated with Thread objects. * * @constructor * @struct * @param {!Interpreter} intrp1 An interpreter initialised exactly as * the one the ouptut JS will be executed by. * @param {!Interpreter} intrp2 An interpreter containing state * modifications (relative to intrp1) to be dumped. * @param {!DumperOptions=} options Additional options. */ var Dumper = function(intrp1, intrp2, options) { this.intrp1 = intrp1; this.intrp2 = intrp2; // Copy DEFAULT_OPTIONS then apply supplied options. /** @type {!DumperOptions} */ this.options = {}; this.setOptions(DEFAULT_OPTIONS); if (options) this.setOptions(options); /** @const {!Map} */ this.scopeDumpers = new Map(); /** @const {!Map} */ this.objDumpers2 = new Map(); /** * Map of Arguments objects to the ScopeDumpers for the scopes to * which they belong. * @const {!Map} */ this.argumentsScopeDumpers = new Map(); /** * Which scope are we presently outputting code in the context of? * @type {!Interpreter.Scope} */ this.scope = intrp2.global; /** @type {!Interpreter.Owner} Perms at present point in output. */ this.perms = intrp2.ROOT; /** * Map from objects from intrp1 to corresponding objects in intrp2. * @type {!Map} */ this.objs1to2 = new Map(); /** * Current indentation. * @type {string} */ this.indent = ''; this.diffBuiltins_(); // Create and initialise ScopeDumper for global scope. /** @const !ScopeDumper */ this.global = this.getScopeDumper_(intrp2.global); for (var v in intrp1.global.vars) { var val1 = intrp1.global.get(v); var val2 = intrp2.global.get(v); var val1in2; if (val1 instanceof intrp1.Object) { if (!(val2 instanceof intrp2.Object)) { throw new TypeError('Primitive / object mistmatch'); } val1in2 = this.objs1to2.get(val1); } else { val1in2 = val1; } if (Object.is(val1in2, val2)) { this.global.setDone(v, (typeof val2 === 'object') ? Do.DONE : Do.RECURSE); if (val2 instanceof intrp2.Object) { this.getObjectDumper_(val2) .updateRef(this, new Components(this.global, v)); // Other initialialisation will be taken care of below. } } } // Survey objects accessible via global scope to find their outer scopes. this.survey_(); }; /** * Diff the values of buit-ins. * @private * @return {void} */ Dumper.prototype.diffBuiltins_ = function() { // Initialise intrpObjs. var builtins = this.intrp1.builtins.keys(); for (var i = 0; i < builtins.length; i++) { var builtin = builtins[i]; var obj1 = this.intrp1.builtins.get(builtin); var obj2 = this.intrp2.builtins.get(builtin); if (!(obj2 instanceof this.intrp2.Object)) { continue; // Skip primitive-valued builtins. } else if (obj1 === undefined) { throw new Error('Builtin not found in intrp1 Interpreter'); } else if (!(obj1 instanceof this.intrp1.Object)) { throw new Error("Builtin wasn't an object originally"); } // TODO(cpcallen): add check for inconsistent duplicate // registrations - e.g., if parseInt and Number.parseInt were // the same in intrp2 but different in intrp1. this.objs1to2.set(obj1, obj2); } // Create and initialise ObjectDumpers for builtin objects. for (var i = 0; i < builtins.length; i++) { builtin = builtins[i]; obj2 = this.intrp2.builtins.get(builtin); if (!(obj2 instanceof this.intrp2.Object)) continue; // Skip primitives. var objDumper = this.getObjectDumper_(obj2); obj1 = this.intrp1.builtins.get(builtin); // Record pre-set prototype. objDumper.proto = (obj1.proto === null) ? null : this.objs1to2.get(obj1.proto); if (obj2.proto === objDumper.proto) { objDumper.setDone(Selector.PROTOTYPE, (obj2.proto === null) ? Do.RECURSE : Do.DONE); } // Record pre-set owner. var owner = /** @type{?Interpreter.Owner} */( (obj1.owner === null) ? null : this.objs1to2.get( /** @type{?Interpreter.prototype.Object} */(obj1.owner))); if (obj2.owner === owner) { objDumper.setDone(Selector.OWNER, (obj2.owner === null) ? Do.RECURSE : Do.DONE); } // Record pre-set property values/attributes. var keys = obj1.ownKeys(this.intrp1.ROOT); for (var j = 0; j < keys.length; j++) { var key = keys[j]; var pd1 = obj1.getOwnPropertyDescriptor(key, this.intrp1.ROOT); var pd2 = obj2.getOwnPropertyDescriptor(key, this.intrp2.ROOT); var attrs = { writable: pd1.writable, enumerable: pd1.enumerable, configurable: pd1.configurable }; objDumper.attributes[key] = attrs; var value = pd1.value instanceof this.intrp2.Object ? this.objs1to2.get(pd1.value) : pd1.value; objDumper.checkProperty(key, value, attrs, pd2); } } }; /** * Dump everything that has not already been dumped so far. The * generated source text is written to the current output buffer. * Notably, this will also dump any listening sockets. * @return {void} */ Dumper.prototype.dump = function() { // Dump all remaining bindings. this.global.dump(this); // Dump listening Servers. for (var key in this.intrp2.listeners_) { var port = Number(key); var server = this.intrp2.listeners_[port]; var args = [port, server.proto]; if (server.timeLimit) args.push(server.timeLimit); this.write(this.exprForCall_('CC.connectionListen', args), ';'); } }; /** * Generate JS source text to declare and optionally initialise a * particular binding (as specified by a Selector). The generated * source text is written to the current output buffer. * * E.g., if foo = [42, 69, 105], then: * * myDumper.dumpBinding(new Selector('foo'), Do.DECL) * // Writes: 'var foo;\n' * myDumper.dumpBinding(new Selector('foo'), Do.SET) * // Writes: 'foo = [];\n' * myDumper.dumpBinding(new Selector('foo[0]'), Do.SET) * // Writes: 'foo[0] = 42;\n' * myDumper.dumpBinding(new Selector('foo'), Do.RECURSE) * // Writs: 'foo[1] = 69;\nfoo[2] = 105;\n' * * This is mainly a wrapper around Object/ScopeDumper.p.dumpBinding * and ObjectDumper.p.dump. * * @param {!Selector} selector The selector for the binding to be dumped. * @param {!Do} todo How much to dump. Must be >= Do.DECL. * @return {void} */ Dumper.prototype.dumpBinding = function(selector, todo) { var c = this.getComponentsForSelector_(selector); var done = c.dumper.dumpBinding(this, c.part, todo); if (todo >= Do.RECURSE && done < Do.RECURSE) { var value = c.dumper.getValue(this, c.part); if (value instanceof this.intrp2.Object) { var objDone = this.getObjectDumper_(value).dump(this, selector); if (objDone === ObjectDumper.Done.DONE_RECURSIVELY) { if (c.dumper.getDone(c.part) < Do.RECURSE) { c.dumper.setDone(c.part, Do.RECURSE); } } } } }; /** * Get a source text representation of a given value. The source text * will vary depending on the state of the dump; for instance, if the * value is an object that has not yet apepared in the dump it will be * represented by an expression creating the object - but if it has * appeared before, then it will instead be represented by an * expression referenceing the previously-constructed object. * * This method is mostly a wrapper around the other .exprFor_ * methods (but notably not .exprForBuiltin_ and .exprForCall_, which * are wrappers around this method); see them for examples of expected * output. * * @private * @param {Interpreter.Value} value Arbitrary JS value from this.intrp2. * @param {!Components=} ref Location in which value will be stored. * @param {boolean=} callable Return the expression suitably * parenthesised to be used as the callee of a CallExpression. * @param {string=} funcName If supplied, and if value is an anonymous * UserFuncion, then the returned expression is presumed to appear * on the right hand side of an assignment statement such that the * resulting Function object has its .name property automatically * set to this value. * @return {string} An eval-able representation of the value. */ Dumper.prototype.exprFor_ = function(value, ref, callable, funcName) { var intrp2 = this.intrp2; if (!(value instanceof intrp2.Object)) { return this.exprForPrimitive_(value); } // Return existing reference to object (if already created). var objDumper = this.getObjectDumper_(value); var selector; // Existing selector for value, if any. if (objDumper.proto !== undefined && objDumper.ref) { selector = objDumper.getSelector(); } if (ref) objDumper.updateRef(this, ref); // Safe new ref if specified. if (selector) return this.exprForSelector_(selector); // Object not yet referenced. Is it a builtin? var key = intrp2.builtins.getKey(value); if (key) { var quoted = code.quote(key); return callable ? '(new ' + quoted + ')' : 'new ' + quoted; } // Seems to be a new object. Check it really doesn't exist already // and that it will be referenceable. if (objDumper.proto !== undefined) { throw new Error('object already exists but is not referenced'); } else if (!objDumper.ref) { throw new Error('refusing to create non-referable object'); } var expr; if (value instanceof intrp2.Function) { expr = this.exprForFunction_(value, objDumper, funcName); } else if (value instanceof intrp2.Array) { expr = this.exprForArray_(value, objDumper); } else if (value instanceof intrp2.Date) { expr = this.exprForDate_(value, objDumper); } else if (value instanceof intrp2.RegExp) { expr = this.exprForRegExp_(value, objDumper); } else if (value instanceof intrp2.Error) { expr = this.exprForError_(value, objDumper); } else if (value instanceof intrp2.WeakMap) { expr = this.exprForWeakMap_(value, objDumper); } else { expr = this.exprForObject_(value, objDumper); } // Do we need to set [[Prototype]]? Not if it's already correct. if (value.proto === objDumper.proto) { objDumper.setDone(Selector.PROTOTYPE, (value.proto === null) ? Do.RECURSE : Do.DONE); } // Do we need to set [[Owner]]? Not if it's already correct. if (value.owner === this.perms) { objDumper.setDone(Selector.OWNER, (value.owner === null) ? Do.RECURSE : Do.DONE); } return expr; }; /** * Get a source text representation of a given Array object. For the * moment the return value is always '[]', but the specified arrDumper * is modified to reflect what further work will need to be done to * finsh dumping the array object. * TODO(cpcallen): Return a more interesting array literal when possible. * @private * @param {!Interpreter.prototype.Array} arr Array object to be recreated. * @param {!ObjectDumper} arrDumper ObjectDumper for arr. * @return {string} An eval-able representation of arr. */ Dumper.prototype.exprForArray_ = function(arr, arrDumper) { arrDumper.proto = this.intrp2.ARRAY; var root = this.intrp2.ROOT; var lastIndex = arr.get('length', root) - 1; arrDumper.attributes['length'] = {writable: true, enumerable: false, configurable: false}; if (lastIndex < 0 || arr.getOwnPropertyDescriptor(String(lastIndex), root)) { // No need to set .length if it will be set via setting final index. arrDumper.setDone('length', Do.RECURSE); } else { // Length exists; don't worry about it when preserving propery order. arrDumper.setDone('length', Do.DECL); } return '[]'; }; /** * Get a source text representation of a given builtin, for the * purposes of calling it. Usually the return value will be a string * like 'Object.defineProperty', but if the builtin in question hasn't * yet been assigned to an object it will instead return a string like * "(new 'Object.defineProperty')" to invoke the new hack to obtain * it. This is a trivial wrapper around exprFor_ for a common use * case. * @private * @param {string} builtin The name of the builtin. * @return {string} An eval-able representation of obj. */ Dumper.prototype.exprForBuiltin_ = function(builtin) { return this.exprFor_(this.intrp2.builtins.get(builtin), undefined, true); }; /** * Get a source text representation of a call to a given builtin * function. The array of arguments can contain either * Interpreter.Values or Selectors, which will be passed to .exprFor_ * and .exprForSelector_, respectively. * @private * @param {string} builtin The name of the builtin function to call. * @param {!Array=} args Arguments to the call. * @return {string} An eval-able representation of a builtin function call. */ Dumper.prototype.exprForCall_ = function(builtin, args) { var dumper = this; return this.exprForBuiltin_(builtin) + '(' + Array.from(args || []).map(function (argument) { if (argument instanceof Selector) { return dumper.exprForSelector_(argument); } else { return dumper.exprFor_(argument); } }).join(', ') + ')'; }; /** * Get a source text representation of a given Date object. The * return value will usually be a string of the form "new * Date('1975-07-27T23:59:59.000Z')" (but the new hack will be invoked * if the Data constructor has not yet been initialised). * @private * @param {!Interpreter.prototype.Date} date Date object to be recreated. * @param {!ObjectDumper} dateDumper ObjectDumper for date. * @return {string} An eval-able representation of date. */ Dumper.prototype.exprForDate_ = function(date, dateDumper) { dateDumper.proto = this.intrp2.DATE; return 'new ' + this.exprForCall_('Date', [date.date.toISOString()]); }; /** * Get a source text representation of a given Error object. The * return value will usually be a string of the form "new * RangeError()" or "new TypeError('message')" (but the new hack will * be invoked if the Data constructor has not yet been initialised). * Only the built-in Error constructors will be used; for custom error * stub-types errDumper will be left in a state that will ensure that * {proto} is subsequently set appropriately. * @private * @param {!Interpreter.prototype.Error} err Error object to be recreated. * @param {!ObjectDumper} errDumper ObjectDumper for err. * @return {string} An eval-able representation of err. */ Dumper.prototype.exprForError_ = function(err, errDumper) { errDumper.proto = err.proto; var constructor; if (err.proto === this.intrp2.EVAL_ERROR) { constructor = 'EvalError'; } else if (err.proto === this.intrp2.RANGE_ERROR) { constructor = 'RangeError'; } else if (err.proto === this.intrp2.REFERENCE_ERROR) { constructor = 'ReferenceError'; } else if (err.proto === this.intrp2.SYNTAX_ERROR) { constructor = 'SyntaxError'; } else if (err.proto === this.intrp2.TYPE_ERROR) { constructor = 'TypeError'; } else if (err.proto === this.intrp2.URI_ERROR) { constructor = 'URIError'; } else if (err.proto === this.intrp2.PERM_ERROR) { constructor = 'PermissionError'; } else { constructor = 'Error'; errDumper.proto = this.intrp2.ERROR; } // Try to set .message in the constructor call. var message = err.getOwnPropertyDescriptor('message', this.intrp2.ROOT); var args = []; if (message && typeof message.value === 'string') { args.push(message.value); var attr = errDumper.attributes['message'] = {writable: true, enumerable: false, configurable: true}; errDumper.checkProperty('message', message.value, attr , message); } // The .stack property is always created, and we always want to // overwrite (or delete) it. errDumper.attributes['stack'] = {writable: true, enumerable: false, configurable: true}; var stack = err.getOwnPropertyDescriptor('stack', this.intrp2.ROOT); if (stack) { errDumper.setDone('stack', Do.DECL); } else { errDumper.scheduleDeletion('stack'); } return 'new ' + this.exprForCall_(constructor, args); }; /** * Get a source text representation of a given Function object. The * returned string is just this.obj.toString(), which will be a string * of the form "function name(arg0, arg1, ...) { body; }", formatted * with whitespace and line breaks as it was in the original source. * Most of this method is therefore devoted to ensuring that * funcDumper is modified to reflect what further work will need to be * done to finsh dumping the function object. * TODO(cpcallen): Dump FunctionDeclarations as such, rather than * converting them into FunctionExpressions. * @private * @param {!Interpreter.prototype.Function} func Function object to be * recreated. * @param {!ObjectDumper} funcDumper ObjectDumper for func. * @param {string=} funcName If supplied, and if value is an anonymous * UserFunction, then the returned expression is presumed to appear * on the right hand side of an assignment statement such that the * resulting Function object has its .name property automatically * set to this value if a name does not appear in the function body. * @return {string} An eval-able representation of func. */ Dumper.prototype.exprForFunction_ = function(func, funcDumper, funcName) { if (!(func instanceof this.intrp2.UserFunction)) { throw Error('Unable to dump non-UserFunction'); } // TODO(cpcallen): Should throw, rather than merely warn. for (var scope = func.scope; scope !== this.scope; scope = scope.outerScope) { var vars = Object.getOwnPropertyNames(scope.vars); if (scope.type === Interpreter.Scope.Type.FUNEXP && scope === func.scope || vars.length === 0) { continue; } this.warn(util.format('CLOSURE: type: %s, vars: %s', scope.type, vars.join(', '))); } // Record stuff that gets done automatically by evaluating a // function expression, like setting its __proto__ and .prototype. funcDumper.proto = this.intrp2.FUNCTION; // TODO(ES6): generators, etc.? // The .length property will be set implicitly (and is immutable). funcDumper.attributes['length'] = {writable: false, enumerable: false, configurable: false}; funcDumper.setDone('length', Do.RECURSE); // The .name property is often set automatically. // TODO(ES6): Handle prefix? if (func.node['id']) { funcName = func.node['id']['name']; } if (funcName) { var attr = funcDumper.attributes['name'] = {writable: false, enumerable: false, configurable: true}; var pd = func.getOwnPropertyDescriptor('name', this.intrp2.ROOT); if (pd) { funcDumper.checkProperty('name', funcName, attr, pd); } else { funcDumper.scheduleDeletion('name'); } } // The .prototype property will automatically be created, so we // don't need to "declare" it. (Fortunately it's non-configurable, // so we don't need to worry that it might need to be deleted.) funcDumper.setDone('prototype', Do.DECL); // Better still, we might be able to use the automatically-created // .prototype object - if the current value is an ordinary Object // and it isn't a built-in or already instantiated. (N.B.: we don't // care about its {proto}; that can be modified later.) attr = funcDumper.attributes['prototype'] = {writable: true, enumerable: false, configurable: false}; pd = func.getOwnPropertyDescriptor('prototype', this.intrp2.ROOT); var prototype = pd.value; if (!this.intrp2.builtins.getKey(prototype) && prototype instanceof this.intrp2.Object && Object.getPrototypeOf(prototype) === this.intrp2.Object.prototype) { var prototypeFuncDumper = this.getObjectDumper_(prototype); if (prototypeFuncDumper.proto === undefined) { // We can use automatic .prototype object. // Mark .prototype as Do.SET or Do.ATTR as appropriate. funcDumper.checkProperty('prototype', prototype, attr, pd); // Mark prototype object as existing and referenceable. prototypeFuncDumper.proto = this.intrp2.OBJECT; prototypeFuncDumper .updateRef(this, new Components(funcDumper, 'prototype')); // Do we need to set .prototype's [[Prototype]]? if (prototype.proto === prototypeFuncDumper.proto) { prototypeFuncDumper.setDone(Selector.PROTOTYPE, (prototype.proto === null) ? Do.RECURSE : Do.DONE); } // Do we need to set .prototype's [[Owner]]? if (prototype.owner === this.perms) { prototypeFuncDumper.setDone(Selector.OWNER, (prototype.owner === null) ? Do.RECURSE : Do.DONE); } // It gets a .constructor property. Check to see if it will // need to be overwritten. attr = prototypeFuncDumper.attributes['constructor'] = {writable: true, enumerable: false, configurable: true}; pd = prototype.getOwnPropertyDescriptor('constructor', this.intrp2.ROOT); prototypeFuncDumper.checkProperty('constructor', func, attr, pd); } } return func.toString(); }; /** * Get a source text representation of a given Object. For now the * return value will always be either the string '{}' or one of the * form 'Object.create(prototype)' (and/or invoking the new hack if * required). * TODO(cpcallen): return a more interesting object literal when possible. * @private * @param {!Interpreter.prototype.Object} obj Object to be recreated. * @param {!ObjectDumper} objDumper ObjectDumper for obj. * @return {string} An eval-able representation of obj. */ Dumper.prototype.exprForObject_ = function(obj, objDumper) { switch (obj.proto) { case null: objDumper.proto = null; return this.exprForCall_('Object.create', [null]); case this.intrp2.OBJECT: objDumper.proto = this.intrp2.OBJECT; return '{}'; default: if (this.getObjectDumper_(obj.proto).proto !== undefined) { // Record prototype connection. objDumper.proto = obj.proto; this.getObjectDumper_(obj.proto) .updateRef(this, new Components(objDumper, Selector.PROTOTYPE)); return this.exprForCall_('Object.create', [obj.proto]); } else { // Can't set [[Prototype]] yet. Do it later. objDumper.proto = this.intrp2.OBJECT; return '{}'; } } }; /** * Get a source text representation of a given primitive value (not * including symbols). Correctly handles having Infinity, NaN and/or * undefiend shadowed by binding in the current scope. In general * this is just the obvious literal, but note: * * - Strings will be single- or double-quoted depending on which is * more concise. * - If Infinity, NaN or undefined is shadowed an alternative * expression evaluating to the desired value will be returned * instead. (N.B.: true, false and null are literals so cannot be * shadowed.) * @private * @param {undefined|null|boolean|number|string} value Primitive JS value. * @return {string} An eval-able representation of the value. */ Dumper.prototype.exprForPrimitive_ = function(value) { switch (typeof value) { case 'undefined': if (this.isShadowed_('undefined')) return '(void 0)'; // FALL THROUGH case 'boolean': return String(value); case 'number': // All finite values (except -0) will convert back to exactly // equal number, but Infinity and NaN could be shadowed. See // https://stackoverflow.com/a/51218373/4969945 if (Object.is(value, -0)) { return '-0'; } else if (Number.isFinite(value)) { return String(value); } else if (Number.isNaN(value)) { if (this.isShadowed_('NaN')) { return '(0/0)'; } return 'NaN'; } else { // value is Infinity or -Infinity. if (this.isShadowed_('Infinity')) { return (value > 0) ? '(1/0)' : '(-1/0)'; } return String(value); } case 'string': return code.quote(value); default: if (value === null) { return 'null'; } else { throw TypeError('exprForPrimitive_ called on non-primitive value'); } } }; /** * Get a source text representation of a given RegExp object. The * returned value will be a string containing a regexp literal, like * '/foobar/gi'. * @private * @param {!Interpreter.prototype.RegExp} re RegExp to be recreated. * @param {!ObjectDumper} reDumper ObjectDumper for re. * @return {string} An eval-able representation of re. */ Dumper.prototype.exprForRegExp_ = function(re, reDumper) { reDumper.proto = this.intrp2.REGEXP; // Some properties are implicitly pre-set. var props = ['source', 'global', 'ignoreCase', 'multiline']; for (var prop, i = 0; (prop = props[i]); i++) { reDumper.attributes[prop] = {writable: false, enumerable: false, configurable: false}; reDumper.setDone(prop, Do.RECURSE); } reDumper.attributes['lastIndex'] = {writable: true, enumerable: false, configurable: false}; if (Object.is(re.get('lastIndex', this.intrp2.ROOT), 0)) { // Can skip setting .lastIndex iff it is 0. reDumper.setDone('lastIndex', Do.RECURSE); } else { reDumper.setDone('lastIndex', Do.DECL); } return re.regexp.toString(); }; /** * Get a source text representation of a given selector. In general, * given Selector s and Dumper d, d.exprForSelector_(s) will be the * same as s.toExpr() except when the output needs to call a builtin * function like Object.getPrototypeOf that is not available via its * usual name - e.g. if Object.getPrototypeOf has not yet been dumped * then the selector foo.bar{proto} might be represented as "(new * 'Object.getPrototypeOf')(foo.bar)" instead of * "Object.getPrototypeOf(foo.bar)". * @private * @param {Selector=} selector Selector to obtain value of. * @return {string} An eval-able representation of the value. */ Dumper.prototype.exprForSelector_ = function(selector) { var dumper = this; return selector.toString(function(part, out) { if (part === Selector.PROTOTYPE) { out.unshift(dumper.exprForBuiltin_('Object.getPrototypeOf'), '('); out.push(')'); } else if (part === Selector.OWNER) { out.unshift(dumper.exprForBuiltin_('Object.getOwnerOf'), '('); out.push(')'); } else { throw new TypeError('Invalid part in parts array'); } }); }; /** * Get a source text representation of a given WeakMap object. The * return value will usually be the string "new WeakMap()" (but the * new hack will be invoked if the WeakMap constructor has not yet * been initialised). * @private * @param {!Interpreter.prototype.WeakMap} weakMap WeakMap object to * be recreated. * @param {!ObjectDumper} weakMapDumper ObjectDumper for weakmap. * @return {string} An eval-able representation of weakmap. */ Dumper.prototype.exprForWeakMap_ = function(weakMap, weakMapDumper) { weakMapDumper.proto = this.intrp2.WEAKMAP; return 'new ' + this.exprForCall_('WeakMap'); }; /** * Given a Selector and optionally a Scope, get the corresponding * Components. * @private * @param {!Selector} selector A selector for the binding in question. * @param {!Interpreter.Scope=} scope Scope which selector is relative to. * Defaults to current scope. * @return {!Components} The dumper and part corresponding to selector. */ Dumper.prototype.getComponentsForSelector_ = function(selector, scope) { if (!scope) scope = this.scope; if (selector.length < 1) throw new RangeError('Zero-length selector??'); var /** !SubDumper */ dumper = this.getScopeDumper_(scope); var /** Interpreter.Value */ v; for (var i = 0; i < selector.length - 1; i++) { v = dumper.getValue(this, selector[i]); if (!(v instanceof this.intrp2.Object)) { var s = new Selector(selector.slice(0, i + 1)); throw TypeError("Can't select part of primitive " + s + ' === ' + v); } dumper = this.getObjectDumper_(v); } return new Components(dumper, selector[selector.length - 1]); }; /** * Given a Selector or selector string and optionally a Scope, get the * SubDumper for the value object identified. This is intended to be * used only for testing. * @param {!Selector|string} selector A Selector or selector string * referring to an object. * @param {!Interpreter.Scope=} scope Scope which ss is relative to. * Defaults to current scope. * @return {!ObjectDumper} The ObjectDumper for the referred-to object. */ Dumper.prototype.getDumperFor = function(selector, scope) { if (typeof selector === 'string') selector = new Selector(selector); if (!scope) scope = this.scope; var /** !SubDumper */ dumper = this.getScopeDumper_(scope); var /** Interpreter.Value */ v; for (var i = 0; i < selector.length; i++) { v = dumper.getValue(this, selector[i]); if (!(v instanceof this.intrp2.Object)) { var s = new Selector(selector.slice(0, i + 1)); throw TypeError("Can't select part of primitive " + s + ' === ' + v); } dumper = this.getObjectDumper_(v); } if (!(dumper instanceof ObjectDumper)) throw new TypeError('corrupt state'); return dumper; }; /** * Get interned ObjectDumper for sope. * @private * @param {!Interpreter.prototype.Object} obj The object to get the dumper for. * @return {!ObjectDumper} The ObjectDumper for obj. */ Dumper.prototype.getObjectDumper_ = function(obj) { if (this.objDumpers2.has(obj)) return this.objDumpers2.get(obj); var objDumper = new ObjectDumper(obj); this.objDumpers2.set(obj, objDumper); return objDumper; }; /** * Get interned ScopeDumper for sope. * @private * @param {!Interpreter.Scope} scope The scope to get info for. * @return {!ScopeDumper} The ScopeDumper for scope. */ Dumper.prototype.getScopeDumper_ = function(scope) { if (this.scopeDumpers.has(scope)) return this.scopeDumpers.get(scope); var scopeDumper = new ScopeDumper(scope); this.scopeDumpers.set(scope, scopeDumper); return scopeDumper; }; /** * Returns true if a given name is shadowed in the current scope. * TODO(cpcallen): Use .reachable on the global Scope's ScopeDumper. * @private * @param {string} name Variable name that might be shadowed. * @param {!Interpreter.Scope=} scope Scope in which name is defined. * Defaults to the global scope. * @return {boolean} True iff name is bound in a scope between the * current scope (this.scope) (inclusive) and scope (exclusive). */ Dumper.prototype.isShadowed_ = function(name, scope) { if (!scope) scope = this.intrp2.global; for (var s = this.scope; s !== scope; s = s.outerScope) { if (s === null) { throw Error("Looking for name '" + name + "' from non-enclosing scope??"); } if (s.hasBinding(name)) return true; } return false; }; /** * Mark a particular binding (as specified by a Selector) with a * certain done value. * @private * @param {!Selector} selector The selector for the binding to be deferred. * @param {!Do} done Do status to mark binding with. */ Dumper.prototype.markBinding_ = function(selector, done) { var c = this.getComponentsForSelector_(selector); var was = c.dumper.getDone(c.part); if (was !== done) c.dumper.setDone(c.part, done); }; /** * Mark a particular binding (as specified by a Selector) to pruned, * which will have the effect of trying to ensure it does not exist in * the state reconstructed by the dump output. * TODO(cpcallen): actually delete pruned properties if necessary. * @param {!Selector} selector The selector for the binding to be pruned. */ Dumper.prototype.prune = function(selector) { var c = this.getComponentsForSelector_(selector); c.dumper.prune(c.part); }; /** * Set the .prune flag on the ObjectDumper for the object identified * by the given Selector to true. * TODO(cpcallen): actually delete pruned properties if necessary. * @param {!Selector} selector The selector for the binding to be pruned. */ Dumper.prototype.pruneRest = function(selector) { selector = new Selector(selector.concat([''])); // N.B. ugly hack! var c = this.getComponentsForSelector_(selector); if (!(c.dumper instanceof ObjectDumper)) throw new TypeError(); c.dumper.pruneRest = true; }; /** * Set options for this dumper. Can be called to change options * between calls to .dumpbBinding. Will update existing settings with * new values, so only changed options need to be supplied. * @param {!DumperOptions} options The new options to apply. * @return {void} */ Dumper.prototype.setOptions = function(options) { for (var key in DEFAULT_OPTIONS) { if (key in options) this.options[key] = options[key]; } }; /** * Mark a particular binding (as specified by a Selector) to be * skipped, which will have the effect of preventing any further * dumping of it until it is unskipped. * @param {!Selector} selector The selector for the binding to be skipped. */ Dumper.prototype.skip = function(selector) { var c = this.getComponentsForSelector_(selector); c.dumper.skip(c.part); }; /** * Survey the global Scope and recursively everything accessible via * its bindings, to prepare for dumping. * * This is done useing Dijkstra's Algorithm to create a least-cost * spanning tree starting from the global scope, with distance * measured by Selector badness. * * @private * @return {void} */ Dumper.prototype.survey_ = function() { var /** !Set */ visited = new Set(); var /** !PriorityQueue */ queue = new PriorityQueue(); // TODO(cpcallen): Remove badness; this info is already stored in queue. var /** !Map */ badness = new Map(); // Start building spanning tree from the global scope. var globalScopeDumper = this.getScopeDumper_(this.intrp2.global); var /* @const */ globalBadness = 0; badness.set(globalScopeDumper, globalBadness); queue.insert(globalScopeDumper, globalBadness); while (queue.length) { var /** !SubDumper */ dumper = queue.deleteMin(); if (visited.has(dumper)) throw new Error('surveying same dumper twice??'); visited.add(dumper); var baseBadness = badness.get(dumper); badness.delete(dumper); var /** !Array */ adjacent = dumper.survey(this); for (var j = 0; j < adjacent.length; j++) { var edge = adjacent[j]; if (edge instanceof ScopeDumper) { if (visited.has(edge)) continue; badness.set(edge, Infinity); queue.set(edge, Infinity); } if (!(edge.value instanceof this.intrp2.Object)) continue; var objectDumper = this.getObjectDumper_(edge.value); if (visited.has(objectDumper)) continue; var newBadness = baseBadness + Selector.partBadness(edge.part); // If we've not seen objectDumper before, .get will return // undefined and the following test will return false. // (Undefined is effectivly a 'bigger infinity' here!) if (newBadness >= badness.get(objectDumper)) continue; objectDumper.preferredRef = new Components(dumper, edge.part); badness.set(objectDumper, newBadness); queue.set(objectDumper, newBadness); } } }; /** * Mark a particular binding (as specified by a Selector) as no longer * to be skipped. * @param {!Selector} selector The selector for the binding to be skipped. */ Dumper.prototype.unskip = function(selector) { var c = this.getComponentsForSelector_(selector); c.dumper.unskip(c.part); }; /** * Log a warning about something suspicious that happened while * dumping. By default this prints to the console and .write()s a * comment to the file being output, but it can be overridden on * individual instances. * @param {string} warning Warning to output or log. */ Dumper.prototype.warn = function(warning) { if (this.options.verbose) console.log(warning); warning = warning.replace(/^(?!$)/gm, this.indent + '// ') .slice(this.indent.length); // Remove indent from first line. this.write(warning); }; /** * Write strings to current output file. (May be buffered.) The * arguments will be concatenated into a single string, which will be * pefixed with the current indentation and have a trailing newline * added if necessary. No indentation will be added to the second and * subsequent lines of a multi-line write, however, to preserve * indentation in function bodies / multi-line string literals / etc. * @param {...string} var_args Strings to output. */ Dumper.prototype.write = function(var_args) { if (this.options.output) { var line = this.indent + Array.prototype.join.call(arguments, ''); if (!line.endsWith('\n')) line += '\n'; this.options.output.write(line); } }; /////////////////////////////////////////////////////////////////////////////// // SubDumper /** * Common interface and functionality for ScopeDumper and ObjectDumper. * @abstract @constructor * @struct */ var SubDumper = function() { /** @type {?Set} */ this.skip_ = null; /** @type {?Set} */ this.prune_ = null; }; /** * Generate JS source text to create and/or initialize a single * binding (varialbe in a scope, or property / internal slot of an * object). * @abstract * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs. * @param {Selector.Part} part The part to dump. Must be simple string. * @param {!Do} todo How much to do. Must be >= Do.DECL; > Do.SET ignored. * @return {!Do} How much has been done on the specified binding. */ SubDumper.prototype.dumpBinding = function(dumper, part, todo) {}; /** * Return the current 'done' status of a binding. * @abstract * @param {Selector.Part} part The part to get status for. * @return {!Do} The done status of the binding. */ SubDumper.prototype.getDone = function(part) {}; /** * Return the value of the given part in intrp2 (i.e., the intended * final value, provided that it isn't going to be pruned.) * @abstract * @param {!Dumper} dumper Dumper to which this SubDumper belongs. * @param {Selector.Part} part The binding part to get the value of. * @return {Interpreter.Value} The value of that part. */ SubDumper.prototype.getValue = function(dumper, part) {}; /** * Update the current 'done' status of a binding. Will throw a * RangeError if caller attempts to un-do or re-do a previously-done * action. * @param {Selector.Part} part The part to set status for. * @param {!Do} done The new done status of the binding. */ SubDumper.prototype.setDone = function(part, done) {}; /** * Mark a particular binding (as specified by a Part) to be pruned, * which will have the effect of trying to ensure it does not exist in * the state reconstructed by the dump output. * TODO(cpcallen): actually delete pruned properties if necessary. * @param {Selector.Part} part The binding to be pruned. */ SubDumper.prototype.prune = function(part) { if (!this.prune_) this.prune_ = new Set(); this.prune_.add(part); }; /** * Return true the specified part is presently reachable - i.e., could * be set or read by an expression in the currently-dumped scope. * @abstract * @param {!Dumper} dumper Dumper to which this SubDumper belongs. * @param {Selector.Part=} part The binding whose reachability is of * interest. Ignored, since all object bindings are always * reachable if the object is. * @return {boolean} */ SubDumper.prototype.reachable = function(dumper, part) {}; /** * Mark a particular binding (as specified by a Part) to be skipped, * which will have the effect of preventing any further dumping of it * until it is unskipped. * @param {Selector.Part} part The binding to be skipped. */ SubDumper.prototype.skip = function(part) { if (!this.skip_) this.skip_ = new Set(); this.skip_.add(part); }; /** * Survey the scope or object associated with this SubDumper in * preparation for dumping. * * Returns a list of OutwardEdges representing outward edges * from this node of the object graph.: the properties (and internal * slots) of this object. Exceptionally, because Scopes are not * Interpreter Objects (and there is no Selector.Part corresponding to * the enclosing scope slot of a UserFunction object), the * ObjectDumper for a UserFunction will also include a bare * ScopeDumper in its returned array. * * @abstract * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs. * @return {!Array} */ SubDumper.prototype.survey = function(dumper) {}; /** * Mark a particular binding (as specified by a Selector) as no longer * to be skipped. * @param {Selector.Part} part The binding to be unskipped. */ SubDumper.prototype.unskip = function(part) { if (!this.skip_) return; this.skip_.delete(part); if (this.skip_.size === 0) this.skip_ = null; }; /////////////////////////////////////////////////////////////////////////////// // ScopeDumper /** * ScopeDumper encapsulates all machinery to dump an Interpreter.Scope * to eval-able JS, including maintaining all the dump-state info * required to keep track of what variable bindings have and haven't * yet been dumped. * @constructor @extends {SubDumper} * @struct * @param {!Interpreter.Scope} scope The scope to keep state for. */ var ScopeDumper = function(scope) { SubDumper.call(this); this.scope = scope; /** @private @const {!Object} Done status of each variable. */ this.doneVar_ = Object.create(null); /** @const {!Set} Set of inner scopes. */ this.innerScopes = new Set(); /** @const {!Set} Set of inner functions. */ this.innerFunctions = new Set(); }; Object.setPrototypeOf(ScopeDumper, SubDumper); Object.setPrototypeOf(ScopeDumper.prototype, SubDumper.prototype); /** * Generate JS source text to create and/or initialize a single * variable binding. * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs. * @return {void} */ ScopeDumper.prototype.dump = function(dumper) { if (dumper.scope !== this.scope) { throw new Error("Can't dump scope other than current scope"); } // Dump variable bindings. for (var name in this.scope.vars) { if (this.getDone(name) >= Do.RECURSE) continue; // Skip already-done. // Dump binding itself. var done = this.dumpBinding(dumper, name, Do.RECURSE); // Attempt to recursively dump the value object, if there is one. if (done >= Do.RECURSE) continue; var value = this.getValue(dumper, name); if (!(value instanceof dumper.intrp2.Object)) continue; var valueDumper = dumper.getObjectDumper_(value); var objDone = valueDumper.dump(dumper, new Selector(name)); if (objDone === ObjectDumper.Done.DONE_RECURSIVELY) { this.setDone(name, Do.RECURSE); } } }; /** * Generate JS source text to create and/or initialize a single * variable binding. * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs. * @param {Selector.Part} part The part to dump. Must be simple string. * @param {!Do} todo How much to do. Must be >= Do.DECL; > Do.SET ignored. * @return {!Do} How much has been done on the specified binding. */ ScopeDumper.prototype.dumpBinding = function(dumper, part, todo) { if (dumper.scope !== this.scope) { throw new Error("Can't create binding other than in current scope"); } else if (typeof part !== 'string') { throw new TypeError('Invalid part (not a variable name)'); } else if (!this.scope.hasBinding(part)) { throw new ReferenceError("Can't dump non-existent variable " + part); } else if (this.prune_ && this.prune_.has(part)) { return Do.RECURSE; // Don't dump this binding at all. } else if (this.skip_ && this.skip_.has(part)) { return this.getDone(part); // Do nothing but don't lie about it. } var done = this.getDone(part); var output = []; if (todo < Do.DECL || done >= todo || done > Do.SET) return done; if (done < Do.DECL) { output.push('var '); done = Do.DECL; } if (done < Do.SET) { output.push(part); if (todo >= Do.SET) { var ref = new Components(this, part); var value = this.scope.get(part); output.push(' = ', dumper.exprFor_(value, ref, false, part)); done = (value instanceof dumper.intrp2.Object) ? Do.DONE : Do.RECURSE; } output.push(';'); } this.setDone(part, done); dumper.write.apply(dumper, output); return done; }; /** * Return the current 'done' status of a variable binding. * @param {Selector.Part} part The part get status for. Must be simple string. * @return {!Do} The done status of the binding. */ ScopeDumper.prototype.getDone = function(part) { if (typeof part !== 'string') { throw new TypeError('Invalid part (not a variable name)'); } var done = this.doneVar_[part]; return done === undefined ? Do.UNSTARTED : done; }; /** * Update the current 'done' status of a variable binding. Will throw * a RangeError if caller attempts to un-do a previously-done action. * @param {Selector.Part} part The part set status for. Must be simple string. * @param {!Do} done The new done status of the binding. */ ScopeDumper.prototype.setDone = function(part, done) { if (typeof part !== 'string') { throw new TypeError('Invalid part (not a variable name)'); } var old = this.getDone(part); // Invariant checks. if (done <= old) { var fault = (done === old) ? 'Refusing redundant' : "Can't undo previous"; throw new RangeError(fault + ' work on variable ' + part); } this.doneVar_[part] = done; }; /** * Return the value of the given variable in this.scope (i.e., the * value in intrp2, and the intended final value - provided that it * isn't going to be pruned.) * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs. * @param {Selector.Part} part The binding part to get the value of. * @return {Interpreter.Value} The value of that part. */ ScopeDumper.prototype.getValue = function(dumper, part) { if (typeof part !== 'string') throw new TypeError('Invalid first part??'); if (!this.scope.hasBinding(part)) { throw new ReferenceError(part + ' is not defined'); } return this.scope.get(part); }; /** * Return true iff the given binding (which must be a variable name) * is currently reachable. Specifically, this will return true if: * * 1. this.scope is the current value dumper.scope, since we can * always access existing bindings and create new ones in the * current scope. * 2. this.scope is an outer scope of dumper.scope and par * is not shadowed in dumper.scope or any intervening one. * * BUG(cpcallen): Only #1 is implemented at the moment. * * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs. * @param {Selector.Part=} part Variable name whose reachability is of * interest. * @return {boolean} */ ScopeDumper.prototype.reachable = function(dumper, part) { return this.scope === dumper.scope; }; /** * Visit a Scope to prepare for dumping. In particular: * * - If this.scope.outerScope is set, record this as one of it's inner * scopes, so that when we go to dump that scope later we know we * need to dump this one inside it. * * - Find any Arguments object attached to this scope and record the * relationship in the dumper.argumentsScopeDumpers map. * * - Collect and return an array of {part, value} tuples, where each * represents a variable in this scope. * * @param {!Dumper} dumper Dumper to which this ScopeDumper belongs. * @return {!Array} */ ScopeDumper.prototype.survey = function(dumper) { var /** !Array */ adjacent = []; // Record parent scope. if (this.scope !== dumper.intrp2.global) { if (this.scope.outerScope === null) { throw new TypeError('Non-global scope has null outer scope'); } var outerScopeDumper = dumper.getScopeDumper_(this.scope.outerScope); // Record this as inner scope of this.outerScope. outerScopeDumper.innerScopes.add(this); // Don't forget to survey the outerScope, too: adjacent.push(outerScopeDumper); } // Record arguments object attached to this scope if it's a function scope. if (this.scope.type === Interpreter.Scope.Type.FUNCTION && this.scope.hasImmutableBinding('arguments')) { var argsObject = this.scope.get('arguments'); if (!(argsObject instanceof dumper.intrp2.Arguments)) { // BUG(cpcallen): what about function(arguments) {...}? throw new TypeError('arguments not an Arguments object'); } else if (dumper.argumentsScopeDumpers.has(argsObject)) { // BUG(cpcallen): what about (function(arguments) {...})( // (function() {return arguments;})()); ? throw new Error('Arguments object belongs to more than one scope'); } dumper.argumentsScopeDumpers.set(argsObject, this); } // Collect Components for other objects reachable from this one. for (var name in this.scope.vars) { adjacent.push({part: name, value: this.scope.get(name)}); } return adjacent; }; /////////////////////////////////////////////////////////////////////////////// // ObjectDumper /** * ObjectDumper encapsulates all machinery to dump an * Interpreter.prototype.Object to eval-able JS, including maintaining * all the dump-state info required to keep track of what properties * (etc.) have and haven't yet been dumped. * @constructor @extends {SubDumper} * @struct * @param {!Interpreter.prototype.Object} obj The object to keep state for. */ var ObjectDumper = function(obj) { SubDumper.call(this); /** @type {!Interpreter.prototype.Object} */ this.obj = obj; /** * Preferred reference to this object. E.g., for Object.prototype * this would be {dumper: , part: 'prototype'}. * @type {?Components} */ this.preferredRef = null; /** * A valid-at-this-point-in-the-dump referrence to this object. * @type {?Components} Reference to this object, once created. */ this.ref = null; /** * If true, then .dump() will not dump any ordinary (property / * member / entry) bindings. This means that only bindings dumped * by calls to .dumpBinding() will be dumped. (Prototype and owner * bindings will still be dumped unless they are individually * .prune()ed.) * @type {boolean} */ this.pruneRest = false; /** @type {!ObjectDumper.Done} How much has object been dumped? */ this.done = ObjectDumper.Done.NO; /** @private @type {!Do} Has prototype been set? */ this.doneProto_ = Do.DECL; // Never need to 'declare' the [[Prototype]] slot! /** * Current value of [[Prototype]] slot of obj at this point in dump. * Typically initially Object.prototype (or similar); will be === * obj.proto when complete. Used to check for unwritable inherited * properties when attempting to set properties by assignment. * Should only be undefined if object has not yet been created. * @type {?Interpreter.prototype.Object|undefined} */ this.proto = undefined; /** @private @type {!Do} Has owner been set? */ this.doneOwner_ = Do.DECL; // Never need to 'declare' that object has owner! /** @private @const {!Object} Done status of each property. */ this.doneProp_ = Object.create(null); /** * Map of property name -> property descriptor, where property * descriptor is a map of attribute names (writable, enumerable, * configurable, more tbd) to boolean values describing the present * attributes of the property at the current point in the dump; this * is updated as code that modifies them is generated. (We do not * store values here.) * @type {!Object>} */ this.attributes = Object.create(null); /** @type {?Array} Properties to delete. */ this.toDelete = null; }; Object.setPrototypeOf(ObjectDumper, SubDumper); Object.setPrototypeOf(ObjectDumper.prototype, SubDumper.prototype); /** * Updates done state of property binding after defining/assigning a * property. This computes the new done value, calls .setDone(key, * done) and returns the new value. * @param {string} key The property key just updated. * @param {Interpreter.Value} value The value just assigned to the property. * @param {!Object} attr The property's current attributes. * @param {!Interpreter.Descriptor|undefined} pd Property descriptor * returned by calling this.obj.getOwnPropertyDescriptor(key, ...). * @return {!Do} New done state. */ ObjectDumper.prototype.checkProperty = function(key, value, attr, pd) { var done; if (!Object.is(value, pd.value)) { done = Do.DECL; } else if (attr.writable === pd.writable && attr.enumerable === pd.enumerable && attr.configurable === pd.configurable) { done = (typeof value === 'object') ? Do.ATTR : Do.RECURSE; } else { done = Do.SET; } this.setDone(key, done); return done; }; /** * Recursively dumps all bindings of the object (and objects reachable * via it). * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {!Selector=} objSelector Selector refering to this object. * Optional; defaults to whatever selector was used to create the * object. * @param {!Array<(!SubDumper)>=} visiting List of Scope/Object dumpers * currently being recursively dumped. Used only when * recursing. * @param {!Set<(!SubDumper)>=} visited Set of Scope/Object dumpers * currently that have already been visited. Used only when * recursing. * @return {!ObjectDumper.Done|?ObjectDumper.Pending} Done status for * object, or or null if there is an outstanding dump or * dumpBinding invocaion for this object, or a (bindings, * dependencies) pair if a recursive call encountered such an * outstanding invocation. */ ObjectDumper.prototype.dump = function( dumper, objSelector, visiting, visited) { if (!visiting) visiting = []; if (!visited) visited = new Set(); if (!objSelector) objSelector = this.getSelector(); if (!objSelector) throw new Error("can't dump unreferencable object"); if (this.proto === undefined) { throw new Error("can't dump uncreated object " + this.getSelector(true)); } if (visited.has(this)) return null; if (this.done === ObjectDumper.Done.DONE_RECURSIVELY) return this.done; visiting.push(this); visited.add(this); // Delete properties that shouldn't exist. if (this.toDelete) { var sel = new Selector(objSelector); for (var key, i = 0; (key = this.toDelete[i]); i++) { sel.push(key); dumper.write('delete ', dumper.exprForSelector_(sel), ';'); sel.pop(); } this.toDelete = null; } // Dump bindings: prototype, owner, and properties. // TODO(cpcallen): Also dump set/map entries, etc. // Optimistically assume success until we find otherwise. var /** !ObjectDumper.Done */ done = ObjectDumper.Done.DONE_RECURSIVELY; var /** ?ObjectDumper.Pending */ pending = null; var keys = this.obj.ownKeys(dumper.intrp2.ROOT); var parts = [Selector.PROTOTYPE, Selector.OWNER]; if (!this.pruneRest) parts = parts.concat(keys); for (i = 0; i < parts.length; i++) { var part = parts[i]; if (this.prune_ && this.prune_.has(part)) { // TODO(cpcallen): delete binding if necessary. continue; } else if (this.skip_ && this.skip_.has(part) || dumper.options.skipBindings.includes(part)) { // Can't finish an object with skipped parts. done = /** @type {!ObjectDumper.Done} */( Math.min(done, ObjectDumper.Done.NO)); continue; } // Attempt to dump the binding itself. var bindingSelector = new Selector(objSelector.concat(part)); var bindingDone = this.dumpBinding(dumper, part, Do.DONE, objSelector, bindingSelector); if (bindingDone === Do.RECURSE) { // Nothing more to do for part. continue; } else if (bindingDone < Do.DONE) { // Object can't be done. done = /** @type {!ObjectDumper.Done} */( Math.min(done, ObjectDumper.Done.NO)); } if (bindingDone < Do.SET) continue; // Can't recurse if no object yet! // Attempt to recursively dump the value object, if there is one. var value = this.getValue(dumper, part); if (!(value instanceof dumper.intrp2.Object)) continue; var valueDumper = dumper.getObjectDumper_(value); if (dumper.options.treeOnly && (this !== valueDumper.preferredRef.dumper || part !== valueDumper.preferredRef.part)) { // Refuse to recurse into objects outside of the spanning tree. done = /** @type {!ObjectDumper.Done} */( Math.min(done, ObjectDumper.Done.DONE)); continue; } valueDumper.updateRef(dumper, new Components(this, part)); var objDone = valueDumper.dump(dumper, bindingSelector, visiting, visited); if (objDone === null || objDone instanceof ObjectDumper.Pending) { // Circular structure detected. if (!pending) { pending = new ObjectDumper.Pending(bindingSelector, valueDumper); } else { pending.add(bindingSelector, valueDumper); } if (objDone instanceof ObjectDumper.Pending) { // Circular dependency detected amongst objects being recursively // dumped. Record details of circularity. Add this binding. pending.merge(objDone); } } else if (objDone === ObjectDumper.Done.DONE_RECURSIVELY) { // Successful recursive dump. Upgrade binding accordingly. this.setDone(part, Do.RECURSE); } } if (this.done < ObjectDumper.Done.DONE && done >= ObjectDumper.Done.DONE) { // Dump extensibility. if (!this.obj.isExtensible(dumper.intrp2.ROOT)) { dumper.write( dumper.exprForCall_('Object.preventExtensions', [objSelector]), ';'); } this.done = ObjectDumper.Done.DONE; // Set now to allow cycles to complete. } visiting.pop(); // If all parts of circular dependency are DONE, mark all as // RECURSE / DONE_RECURSIVELY. // TODO(cpcallen): Clean up this code. if (done) { if (pending) { if (pending.dependencies.some( function(dep) {return !dep.done || visiting.includes(dep);})) { done = /** @type {!ObjectDumper.Done} */( Math.min(done, ObjectDumper.Done.DONE)); } else { var /** !Selector */ binding; for (i = 0; (binding = pending.bindings[i]); i++) { dumper.markBinding_(binding, Do.RECURSE); } for (var dep, i = 0; (dep = pending.dependencies[i]); i++) { dep.done = ObjectDumper.Done.DONE_RECURSIVELY; } pending = null; } } } this.done = done; return pending || done; }; /** * Generate JS source text to create and/or initialize a single * binding (property or internal slot) of the object. * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {Selector.Part} part The binding part to dump. * @param {!Do} todo How much to do. Must be >= Do.DECL; > Do.ATTR ignored. * @param {!Selector=} objSelector Selector refering to this object. * Optional; will be created using getSelector if not supplied. * @param {!Selector=} bindingSelector Selector refering to part. * Optional; will be created by appending part to objSelector. * @return {!Do} The done status of the specified binding. */ ObjectDumper.prototype.dumpBinding = function( dumper, part, todo, objSelector, bindingSelector) { if (!objSelector) objSelector = this.getSelector(); if (!objSelector) { throw new Error("can't dump unreferencable object"); } else if (this.proto === undefined) { throw new Error("can't dump uncreated object " + this.getSelector(true)); } else if (this.prune_ && this.prune_.has(part)) { return Do.RECURSE; // Don't dump requested binding at all. } else if (this.skip_ && this.skip_.has(part)) { return this.getDone(part); // Do nothing but don't lie about it. } if (!bindingSelector) { bindingSelector = new Selector(objSelector.concat(part)); } var partRef = new Components(this, part); if (part === Selector.PROTOTYPE) { return this.dumpPrototype_(dumper, todo, partRef, objSelector, bindingSelector); } else if (part === Selector.OWNER) { return this.dumpOwner_(dumper, todo, partRef, objSelector, bindingSelector); } else if (typeof part === 'string') { return this.dumpProperty_(dumper, part, todo, partRef, objSelector, bindingSelector); } else { throw new Error('Invalid part'); } }; /** * Generate JS source text to set the object's [[Owner]]. * @private * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {!Do} todo How much to do. Must be >= Do.DECL; > Do.SET ignored. * @param {!Components} partRef A reference to this object's [[Owner]] slot. * @param {!Selector} objSelector Selector refering to this object. * @param {!Selector} bindingSelector Selector refering to this * object's [[Owner]] slot. * @return {!Do} The done status of the object's [[Owner]] slot. */ ObjectDumper.prototype.dumpOwner_ = function( dumper, todo, partRef, objSelector,bindingSelector) { var value = /** @type {?Interpreter.prototype.Object} */(this.obj.owner); if (todo >= Do.SET && this.doneOwner_ < Do.SET) { // Record owner connection. if (value !== null) { dumper.getObjectDumper_(value) .updateRef(dumper, new Components(this, Selector.OWNER)); } dumper.write( dumper.exprForCall_('Object.setOwnerOf', [objSelector, value]), ';'); this.doneOwner_ = (value === null) ? Do.RECURSE: Do.DONE; } return this.doneOwner_; }; /** * Generate JS source text to create and/or initialize a single * property of the object. The output will consist of: * * - An assignment statement to create the property and/or set its * value, if necessary and possible. * - A call to Object.defineProperty, to set the property's attributes * (and value, if the value couldn't be set by assignement), if * necessary. * @private * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {string} key The property to dump. * @param {!Do} todo How much to do. * @param {!Components} partRef A reference to this object's property [key]. * @param {!Selector} objSelector Selector refering to this object. * @param {!Selector} bindingSelector Selector refering to key. * @return {!Do} The done status of the specified property. */ ObjectDumper.prototype.dumpProperty_ = function( dumper, key, todo, partRef, objSelector, bindingSelector) { var pd = this.obj.getOwnPropertyDescriptor(key, dumper.intrp2.ROOT); if (!pd) { throw new RangeError("can't dump nonexistent property " + bindingSelector); } // Do this binding, if requested. var done = this.getDone(key); if (todo >= Do.DECL && todo > done && done < Do.ATTR) { var attr = this.attributes[key]; // If only "declaring" property, set it to undefined. var value = (todo === Do.DECL) ? undefined : pd.value; // Output assignment statement if useful. if (done < Do.SET && this.isWritable(dumper, key)) { if (!attr) { attr = this.attributes[key] = {writable: true, enumerable: true, configurable: true}; } // Will this assignemnt set the .name of an anonymous function? // TODO(ES6): Handle prefix? var funcName = dumper.intrp1.options.methodNames ? key : undefined; dumper.write(dumper.exprForSelector_(bindingSelector), ' = ', dumper.exprFor_(value, partRef, false, funcName), ';'); done = this.checkProperty(key, value, attr, pd); } // Output defineProperty call if useful. if (todo > done && done < Do.ATTR) { if (!attr) { attr = this.attributes[key] = {writable: false, enumerable: false, configurable: false}; } else if (!attr.configurable) { dumper.warn( "Can't redefine non-configurable property " + bindingSelector); return done; } var items = []; if (attr.writable !== (pd.writable || todo < Do.SET)) { attr.writable = pd.writable || todo < Do.SET; items.push('writable: ' + attr.writable); } if (attr.enumerable !== (pd.enumerable || todo < Do.SET)) { attr.enumerable = pd.enumerable || todo < Do.SET; items.push('enumerable: ' + attr.enumerable); } if (attr.configurable !== (pd.configurable || todo < Do.SET)) { attr.configurable = pd.configurable || todo < Do.SET; items.push('configurable: ' + attr.configurable); } if (todo >= Do.SET && done < Do.SET) { // TODO(cpcallen): supply selector here? items.push('value: ' + dumper.exprFor_(value)); } dumper.write(dumper.exprForBuiltin_('Object.defineProperty'), '(', dumper.exprForSelector_(objSelector), ', ', dumper.exprFor_(key), ', {', items.join(', '), '});'); done = this.checkProperty(key, value, attr, pd); } } return done; }; /** * Generate JS source text to set the object's [[Prototype]]. * @private * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {!Do} todo How much to do. Must be >= Do.DECL; > Do.SET ignored. * @param {!Components} partRef A reference to this object's [[Owner]] slot. * @param {!Selector} objSelector Selector refering to this object. * @param {!Selector} bindingSelector Selector refering to this * object's [[Prototype]] slot. * @return {!Do} The done status of the object's [[Prototype]] slot. */ ObjectDumper.prototype.dumpPrototype_ = function( dumper, todo, partRef, objSelector, bindingSelector) { var value = this.obj.proto; if (todo >= Do.SET && this.doneProto_ < Do.SET) { // Record prototype connection. this.proto = value; if (value !== null) { dumper.getObjectDumper_(value) .updateRef(dumper, new Components(this, Selector.PROTOTYPE)); } dumper.write( dumper.exprForCall_('Object.setPrototypeOf', [objSelector, value]), ';'); this.doneProto_ = (value === null) ? Do.RECURSE: Do.DONE; } return this.doneProto_; }; /** * Return the current 'done' status of an object binding. * @param {Selector.Part} part The part to get status for. * @return {!Do} The done status of the binding. */ ObjectDumper.prototype.getDone = function(part) { if (part === Selector.PROTOTYPE) { return this.doneProto_; } else if (part === Selector.OWNER) { return this.doneOwner_; } else if (typeof part === 'string') { var done = this.doneProp_[part]; return done === undefined ? Do.UNSTARTED : done; } else { throw new TypeError('Invalid part'); } }; /** * Return a Selector for this object. If preferred is true, the * preferred selector will be returned; this is the least-badness * Selecgtor in intrp2 for this.obj, but may not yet be a valid * selector at the current point in the dump. Otherwise, the selector * returned will be the best known valid selector. An Error will be * thrown if no valid selector exists. * @param {boolean=} preferred Return preferred selector? * @return {!Selector} A selector for this.obj. */ ObjectDumper.prototype.getSelector = function(preferred) { var /** !SubDumper */ sd = this; var /** !Array */ parts = []; while (sd instanceof ObjectDumper) { var /** ?Components */ next = preferred ? sd.preferredRef : sd.ref; if (!next) throw new Error('unreferenced object while building Selector'); sd = next.dumper; parts.unshift(next.part); } if (!(sd instanceof ScopeDumper)) { throw new TypeError('unknown SubDumper subclass'); } else if (sd.scope.type !== Interpreter.Scope.Type.GLOBAL) { throw new Error('refusing to create Selector for non-global scope'); } return new Selector(parts); }; /** * Return the value of the given part of this.obj (i.e., the value * in intrp2, and the intended final value provided that it isn't * going to be pruned.) * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {Selector.Part} part The binding part to get the value of. * @return {Interpreter.Value} The value of that part. */ ObjectDumper.prototype.getValue = function(dumper, part) { if (typeof part === 'string') { return this.obj.get(part, dumper.intrp2.ROOT); } else if (part === Selector.PROTOTYPE) { return this.obj.proto; } else if (part === Selector.OWNER) { return /** @type{?Interpreter.prototype.Object} */(this.obj.owner); } else { throw new Error('unknown part type'); } }; /** * Return true iff the specifed property can be created or set by * assignment - i.e., that it exists and is writable, or doesn't exist * and does not inherit from a non-writable property on the prototype * chain. * * N.B. this not checking writability on intrp1 or intrp2, but on the * notional state of the interpreter at this point in the dump (i.e., * somewhere in between the two), as recorded on the relevant * ObjectDumper .attibutes and .proto properties. * * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {string} key The property key to check for writability of. * @return {boolean} True iff the property can be set by assignment. */ ObjectDumper.prototype.isWritable = function(dumper, key) { // Invariant checks. if (this.proto === undefined) { throw new Error('Checking writability of property on non-created object'); } else if ((key in this.attributes) !== (this.getDone(key) >= Do.DECL)) { throw new Error('Attribute / done mismatch'); } if (key in this.attributes) { return this.attributes[key].writable; } else { if (this.proto === null) { return true; } else { return dumper.getObjectDumper_(this.proto).isWritable(dumper, key); } } }; /** * Return true iff this.object is currently reachable. * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @param {Selector.Part=} part The binding whose reachability is of * interest. Ignored, since all object bindings are always * reachable if the object is. * @return {boolean} */ ObjectDumper.prototype.reachable = function(dumper, part) { return Boolean(this.ref) && this.ref.dumper.reachable(dumper, this.ref.part); }; /** * Record that the (ressurected) object will have a property, not on * the original, that needs to be deleted. * @param {string} key The property key to delete. */ ObjectDumper.prototype.scheduleDeletion = function(key) { if (this.toDelete) { this.toDelete.push(key); } else { this.toDelete = [key]; } }; /** * Update the current 'done' status of a property. Will throw a * RangeError if caller attempts to un-do or re-do a previously-done * action. * @param {Selector.Part} part The part to set status for. * @param {!Do} done The new done status of the binding. */ ObjectDumper.prototype.setDone = function(part, done) { var old = this.getDone(part); // Invariant checks. if (done <= old) { var fault = (done === old) ? 'Refusing redundant' : "Can't undo previous"; var description = this.getSelector(/*preferred=*/true); throw new RangeError(fault + ' work on ' + part + ' of ' + description); } // Do set. if (part === Selector.PROTOTYPE) { this.doneProto_ = done; } else if (part === Selector.OWNER) { this.doneOwner_ = done; } else if (typeof part === 'string') { this.doneProp_[part] = done; } }; /** * Visit an Object to prepare for dumping. In particular: * * - If this.object is a UserFunction, record it on it's .scope's * ScopeDumper's list of inner functions, so that when we go to dump * that scope later we know all the functions that need to be * declared within it. * * - Collect and return an array of {part, value}, where each * represents a property or internal slot of this.object. If * this.object is a UserFunction, the returned array will also * contain a bare ScopeDumper object representing the * function's enclosing scope. * * @param {!Dumper} dumper Dumper to which this ObjectDumper belongs. * @return {!Array} */ ObjectDumper.prototype.survey = function(dumper) { var /** !Array */ adjacent = []; if (this.obj instanceof dumper.intrp2.UserFunction) { // Record this this function as inner to scope, and survey scope. var scopeDumper = dumper.getScopeDumper_(this.obj.scope); scopeDumper.innerFunctions.add(this); adjacent.push(scopeDumper); } adjacent.push({part: Selector.PROTOTYPE, value: this.obj.proto}); var ownerObj = /** @type {!Interpreter.prototype.Object} */(this.obj.owner); adjacent.push({part: Selector.OWNER, value: ownerObj}); var keys = this.obj.ownKeys(dumper.intrp2.ROOT); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = this.obj.get(key, dumper.intrp2.ROOT); adjacent.push({part: key, value: value}); } return adjacent; }; /** * Record a new reference to the object, if it is 'better' than the * existing one. 'Better' means, in order of priority: * * - Ignore references from self entirely. * - Prefer any reference over no reference. * - Prefer references from reachable objects over ones from * unreachable objects. * - If both existing (this.ref) and proposed (ref) .dumpers are reachable: * - Prefer .preferredRef over others, otherwise * - Prefer reference with lowest overall badness. * - If neither .dumper is reachable, prefer reference with lowest overall * badness when using .dumpers's .preferredRef instead. * * @param {!Dumper} dumper The Dumper to which this ObjectDumber belongs. * @param {!Components} ref The new reference. * @return {void} */ ObjectDumper.prototype.updateRef = function(dumper, ref) { if (ref.dumper === this) return; // Ignore references from self entirely. if (!this.ref) { // Prefer any reference over no reference. this.ref = ref; return; } if (this.ref.isReachable(dumper)) { if (ref.isReachable(dumper)) { // Both existing and new refs reachable. if (this.preferredRef) { // Prefer .preferredRef over others. if (this.preferredRef.equals(this.ref)) { return; } else if(this.preferredRef.equals(ref)) { this.ref = ref; return; } } // Otherwise, prefer ref with lowest overall badness. var oldBadness = this.getSelector().badness(); var newBadness = Selector.partBadness(ref.part); if (ref.dumper instanceof ObjectDumper) { newBadness += ref.dumper.getSelector().badness(); } if (newBadness < oldBadness) this.ref = ref; } } else { if (ref.isReachable(dumper)) { // Existing ref unreachable but new ref is! this.ref = ref; } else { // Neither existing nor new refs reachable. var oldBadness = Selector.partBadness(this.ref.part) + (this.ref.dumper instanceof ObjectDumper ? this.ref.dumper.getSelector(/*preferred=*/true).badness() : 0); var newBadness = Selector.partBadness(ref.part) + (ref.dumper instanceof ObjectDumper ? ref.dumper.getSelector(/*preferred=*/true).badness() : 0); if (newBadness < oldBadness) this.ref = ref; } } }; /** * Tri-state "done" flag for ObjectDumper. A bit like Do, but for the * whole object rather than a single binding. * @enum {number} */ ObjectDumper.Done = { /** Object not fully dumped. */ NO: 0, /** * Object is done (has all own properties fully defined including * attributes, has correct [[Owner]] and [[Prototype]], is * non-extensible if applicable, etc.). */ DONE: 1, /** This object and all objects accessible from it are done. */ DONE_RECURSIVELY: 2, }; /** * A record of pending bindings returned by the .dump and .dumpBinding * methods when they encounter a circular dependency while trying to * recursively dump some objects. * * E.g., given objects a and b, if a.b === b, and b.a === a, then * either both a and b can be both be fully recursivley dumped or * neither is. When attempting to dump a, the dumpProperty() * will try to dump b, which will ensure that b.a is done and return a * Pending object indicating that being recursively done is * awaiting completion of a. * * @constructor * @struct * @param {!Selector} binding A binding awaiting recursive completion * of its value object. * @param {!ObjectDumper} valueDumper The ObjectDumper for the object * which is the value of binding. */ ObjectDumper.Pending = function(binding, valueDumper) { if (!binding) throw new Error('no binding'); if (!valueDumper) throw new Error('no valueDumper'); /** !Array */ this.bindings = [binding]; /** !Array */ this.dependencies = [valueDumper]; }; /** * Add a new (binding, dependency) pair to this Pending object. * @param {!Selector} binding A binding awaiting recursive completion * of its value object. * @param {!ObjectDumper} valueDumper The ObjectDumper for the object * which is the value of binding. */ ObjectDumper.Pending.prototype.add = function(binding, valueDumper) { if (!binding) throw new Error('no binding'); if (!valueDumper) throw new Error('no valueDumper'); this.bindings.push(binding); this.dependencies.push(valueDumper); }; /** * Merge another pending list into this one. * @param {!ObjectDumper.Pending} that Another Pending list. */ ObjectDumper.Pending.prototype.merge = function(that) { this.bindings = this.bindings.concat(that.bindings); this.dependencies = this.dependencies.concat(that.dependencies); }; /** @override */ ObjectDumper.Pending.prototype.toString = function() { return '{bindings: [' + this.bindings.join(', ') + '], ' + 'dependencies: [' + this.dependencies.map(function(od) { return String(od.getSelector(/*preferred=*/true)); }).join(', ') + ']}'; }; /////////////////////////////////////////////////////////////////////////////// // Helper Classes. /** * A {SubDumper, Selector.Part} tuple. * * N.B.: the usage of 'components' here is analagous to that term's * usage in interpreter.js but not identical: there is is a [scope, * variable] tuple; here it is a {ScopeDumper/ObjectDumper, * Selector.Part} tuple. * * @constructor * @struct * @param {!SubDumper} dumper * @param {Selector.Part} part */ var Components = function(dumper, part) { /** @const {!SubDumper} */ this.dumper = dumper; /** @const {Selector.Part} */ this.part = part; }; /** * Return true iff this and that represent the same binding. * @param {!Components} that Another Components to compare this with. * @return {boolean} */ Components.prototype.equals = function(that) { return this.dumper === that.dumper && this.part === that.part; }; /** * Return true iff this reference is currently reachable. * @param {!Dumper} dumper Dumper to which this Components belongs. * @return {boolean} */ Components.prototype.isReachable = function(dumper) { return this.dumper.reachable(dumper, this.part); }; /** * Custom util.inspect implementation, to make debug/test output more * readable. * @param {number} depth * @param {util.inspect.Options} opts * @return {string} */ Components.prototype[util.inspect.custom] = function(depth, opts) { var /** string */ dumper; if (this.dumper instanceof ScopeDumper) { dumper = util.format('<%s scope>', this.dumper.scope.type); } else if (this.dumper instanceof ObjectDumper) { try { dumper = this.dumper.getSelector(/*preferred=*/true).toString(); } catch (e) { dumper = ''; } } return util.format('[%s.%s]', dumper, this.part); }; /////////////////////////////////////////////////////////////////////////////// // Type declarations: Do, etc. /** * Possible things to do (or have done) with a variable / property / * etc. binding. N.B.: values meaning "don't do this one (yet)" * are negative, "nothing done" is zero (and therefore falsey), and * "some work has been done" are positive. * * Code should not depend on the numeric values of the enum options, * but it is permissiible to depend on the options being in numeric * order of ascending completion - i.e., Do.x implies Do.y if Do.x >= * Do.y. * * @enum {number} */ var Do = { /** * Nothing has been done about this binding yet. Only valid as a * 'done' value, not as a 'do' value. */ UNSTARTED: 0, /** * Ensure that the specified binding exists, but do not yet set it * to its final value. If the binding is a variable, it has been / * will be declared; if it is a property, it has been / will be * created but not (yet) set to a value other than undefined (nor * made non-configurable). */ DECL: 1, /** * Ensure that the specified binding exists and has been set to its * final value (if primitive) or an object of the correct class (if * non-primitive). * * For property bindings, the property attributes will generally not * (yet) be set, and if a new object was created to be the value of * the specified binding it will generally not (yet) have its * properties or internal set/map data set (but immutable internal * data, such as function code, will have been set at creation). */ SET: 2, /** * Ensure theat the specified binding has been set to its final * value, and additionally that the final property attributes * (enumerable, writable and/or configurable) are set. DONE is * provided as an alias for bindings (like variables, * [[Prototype]] and [[Owner]] that don't have attributes; for * those, SET should automatically be promoted to DONE. */ ATTR: 3, DONE: 3, /** * Ensure the specified path is has been set to its final value (and * marked immuable, if applicable) and that the same has been done * recursively to all bindings reachable via path. */ RECURSE: 4, }; /** * Options object for Dumper. * @record */ var DumperOptions = function() {}; /** * The stream that this.write() will write to. Setting it to null * (the default) will cause cause .write() to do nothing, causing * dumped code to be lost. * @type {?Writable|undefined} */ DumperOptions.prototype.output; /** * Skip the named bindings. * @type {!Array|undefined} */ DumperOptions.prototype.skipBindings; /** * If true, limit recursive dumping to the spaning tree defined by the * preferred selectors. * * E.g.: Noting that Object{proto}, Fucntion{proto} and * Function.prototype are the same object. If treeOnly is true (the * default), then: * * * Dumping Object recursively would set Object{proto} but not visit * Function.prototype at all, while * * Dumping Function recursively would set Function{proto} but * recurse into Function.prototype. * * On the other hand, if treeOnly is false, then dumping Object * recursively would recurse into Object{proto} (i.e., * Function.prototype by a different name), and dumping Function might * choose ot recurse via Function{proto} rather than * Function.prototype. * * @type {boolean|undefined} */ DumperOptions.prototype.treeOnly; /** * Print status information and warnings to the console? * @type {boolean|undefined} */ DumperOptions.prototype.verbose; /** * Default options for Dumper. * @const @type {!DumperOptions} */ var DEFAULT_OPTIONS = { output: null, skipBindings: [], treeOnly: true, verbose: false, }; /** * A value representing an outward edge (from an unspecified object) * on the object graph. * * - Outward edges that are properties or internal slots are * represented as a {Selector.Part, Interpreter.Value} tuple. * - Outward edges that are the enclosing scope of a UserFunction are * represented by a bare ScopeDumper. * @typedef {{part: Selector.Part, value: Interpreter.Value}|!ScopeDumper} */ var OutwardEdge; /** * A writable stream. Could be a stream.Writable, but we don't check * the return value of .write to see if it's safe to keep writing, so * caller might prefer to supply a synchronous implementation instead! * @interface */ var Writable = function() {}; /** * Write a string to the writable stream. * @param {string} s */ Writable.prototype.write = function(s) {}; /////////////////////////////////////////////////////////////////////////////// // Exports. exports.Do = Do; exports.Dumper = Dumper; exports.DumperOptions = DumperOptions; exports.Writable = Writable; // For unit testing only! exports.testOnly = { Components: Components, ObjectDumper: ObjectDumper, ScopeDumper: ScopeDumper, }; ================================================ FILE: server/externs/WeakRef.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Closure Compiler externs for the new ES2020 WeakRef and * FinalizationRegistry API https://tc39.es/ecma262/#sec-managing-memory * @author cpcallen@google.com (Christopher Allen) * @externs */ // Closure Compiler (as of google-closue-compiler@20210406.0.0) now // knows about WeakRef, but it doesn't yet know about FinalizationRegistry. /** * @constructor * @struct * @param {function(HELDVALUE)} cleanupCallback * @template TARGET, HELDVALUE, TOKEN * @nosideeffects */ // TODO(cpcallen): Make TARGET and TOKEN bounded to {!Object} once // closure-compiler supports bounded generic types. var FinalizationRegistry = function(cleanupCallback) {}; /** * @param {TARGET} target * @param {HELDVALUE} heldValue * @param {TOKEN=} unregisterToken * @return {void} */ FinalizationRegistry.prototype.register = function(target, heldValue, unregisterToken) {}; /** * @param {TOKEN} unregisterToken * @return {void} */ FinalizationRegistry.prototype.unregister = function(unregisterToken) {}; ================================================ FILE: server/externs/buffer/buffer.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's buffer module to * satisfy Closure Compiler dependencies. This is mostly an * excerpt from contrib/nodejs/buffer.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. /** @constructor @struct */ var Buffer = function() {}; exports.Buffer = Buffer; ================================================ FILE: server/externs/buffer/package.json ================================================ { "description": "Fake package.json for require('buffer')", "main": "buffer.js", "name": "buffer", } ================================================ FILE: server/externs/crypto/crypto.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's crypto module to satisfy * Closure Compiler dependencies. This is mostly an excerpt from * contrib/nodejs/fs.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. var Buffer = require('buffer').Buffer; var stream = require('stream'); /** @const */ var crypto = {}; /** * @param {string} algorithm * @return {crypto.Hash} */ crypto.createHash = function(algorithm) {}; /** * @constructor * @struct * @extends stream.Transform * @param {string} algorithm * @param {Object=} options */ crypto.Hash = function(algorithm, options) {}; /** * @param {string|Buffer} data * @param {string=} input_encoding * @return {crypto.Hash} */ crypto.Hash.prototype.update = function(data, input_encoding) {}; /** * @param {string=} encoding * @return {string} */ crypto.Hash.prototype.digest = function(encoding) {}; /** * @return {!Array} */ crypto.getHashes = function() {}; module.exports = crypto; ================================================ FILE: server/externs/crypto/package.json ================================================ { "description": "Fake package.json for require('crypto')", "main": "crypto.js", "name": "crypto", } ================================================ FILE: server/externs/events/events.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's events module to * satisfy Closure Compiler dependencies. * @author cpcallen@google.com (Christopher Allen) */ /** @const */ var events = {}; /** @type {symbol} */ events.errorMonitor; /** @constructor @struct */ events.EventEmitter = function() {}; /** * @param {string|symbol} event * @param {function(...)} listener * @return {events.EventEmitter} */ events.EventEmitter.prototype.on = function(event, listener) {}; /** * @param {string|symbol} event * @param {function(...)} listener * @return {events.EventEmitter} */ events.EventEmitter.prototype.once = function(event, listener) {}; /** * @param {string|symbol} event * @param {function(...)} listener * @return {events.EventEmitter} */ events.EventEmitter.prototype.removeListener = function(event, listener) {}; module.exports = events; ================================================ FILE: server/externs/events/package.json ================================================ { "description": "Fake package.json for require('events')", "main": "events.js", "name": "events", } ================================================ FILE: server/externs/fs/fs.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's fs module to satisfy * Closure Compiler dependencies. This is mostly an excerpt from * contrib/nodejs/fs.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. var Buffer = require('buffer').Buffer; var stream = require('stream'); /** @const */ var fs = {}; /** * @param {string} path * @param {number=} mode */ fs.accessSync = function(path, mode) {}; /** * @param {number} fd * @return {void} */ fs.closeSync = function(fd) {}; /** * @param {string} path * @param {{flags: (string|undefined), * encoding: (string|undefined), * fd: (number|undefined), * mode: (number|undefined), * bufferSize: (number|undefined)}=} options * @return {fs.ReadStream} */ fs.createReadStream = function(path, options) {}; /** * @constructor * @struct * @extends stream.ReadableStream */ fs.ReadStream = function () {}; /** * @param {string} path * @param {{flags: (string|undefined), * encoding: (string|undefined), * mode: (number|undefined)}=} options * @return {fs.WriteStream} */ fs.createWriteStream = function(path, options) {}; /** * @constructor * @struct * @extends stream.WritableStream */ fs.WriteStream = function () {}; /** * @param {string} path * @return {boolean} */ fs.existsSync = function(path) {}; /** * @param {string} path * @param {string} flags * @param {number=} mode * @return {number} */ fs.openSync = function(path, flags, mode) {}; /** * @param {string} path * @return {Array} */ fs.readdirSync = function(path) {}; /** * @param {string} filename * @param {string=} encoding * @return {string|Buffer} */ fs.readFileSync = function(filename, encoding) {}; /** * @param {string} oldPath * @param {string} newPath * @return {void} */ fs.renameSync = function(oldPath, newPath) {}; /** * @param {string} path * @return {fs.Stats} */ fs.statSync = function(path) {}; /** * @param {string} path * @return {void} */ fs.unlinkSync = function(path) {}; /** * @param {string} filename * @param {*} data * @param {string=} encoding * @return {void} */ fs.writeFileSync = function(filename, data, encoding) {}; /** * @param {number} fd * @param {string} string * @param {number=} position * @param {string=} encoding * @return {number} */ fs.writeSync = function(fd, string, position, encoding) {}; /** @constructor @struct */ fs.Stats = function () {}; /** @return {boolean} */ fs.Stats.prototype.isFile; /** @return {boolean} */ fs.Stats.prototype.isDirectory; /** @return {boolean} */ fs.Stats.prototype.isBlockDevice; /** @return {boolean} */ fs.Stats.prototype.isCharacterDevice; /** @return {boolean} */ fs.Stats.prototype.isSymbolicLink; /** @return {boolean} */ fs.Stats.prototype.isFIFO; /** @return {boolean} */ fs.Stats.prototype.isSocket; /** @type {number} */ fs.Stats.prototype.dev = 0; /** @type {number} */ fs.Stats.prototype.ino = 0; /** @type {number} */ fs.Stats.prototype.mode = 0; /** @type {number} */ fs.Stats.prototype.nlink = 0; /** @type {number} */ fs.Stats.prototype.uid = 0; /** @type {number} */ fs.Stats.prototype.gid = 0; /** @type {number} */ fs.Stats.prototype.rdev = 0; /** @type {number} */ fs.Stats.prototype.size = 0; /** @type {number} */ fs.Stats.prototype.blkSize = 0; /** @type {number} */ fs.Stats.prototype.blocks = 0; /** @type {Date} */ fs.Stats.prototype.atime; /** @type {Date} */ fs.Stats.prototype.mtime; /** @type {Date} */ fs.Stats.prototype.ctime; module.exports = fs; ================================================ FILE: server/externs/fs/package.json ================================================ { "description": "Fake package.json for require('fs')", "main": "fs.js", "name": "fs", } ================================================ FILE: server/externs/http/http.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's http module to * satisfy Closure Compiler dependencies. This is mostly an * adaptation of contrib/nodejs/http.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. var Buffer = require('buffer').Buffer; var events = require('events'); var net = require('net'); var stream = require('stream'); /** @const */ var http = {}; /** * @typedef {function(http.IncomingMessage, http.ServerResponse)} */ http.requestListener; /** * @param {http.requestListener=} listener * @return {http.Server} */ http.createServer; /** * @constructor * @struct * @extends events.EventEmitter * @param {http.requestListener=} listener */ http.Server = function(listener) {}; /** * @param {(number|string)} portOrPath * @param {(string|Function)=} hostnameOrCallback * @param {Function=} callback */ http.Server.prototype.listen; /** * @return {void} */ http.Server.prototype.close; /** * @constructor * @struct * @extends stream.Readable */ http.IncomingMessage = function() {}; /** * @type {?string} * */ http.IncomingMessage.prototype.method; /** * @type {?string} */ http.IncomingMessage.prototype.url; /** * @type {Object} * */ http.IncomingMessage.prototype.headers; /** * @type {Object} * */ http.IncomingMessage.prototype.trailers; /** * @type {string} */ http.IncomingMessage.prototype.httpVersion; /** * @type {string} */ http.IncomingMessage.prototype.httpVersionMajor; /** * @type {string} */ http.IncomingMessage.prototype.httpVersionMinor; /** * @type {*} */ http.IncomingMessage.prototype.connection; /** * @type {?number} */ http.IncomingMessage.prototype.statusCode; /** * @type {net.Socket} */ http.IncomingMessage.prototype.socket; /** * @param {number} msecs * @param {function()} callback * @return {void} */ http.IncomingMessage.prototype.setTimeout; /** * @constructor * @struct * @extends events.EventEmitter * @private */ http.ServerResponse = function() {}; /** * @return {void} */ http.ServerResponse.prototype.writeContinue; /** * @param {number} statusCode * @param {*=} reasonPhrase * @param {*=} headers */ http.ServerResponse.prototype.writeHead; /** * @type {number} */ http.ServerResponse.prototype.statusCode; /** * @param {string} name * @param {string} value * @return {void} */ http.ServerResponse.prototype.setHeader; /** * @param {string} name * @return {string|undefined} value */ http.ServerResponse.prototype.getHeader; /** * @param {string} name * @return {void} */ http.ServerResponse.prototype.removeHeader; /** * @param {string|Array|Buffer} chunk * @param {string=} encoding * @return {void} */ http.ServerResponse.prototype.write; /** * @param {Object} headers * @return {void} */ http.ServerResponse.prototype.addTrailers; /** * @param {(string|Array|Buffer)=} data * @param {string=} encoding * @return {void} */ http.ServerResponse.prototype.end; /** * @constructor * @struct * @extends events.EventEmitter * @private */ http.ClientRequest = function() {}; /** * @param {string|Array|Buffer} chunk * @param {string=} encoding * @return {void} */ http.ClientRequest.prototype.write; /** * @param {(string|Array|Buffer)=} data * @param {string=} encoding * @return {void} */ http.ClientRequest.prototype.end; /** * @return {void} */ http.ClientRequest.prototype.abort; /** * @param {string|!Object} urlOrOptions * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback * @param {function(!http.IncomingMessage)=} callback * @return {http.ClientRequest} */ http.request = function(urlOrOptions, optionsOrCallback, callback) {}; /** * @param {string|!Object} urlOrOptions * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback * @param {function(!http.IncomingMessage)=} callback * @return {http.ClientRequest} */ http.get = function(urlOrOptions, optionsOrCallback, callback) {}; /** * @constructor * @struct * @extends events.EventEmitter */ http.Agent = function() {}; /** * @type {number} */ http.Agent.prototype.maxSockets; /** * @type {number} */ http.Agent.prototype.sockets; /** * @type {Array.} */ http.Agent.prototype.requests; /** * @type {http.Agent} */ http.globalAgent; module.exports = http; ================================================ FILE: server/externs/http/package.json ================================================ { "description": "Fake package.json for require('http')", "main": "http.js", "name": "http", } ================================================ FILE: server/externs/https/https.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's https module to * satisfy Closure Compiler dependencies. This is mostly an * adaptation of contrib/nodejs/https.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. var Buffer = require('buffer').Buffer; var http = require('http'); var tls = require('tls'); /** @const */ var https = {}; /** * @constructor * @struct * @extends tls.Server */ https.Server = function() {}; /** * @param {...*} var_args * @return {void} */ https.Server.prototype.listen; /** * @param {function()=} callback * @return {void} */ https.Server.prototype.close; /** * @param {tls.CreateOptions} options * @param {function(http.IncomingMessage, http.ServerResponse)=} requestListener * @return {!https.Server} */ https.createServer; /** * @typedef {{host: ?string, hostname: ?string, port: ?number, method: ?string, path: ?string, headers: ?Object., auth: ?string, agent: ?(https.Agent|boolean), pfx: ?(string|Buffer), key: ?(string|Buffer), passphrase: ?string, cert: ?(string|Buffer), ca: ?Array., ciphers: ?string, rejectUnauthorized: ?boolean}} */ https.ConnectOptions; /** * @param {string|!Object} urlOrOptions * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback * @param {function(!http.IncomingMessage)=} callback * @return {http.ClientRequest} */ https.request = function(urlOrOptions, optionsOrCallback, callback) {}; /** * @param {string|!Object} urlOrOptions * @param {!Object|function(!http.IncomingMessage)=} optionsOrCallback * @param {function(!http.IncomingMessage)=} callback * @return {http.ClientRequest} */ https.get = function(urlOrOptions, optionsOrCallback, callback) {}; /** * @constructor * @struct * @extends http.Agent */ https.Agent = function() {}; /** * @type {https.Agent} */ https.globalAgent; module.exports = https; ================================================ FILE: server/externs/https/package.json ================================================ { "description": "Fake package.json for require('https')", "main": "https.js", "name": "https", } ================================================ FILE: server/externs/net/net.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's net module to * satisfy Closure Compiler dependencies. * @author cpcallen@google.com (Christopher Allen) */ var Buffer = require('buffer').Buffer; var events = require('events'); var net = {}; /** * @typedef {{allowHalfOpen: ?boolean}} */ var createOptions; /** * @param {(createOptions|function(...))=} options * @param {function(...)=} connectionListener * @return {net.Server} */ net.createServer = function(options, connectionListener) {}; /** * @typedef {{port: (number|undefined), * host: (string|undefined), * localAddress: (string|undefined), * path: (string|undefined), * allowHalfOpen: (boolean|undefined)}} */ var connectOptions; /** * @param {connectOptions|number|string} arg1 * @param {(function(...)|string)=} arg2 * @param {function(...)=} arg3 * @return {!net.Socket} */ net.createConnection = function(arg1, arg2, arg3) {}; /////////////////////////////////////////////////////////////////////////////// // net.Server /** * @constructor * @struct * @param {createOptions=} options * @extends {events.EventEmitter} */ net.Server = function(options) {}; /** * @return {{port: number, family: string, address: string}} */ net.Server.prototype.address = function() {}; /** * @param {function(...)=} callback * @return {void} */ net.Server.prototype.close = function(callback) {}; /** * * @param {number|*} port * @param {(string|number|function(...))=} host * @param {(number|function(...))=} backlog * @param {function(...)=} callback * @return {void} */ net.Server.prototype.listen = function(port, host, backlog, callback) {}; /////////////////////////////////////////////////////////////////////////////// // net.Socket /** * @constructor * @struct * @param {{fd: ?*, type: ?string, allowHalfOpen: ?boolean}=} options * @extends events.EventEmitter */ net.Socket = function(options) {}; /** * @param {string|Buffer} data * @param {(string|function(...))=} encoding * @param {function(...)=} callback * @return {void} */ net.Socket.prototype.write = function(data, encoding, callback) {}; /** * @param {(string|Buffer)=} data * @param {(string|function(...))=} encoding * @param {function(...)=} callback * @return {void} */ net.Socket.prototype.end = function(data, encoding, callback) {}; module.exports = net; ================================================ FILE: server/externs/net/package.json ================================================ { "description": "Fake package.json for require('net')", "main": "net.js", "name": "net", } ================================================ FILE: server/externs/node.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Closure Compiler externs for node.js, mostly * excerpted from contrib/nodejs/globals.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) * @externs */ // TODO(cpcallen): Use official externs directly. /** @const {string} */ var __filename; /** @const {string} */ var __dirname; /** @type {!Object} */ var exports; /** @param {boolean=} full */ var gc = function(full) {}; /** @type {!Object} */ var module; /** * @param {string} name * @return {?} */ function require(name) {} /** @type {!Object} */ require.main; /** * @param {string} request * @param {!Object=} options * @return {string} */ require.resolve = function(request, options) {}; /////////////////////////////////////////////////////////////////////////////// // process /** @const */ var process = {}; /** @type {string} */ process.arch; /** @type {!Array} */ process.argv; /** @return {string} */ process.cwd = function () {}; /** @type {!Object} */ process.env; /** @param {number=} code */ process.exit = function (code) {}; /** * @param {!Array=} time * @return {!Array} */ process.hrtime = function(time) {}; /** * @param {number} pid * @param {string|number} signal */ process.kill = function (pid, signal) {}; /** * This is actually inherited from EventEmitter * (===require('events')), but redefined here since * closure-compiler won't let us require() that definition in an * externs file. * @param {string|symbol} event * @param {function(...)} listener */ process.on = function(event, listener) {}; /** * Also inherited from EventEmitter. * @param {string|symbol} event * @param {function(...)} listener */ process.once = function(event, listener) {}; /** @type {number} */ process.pid; /** @type {string} */ process.platform; /** @type {string} */ process.version; /** @type {!Object} */ process.versions; ================================================ FILE: server/externs/path/package.json ================================================ { "description": "Fake package.json for require('path')", "main": "path.js", "name": "path", } ================================================ FILE: server/externs/path/path.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's fs module to satisfy * Closure Compiler dependencies. This is mostly an excerpt from * contrib/nodejs/fs.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. /** @const */ var path = {}; /** * @param {string} path * @return {string} */ path.dirname = function(path) {}; /** * @param {string} path * @return {string} */ path.extname = function(path) {}; /** * @param {string} p * @return {boolean} */ path.isAbsolute = function(p) {}; /** * @param {...string} var_args * @return {string} */ path.join = function(var_args) {}; /** * @param {string} p * @return {string} */ path.normalize = function(p) {}; module.exports = path; ================================================ FILE: server/externs/stream/package.json ================================================ { "description": "Fake package.json for require('stream')", "main": "stream.js", "name": "stream", } ================================================ FILE: server/externs/stream/stream.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's stream module to * satisfy Closure Compiler dependencies. This is mostly an * adaptation of contrib/nodejs/stream.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. var events = require('events'); var Buffer = require('buffer').Buffer; /** @const */ var stream = {}; /** * @constructor * @struct * @extends events.EventEmitter * @param {Object=} options */ stream.Stream = function(options) {}; /** * @param {stream.Writable} dest * @param {{end: boolean}=} pipeOpts * @return {stream.Writable} */ stream.Stream.prototype.pipe; /** * @constructor * @struct * @extends stream.Stream * @param {Object=} options */ stream.Readable = function(options) {}; /** * @type {boolean} * @deprecated */ stream.Readable.prototype.readable; /** * @protected * @param {string|Buffer|null} chunk * @return {boolean} */ stream.Readable.prototype.push; /** * @param {string|Buffer|null} chunk * @return {boolean} */ stream.Readable.prototype.unshift; /** * @param {string} enc * @return {void} */ stream.Readable.prototype.setEncoding; /** * @param {number=} n * @return {Buffer|string|null} */ stream.Readable.prototype.read; /** * @protected * @param {number} n * @return {void} */ stream.Readable.prototype._read; /** * @param {stream.Writable=} dest * @return {stream.Readable} */ stream.Readable.prototype.unpipe; /** * @return {void} */ stream.Readable.prototype.resume; /** * @return {void} */ stream.Readable.prototype.pause; /** * @param {stream.Stream} stream * @return {stream.Readable} */ stream.Readable.prototype.wrap; /** * @constructor * @struct * @extends stream.Readable */ stream.ReadableStream = function() {}; /** * @type {boolean} */ stream.ReadableStream.prototype.readable; /** * @param {string=} encoding * @return {void} */ stream.ReadableStream.prototype.setEncoding; /** * @return {void} */ stream.ReadableStream.prototype.destroy; /** * @constructor * @struct * @extends stream.Stream * @param {Object=} options */ stream.Writable = function(options) {}; /** * @deprecated * @type {boolean} */ stream.Writable.prototype.writable; /** * @param {string|Buffer} chunk * @param {string=} encoding * @param {function(*=)=} cb * @return {boolean} */ stream.Writable.prototype.write; /** * @protected * @param {string|Buffer} chunk * @param {string} encoding * @param {function(*=)} cb * @return {void} */ stream.Writable.prototype._write; /** * @param {string|Buffer=} chunk * @param {string=} encoding * @param {function(*=)=} cb * @return {void} */ stream.Writable.prototype.end; /** * @constructor * @struct * @extends stream.Writable */ stream.WritableStream = function() {}; /** * @return {void} */ stream.WritableStream.prototype.drain; /** * @type {boolean} */ stream.WritableStream.prototype.writable; /** * @param {string|Buffer} buffer * @param {string=} encoding * @return {void} */ stream.WritableStream.prototype.write; /** * @param {string|Buffer=} buffer * @param {string=} encoding * @param {function(*=)=} cb * @return {void} */ stream.WritableStream.prototype.end; /** * @return {void} */ stream.WritableStream.prototype.destroy; /** * @return {void} */ stream.WritableStream.prototype.destroySoon; /** * @constructor * @struct * @extends stream.Readable */ stream.Duplex = function(options) {}; /** * @type {boolean} */ stream.Duplex.prototype.allowHalfOpen; /** * @constructor * @struct * @extends stream.Duplex * @param {Object=} options */ stream.Transform = function(options) {}; /** * @protected * @param {string|Buffer} chunk * @param {string} encoding * @param {function(*=)} cb * @return {void} */ stream.Transform._transform; /** * @protected * @param {function(*=)} cb * @return {void} */ stream.Transform._flush; /** * @constructor * @struct * @extends stream.Transform * @param {Object=} options */ stream.PassThrough = function(options) {}; module.exports = stream; ================================================ FILE: server/externs/tls/package.json ================================================ { "description": "Fake package.json for require('tls')", "main": "tls.js", "name": "tls", } ================================================ FILE: server/externs/tls/tls.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's tls module to * satisfy Closure Compiler dependencies. This is mostly an * excerpt of contrib/nodejs/tls.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. var Buffer = require('buffer').Buffer; var events = require('events'); var net = require('net'); var stream = require('stream'); /** * @const */ var tls = {}; /** * @constructor * @struct * @extends stream.Stream */ tls.CreateOptions = function () {}; /** @type {boolean} */ tls.CreateOptions.prototype.honorCipherOrder; /** @type {boolean} */ tls.CreateOptions.prototype.requestCert; /** @type {boolean} */ tls.CreateOptions.prototype.rejectUnauthorized; /** @type {Array|Buffer} */ tls.CreateOptions.prototype.NPNProtocols; /** @type {function(string)} */ tls.CreateOptions.prototype.SNICallback; /** @type {string} */ tls.CreateOptions.prototype.sessionIdContext; /** * * @param {tls.CreateOptions} options * @param {function(...)=} secureConnectionListener * @return {tls.Server} */ tls.createServer; /** * @typedef {{host: string, port: number, socket: *, pfx: (string|Buffer), key: (string|Buffer), passphrase: string, cert: (string|Buffer), ca: Array., rejectUnauthorized: boolean, NPNProtocols: Array., servername: string}} */ tls.ConnectOptions; /** * * @param {number|tls.ConnectOptions} port * @param {(string|tls.ConnectOptions|function(...))=} host * @param {(tls.ConnectOptions|function(...))=} options * @param {function(...)=} callback * @return {void} */ tls.connect = function(port, host, options, callback) {}; // Don't need this yet, and don't have externs for crypto yet. // /** // * @param {crypto.Credentials=} credentials // * @param {boolean=} isServer // * @param {boolean=} requestCert // * @param {boolean=} rejectUnauthorized // * @return {tls.SecurePair} // */ // tls.createSecurePair; /** * @constructor * @struct * @extends events.EventEmitter */ tls.SecurePair = function() {}; /** * @constructor * @struct * @extends net.Server */ tls.Server = function() {}; /** * @param {string} hostname * @param {string|Buffer} credentials * @return {void} */ tls.Server.prototype.addContext = function(hostname, credentials) {}; /** * @constructor * @struct * @extends stream.Duplex */ tls.CleartextStream = function() {}; /** * @type {boolean} */ tls.CleartextStream.prototype.authorized; /** * @type {?string} */ tls.CleartextStream.prototype.authorizationError; /** * @return {Object.)>} */ tls.CleartextStream.prototype.getPeerCertificate; /** * @return {{name: string, version: string}} */ tls.CleartextStream.prototype.getCipher; /** * @return {{port: number, family: string, address: string}} */ tls.CleartextStream.prototype.address; /** * @type {string} */ tls.CleartextStream.prototype.remoteAddress; /** * @type {number} */ tls.CleartextStream.prototype.remotePort; module.exports = tls; ================================================ FILE: server/externs/util/package.json ================================================ { "description": "Fake package.json for require('util')", "main": "util.js", "name": "util", } ================================================ FILE: server/externs/util/util.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Fake implementation of node.js's fs module to satisfy * Closure Compiler dependencies. This is mostly an excerpt from * contrib/nodejs/fs.js from * https://github.com/google/closure-compiler.git * @author cpcallen@google.com (Christopher Allen) */ // TODO(cpcallen): Use official externs directly. /** @const */ var util = {}; /** * @param {*} object * @param {?util.inspect.Options=} options * @return {string} */ util.inspect = function(object, options) {}; /** * @const {symbol} */ util.inspect.custom; /** * @typedef {{showHidden: (boolean|undefined), * depth: (number|null|undefined), * colors: (boolean|undefined), * customInspect: (boolean|undefined), * showProxy: (boolean|undefined), * maxArrayLength: (number|undefined), * maxStringLength: (number|undefined), * breakLength: (number|undefined), * compact: (boolean|number|undefined), * sorted: (boolean|!Function|undefined)}} */ util.inspect.Options; /** * @param {string} format * @param {...*} var_args * @return {string} */ util.format = function(format, var_args) {}; module.exports = util; ================================================ FILE: server/interpreter.js ================================================ /** * @license * Copyright 2013 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Interpreting JavaScript in JavaScript. * @author fraser@google.com (Neil Fraser) */ 'use strict'; var events = require('events'); var IterableWeakMap = require('./iterable_weakmap'); var net = require('net'); var http = require('http'); var https = require('https'); var parser = require('./parser'); var Registry = require('./registry'); var Node = parser.Node; var Parser = parser.Parser; /** * Version number for the serialisation format. MUST be incremented * when any change is made to the implementation of Interpreter and * related classes (in this file and others) which would change how * the runtime state is represented on disk. * @type {number} */ var SERIALIZATION_VERSION = 1; /** * Create a new interpreter. * @constructor * @struct * @param {!Interpreter.Options=} options */ var Interpreter = function(options) { /** @type {!Interpreter.Options} */ this.options = options || {}; /** * Serialisation version for this Interpreter instance. Will be set * to SERIALIZATION_VERSION, but not here, because there exist .city * files that have no .serlizationVersion in them, and loading one * won't overwrite what we set here. Instead, set it in * .preSerialize, and check in in .postDeserialize. * @type {number|undefined} */ this.serializationVersion = undefined; // Install .Object, .Function, etc. this.installTypes(); /** * Registry of builtins - e.g. Object, Function.prototype, Array.pop, etc. * @const {!Registry} */ this.builtins = new Registry; /** * For cycle detection in Array.prototype.toString; see spec bug * github.com/tc39/ecma262/issues/289. (Also used in * Error.prototype.toString, which has same issue.) Since these * functions are atomic (i.e., take place entirely within the * duration of a single call to .step) and do not call user code * which could suspend, it's fine that it's not per-Thread. * @private @const {!Set} */ this.toStringVisited_ = new Set; /** * The interpreter's global scope. * @const {!Interpreter.Scope} */ this.global = new Interpreter.Scope(Interpreter.Scope.Type.GLOBAL, /** @type {?} */ (undefined), null, undefined); // Declare properties that wil be initialised by initBuiltins_. /** @type {!Interpreter.prototype.Object} */ this.OBJECT; /** @type {!Interpreter.Owner} */ this.ROOT; /** @type {!Interpreter.prototype.Function} */ this.FUNCTION; /** @type {!Interpreter.prototype.Array} */ this.ARRAY; /** @type {!Interpreter.prototype.Object} */ this.STRING; /** @type {!Interpreter.prototype.Object} */ this.BOOLEAN; /** @type {!Interpreter.prototype.Object} */ this.NUMBER; /** @type {!Interpreter.prototype.Object} */ this.DATE; /** @type {!Interpreter.prototype.Object} */ this.REGEXP; /** @type {!Interpreter.prototype.Error} */ this.ERROR; /** @type {!Interpreter.prototype.Error} */ this.EVAL_ERROR; /** @type {!Interpreter.prototype.Error} */ this.RANGE_ERROR; /** @type {!Interpreter.prototype.Error} */ this.REFERENCE_ERROR; /** @type {!Interpreter.prototype.Error} */ this.SYNTAX_ERROR; /** @type {!Interpreter.prototype.Error} */ this.TYPE_ERROR; /** @type {!Interpreter.prototype.Error} */ this.URI_ERROR; /** @type {!Interpreter.prototype.Error} */ this.PERM_ERROR; /** @type {!Interpreter.prototype.Object} */ this.WEAKMAP; /** @type {!Interpreter.prototype.Object} */ this.THREAD; /** @type {!Interpreter.Owner} */ this.ANYBODY; // Create builtins and (minimally) initialize global scope: this.initBuiltins_(); /** @private @const {!Array} */ this.threads_ = []; /** @private @type {?Interpreter.Thread} */ this.thread_ = null; /** @private @type {number|undefined} */ this.threadTimeLimit_ = undefined; /** @private (Type is whatever is returned by setTimeout()) */ this.runner_ = null; /** @type {boolean} */ this.done = true; // True if no non-ZOMBIE threads exist. // TODO(cpcallen): rename this to .listeners /** @const {!Object} */ this.listeners_ = Object.create(null); // TODO(cpcallen): This is an ugly hack to allow the serialiser to // know the names of step functions in an otherwise-empty // interpreter. Find a better way to do this. /** @const {!Object} */ this.stepFuncs = stepFuncs_; // Bring interpreter up to PAUSED status, setting up timers etc. /** @type {!Interpreter.Status} */ this.status = Interpreter.Status.STOPPED; /** @private @type {number} */ this.previousTime_ = 0; /** @private @type {number} */ this.cumulativeTime_ = 0; /** @private @type {!Array} */ this.hrStartTime_; // Initialised by pause. this.pause(); }; /** * Return a monotonically increasing count of milliseconds since this * Interpreter was last brought to PAUSED or RUNNING status from * STOPPED. This excludes time when Node was suspended by the host OS * (say, because the machine was asleep). * @return {number} Elapsed time in milliseconds. */ Interpreter.prototype.uptime = function() { var t = process.hrtime(this.hrStartTime_); return t[0] * 1000 + t[1] / 1000000; }; /** * Return a monotonically increasing count of milliseconds since this * Interpreter instance was created. In the event of an interpreter * being serialized / deserialized, this count will continue from * where it left off before serialization. * @return {number} Elapsed total time in milliseconds. */ Interpreter.prototype.now = function() { return this.uptime() + this.previousTime_; }; /** * Create a new thread and add it to .threads_, and create a companion * user-visible wrapper object and return it. * @param {!Interpreter.Owner} owner Owner of new thread. * @param {!Interpreter.State} state Initial state * @param {number=} runAt Time at which thread should begin execution * (default: now). * @param {number=} timeLimit Maximum runtime without suspending (in ms). * @return {!Interpreter.prototype.Thread} Userland Thread object. */ Interpreter.prototype.createThread = function(owner, state, runAt, timeLimit) { var id = this.threads_.length; var thread = new Interpreter.Thread(id, state, runAt || this.now(), timeLimit); this.threads_[this.threads_.length] = thread; this.go_(); return new this.Thread(thread, owner); }; /** * Create a new thread to execute arbitrary JavaScript code. Thread * will have specified owner, but code will be evaluated directly in * global scope and will consequently runs wit whatever permissions * the global scope has. * @param {string} src JavaScript source code to parse and run. * @param {number=} timeLimit Maximum runtime without suspending (in ms). * @return {!Interpreter.prototype.Thread} Userland Thread object. */ Interpreter.prototype.createThreadForSrc = function(src, timeLimit) { if (typeof src !== 'string') throw new TypeError('src must be a string'); if (this.options.trimProgram) { src = src.trim(); } var ast = this.compile_(src); this.populateScope_(ast, this.global); var state = new Interpreter.State(ast, this.global); return this.createThread(this.ROOT, state, undefined, timeLimit); }; /** * Create a new thread to execute a particular function call. * @param {!Interpreter.Owner} owner Owner of new thread; also becomes * caller perms of function. * @param {!Interpreter.prototype.Function} func Function to call. * @param {?Interpreter.Value} thisVal value of 'this' in function call. * @param {!Array} args Arguments to pass. * @param {number=} runAt Time at which thread should begin execution * (default: now). * @param {number=} timeLimit Maximum runtime without suspending (in ms). * @return {!Interpreter.prototype.Thread} Userland Thread object. */ Interpreter.prototype.createThreadForFuncCall = function( owner, func, thisVal, args, runAt, timeLimit) { var state = Interpreter.State.newForCall(func, thisVal, args, owner); return this.createThread(owner, state, runAt, timeLimit); }; /** * Schedule the next runnable thread. Returns 0 if a READY thread * successfuly scheduled (or if the current thread was already * runnable, which can happen when interpreter has just been * deserialised); otherwise returns earliest .runAt time * amongst SLEEPING threads (if any), or Number.MAX_VALUE if there are * none. If there are additionally no BLOCKED threads left (i.e., * there are no non-ZOMBIE theads at all) it will also set .done to * true. * @return {number} See description. */ Interpreter.prototype.schedule = function() { if (this.thread_ && this.thread_.status === Interpreter.Thread.Status.READY) { return 0; // Nothing to do. Don't reset .threadTimeLimit_! } var now = this.now(); var runAt = Number.MAX_VALUE; var threads = this.threads_; // Assume all remaining threads are ZOMBIEs until proven otherwise. this.done = true; this.thread_ = null; // .threads_ will be very sparse, so use for-in loop. for (var i in threads) { i = Number(i); // Make Closure Compiler happy. if (!threads.hasOwnProperty(i)) { continue; } switch (threads[i].status) { case Interpreter.Thread.Status.ZOMBIE: // Remove zombie from threads. delete threads[i]; continue; case Interpreter.Thread.Status.BLOCKED: // Ignore blocked threads except noting existence. this.done = false; continue; case Interpreter.Thread.Status.SLEEPING: if (threads[i].runAt > now) { runAt = Math.min(runAt, threads[i].runAt); this.done = false; continue; } // Done sleeping; wake thread. threads[i].status = Interpreter.Thread.Status.READY; // fall through case Interpreter.Thread.Status.READY: // Is this this most-overdue thread found so far? if (threads[i].runAt < runAt) { this.thread_ = threads[i]; runAt = this.thread_.runAt; } this.done = false; break; default: throw new Error('Unknown thread state'); } } this.threadTimeLimit_ = (this.thread_ && this.thread_.timeLimit) ? now + this.thread_.timeLimit : undefined; return runAt < now ? 0 : runAt; }; /** * Execute one step of the interpreter. Schedules the next runnable * thread if required. * @return {boolean} True if a step was executed, false if no more * READY threads. */ Interpreter.prototype.step = function() { /* NOTE: Beware that an async (user) Function might reject * immediately, unwinding the stack before the Call step function * returns. */ if (this.status !== Interpreter.Status.PAUSED) { throw new Error('Can only step paused interpreter'); } if (!this.thread_ || this.thread_.status !== Interpreter.Thread.Status.READY) { if (this.schedule() > 0) { return false; } } if (!this.thread_) throw new Error('Scheduling failed'); // Satisfy compiler. this.step_(this.thread_, this.thread_.stateStack_); return true; }; /** * Execute the interpreter to program completion. Vulnerable to * infinite loops. Alternates between waking any past-due SLEEPING * threads and running the most-overdue READY thread until there are * no more READY threads, then returns an integer as follows: * * - If there are SLEEPING threads, then a positive number that is the * smallest .runAt value of any sleeping thread. * - If there are no SLEEPING threads, but there are BLOCKED threads * then a negative number is returned. * - If only ZOMBIE threads remain, then zero is returned. * @return {number} See description. */ Interpreter.prototype.run = function() { /* NOTE: Beware that an async (user) Function might reject * immediately, unwinding the stack before the Call step function * returns. */ if (this.status === Interpreter.Status.STOPPED) { throw new Error("Can't run stopped interpreter"); } var t; while ((t = this.schedule()) === 0) { var thread = this.thread_; var stack = thread.stateStack_; while (thread.status === Interpreter.Thread.Status.READY) { this.step_(thread, stack); } } if (t === Number.MAX_VALUE) { return this.done ? 0 : -1; } return t; }; /** * Actually execute one step of the interpreter. Presumes thread is * the currently-scheduled thread, is runnable, etc. * @private * @param {!Interpreter.Thread} thread The current thread. * @param {!Array} stack The current thread's state stack. */ Interpreter.prototype.step_ = function(thread, stack) { var state = stack[stack.length - 1]; var node = state.node; try { var nextState = state.stepFunc.call(this, thread, stack, state, node); } catch (e) { this.throw_(thread, e, state.scope.perms); nextState = undefined; } if (nextState) { stack[stack.length] = nextState; } if (stack.length === 0) { thread.status = Interpreter.Thread.Status.ZOMBIE; } }; /** * If interpreter status is RUNNING, use setTimeout to arrange for * .run() to be called repeatedly until there are no more sleeping * threads. * @private */ Interpreter.prototype.go_ = function() { // Ignore calls to .go_ when PAUSED or STOPPED if (this.status !== Interpreter.Status.RUNNING) { return; } // Kill any existing runner and restart. if (this.runner_) clearTimeout(this.runner_); var intrp = this; this.runner_ = setTimeout(function runner() { // Invariant check: pausing or stopping interpreter should cancel // timeout, so we should never get here while it is not RUNNING. if (intrp.status !== Interpreter.Status.RUNNING) { throw new Error('Un-cancelled runner on non-RUNNING interpreteter'); } // N.B.: .run may indirectly call .go_ or even .pause or .stop // (e.g. via native function calling .createThread, .pause, etc.). var r = intrp.run(); if (intrp.runner_) { // Clear any outstanding timeout. This might be the // just-completed one that called this invocation of runner, but // it might be a new one created by a reentrant call to .go_ // (e.g. via .run -> [native function] -> .createThread). clearTimeout(intrp.runner_); intrp.runner_ = null; } if (r > 0 && intrp.status === Interpreter.Status.RUNNING) { // No more code to run right now, but there is an outstanding // userland timeout, so set up a future reinvocation of runner // when it's time for that to run. intrp.runner_ = setTimeout(runner, r - intrp.now()); } }); }; /** * Set the interpreter status to RUNNING and kick it into action if * there is anything to do. */ Interpreter.prototype.start = function() { if (this.status !== Interpreter.Status.RUNNING) { // Take care of STOPPED -> PAUSED transition if required. this.pause(); } this.status = Interpreter.Status.RUNNING; this.go_(); }; /** * Set the interpreter status to PAUSED. If it was previously * STOPPED, begin listening on any listened ports. If it was * previously RUNNING, ensure the interpreter takes no further action * of its own. * * Call this function before serializing a RUNNING or PAUSED * interpreter to ensure correct timer restoration when deserializing. * (No need to call it if instance is already STOPPED.) */ Interpreter.prototype.pause = function() { switch (this.status) { case Interpreter.Status.RUNNING: clearTimeout(this.runner_); this.runner_ = null; this.cumulativeTime_ = this.now(); // Save elapsed time. break; case Interpreter.Status.PAUSED: // No state change; just update elapsed time. this.cumulativeTime_ = this.now(); break; case Interpreter.Status.STOPPED: // Re-listen to any previously listened ports: for (var port in this.listeners_) { var intrp = this; var server = this.listeners_[Number(port)]; server.listen(function(error) { if (!error) return; // Something went wrong while re-listening. Maybe port in use. intrp.log('net', 'Re-listen on port %s failed: %s: %s', server.port, error.name, error.message); // Report this to userland by calling .onError on proto // (with this === proto) - for lack of a better option. if (!server.owner) return; var func = server.proto.get('onError', server.owner); if (!(func instanceof intrp.Function)) return; var userError = intrp.errorNativeToPseudo(error, server.owner); // TODO(cpcallen:perms): Is server.owner the correct owner // for this thread? Note that this will typically be root, // and .onError will therefore get caller perms === root, // which is probably dangerous. intrp.createThreadForFuncCall( server.owner, func, server.proto, [userError], undefined, server.timeLimit); }); } // Reset .uptime() to start counting from *NOW*, and .now() to // continue from where it was before the interpreter was stopped. this.previousTime_ = this.cumulativeTime_; this.hrStartTime_ = process.hrtime(); } this.status = Interpreter.Status.PAUSED; }; /** * Set the interpreter status to STOPPED, stop listening on any port * (but do not close any open sockets), and ensure the interpreter * takes no further action of its own. */ Interpreter.prototype.stop = function() { if (this.status === Interpreter.Status.STOPPED) { return; } // Do RUNNING -> PAUSED transition if required; update elapsed time. this.pause(); // Unlisten to network sockets. for (var port in this.listeners_) { this.listeners_[Number(port)].unlisten(); } this.status = Interpreter.Status.STOPPED; }; /** * Prepare an interpreter to be seralized. */ Interpreter.prototype.preSerialize = function() { // As noted in constructor: set .seralizationVersion only just // before serialising, so as to avoid mistaking old, un-versioned // .city files for the current version. this.serializationVersion = SERIALIZATION_VERSION; }; /** * Prepare an interpreter to run after being deseralized. */ Interpreter.prototype.postDeserialize = function() { // Check to make sure deseralised interpreter is compatible with the // current implementation. if (this.serializationVersion !== SERIALIZATION_VERSION) { throw new Error('version error: seralized interpreter was version ' + this.serializationVersion + '; current version is ' + SERIALIZATION_VERSION); } // Checkpointed interpreter was probably paused, but because we're // restoring from a checkpoint the resurrected interpreter is // actually stopped (i.e., with no listening sockets, and with // questionable timer state information). this.status = Interpreter.Status.STOPPED; }; /** * Convert source code into a ready-to-execute parse tree. * @private * @param {string} src The source code to be compiled. * @param {!Interpreter.Owner=} perms Re-throw parse errors as * user errors owned by perms. (Default: re-throw parse * errors as internal (native) errors.) * @return {!Node} node Root AST node. */ Interpreter.prototype.compile_ = function(src, perms) { try { var ast = Parser.parse(src); } catch (e) { // Acorn threw a SyntaxError. Rethrow as a trappable error? throw perms ? this.errorNativeToPseudo(e, perms) : e; } (function analyse(node) { for (var name in node) { // Recursively analyse subtrees. var prop = node[name]; if (prop && typeof prop !== 'object') continue; if (Array.isArray(prop)) { for (var i = 0; i < prop.length; i++) { if (prop[i] && prop[i] instanceof Node) { analyse(prop[i]); } } } else { if (prop instanceof Node) { analyse(prop); } } } // Populate props on this node. node['stepFunc'] = stepFuncs_[node['type']]; })(ast); ast['source'] = new Interpreter.Source(src); return ast; }; /** * Create and register the builtin classes and functions specified in * the ECMAScript specification plus our extensions. Add a few items * (e.g., eval) to the global scope that can't be added any other way. * @private */ Interpreter.prototype.initBuiltins_ = function() { // Initialize uneditable global properties. this.global.createImmutableBinding('NaN', NaN); this.global.createImmutableBinding('Infinity', Infinity); this.global.createImmutableBinding('undefined', undefined); // Create the objects which will become Object.prototype and // Function.prototype, which are needed to bootstrap everything else. this.OBJECT = new this.Object(null, null); this.builtins.set('Object.prototype', this.OBJECT); // Create the object that will own all of the system objects. var root = new this.Object(null, this.OBJECT); this.ROOT = /** @type {!Interpreter.Owner} */ (root); this.builtins.set('CC.root', root); this.global.perms = this.ROOT; // Retroactively apply root ownership to Object.prototype: this.OBJECT.owner = this.ROOT; // NativeFunction constructor adds new function to the map of builtins. this.FUNCTION = new this.NativeFunction({ id: 'Function.prototype', name: '', length: 0, proto: this.OBJECT, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) {/* do nothing */} }); // Initialize global objects. this.initObject_(); this.initFunction_(); this.initArray_(); this.initString_(); this.initBoolean_(); this.initNumber_(); this.initDate_(); this.initRegExp_(); this.initError_(); this.initMath_(); this.initJSON_(); this.initWeakMap_(); this.initPerms_(); // Initialize ES standard global functions. var eval_ = new this.NativeFunction({ id: 'eval', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var code = args[0]; var perms = state.scope.perms; if (intrp.options.trimEval) { code = code.trim(); } if (typeof code !== 'string') { // eval() // Eval returns the argument if the argument is not a string. // eval(Array) -> Array return code; } var ast = intrp.compile_(code, perms); // Change node type from Program to EvalProgram_. ast['type'] = 'EvalProgram_'; ast['stepFunc'] = stepFuncs_['EvalProgram_']; // Create new scope and update it with definitions in eval(). var outerScope = state.info_.directEval ? state.scope : intrp.global; var scope = new Interpreter.Scope(Interpreter.Scope.Type.EVAL, perms, outerScope); intrp.populateScope_(ast, scope); thread.stateStack_[thread.stateStack_.length] = new Interpreter.State(ast, scope); thread.value = undefined; // In case no ExpressionStatements evaluated. return Interpreter.FunctionResult.AwaitValue; } }); // eval is a special case; it must be added to the global scope at // startup time (rather than by a "var eval = new 'eval';" statement // in es5.js) because assigning to eval is illegal in strict mode. // This also means that it is effectively immutable despite being // created with createMutableBinding. this.global.createMutableBinding('eval', eval_); this.createNativeFunction('isFinite', isFinite, false); this.createNativeFunction('isNaN', isNaN, false); this.createNativeFunction('parseFloat', parseFloat, false); this.createNativeFunction('parseInt', parseInt, false); var strFunctions = [ [escape, 'escape'], [unescape, 'unescape'], [decodeURI, 'decodeURI'], [decodeURIComponent, 'decodeURIComponent'], [encodeURI, 'encodeURI'], [encodeURIComponent, 'encodeURIComponent'] ]; var intrp = this; for (var i = 0; i < strFunctions.length; i++) { var wrapper = (function(nativeFunc) { return function(str) { try { return nativeFunc(str); } catch (e) { // decodeURI('%xy') will throw an error. Catch and rethrow. throw intrp.errorNativeToPseudo(e, intrp.thread_.perms()); } }; })(strFunctions[i][0]); this.createNativeFunction(strFunctions[i][1], wrapper, false); } // Initialize CC-specific globals. this.initThread_(); this.initNetwork_(); }; /** * Initialize the Object class. * @private */ Interpreter.prototype.initObject_ = function() { // Object constructor. new this.NativeFunction({ id: 'Object', length: 1, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { var value = args[0]; if (value instanceof intrp.Object) { return value; } else if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') { // No boxed primitives in Code City. throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'boxed primitives not supported'); } else if (value === undefined || value === null) { return new intrp.Object(state.scope.perms); } else { throw new TypeError('Unknown value type??'); } }, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return this.construct.call(this, intrp, thread, state, args); } }); // Static methods on Object. this.createNativeFunction('Object.is', Object.is, false); new this.NativeFunction({ id: 'Object.getOwnPropertyNames', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; // N.B.: we use ES6 definition; ES5.1 would throw TypeError if // passed a non-object. var obj = intrp.toObject(args[0], perms); return intrp.createArrayFromList(obj.ownKeys(perms), perms); } }); new this.NativeFunction({ id: 'Object.keys', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(args[0], perms); var keys = obj.ownKeys(perms); var enumerableKeys = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var pd = obj.getOwnPropertyDescriptor(key, perms); if (pd.enumerable) enumerableKeys.push(key); } return intrp.createArrayFromList(enumerableKeys, perms); } }); new this.NativeFunction({ id: 'Object.create', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var proto = args[0]; // Support for the second argument is the responsibility of a polyfill. if (proto === null) { return new intrp.Object(state.scope.perms, null); } if (!(proto === null || proto instanceof intrp.Object)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Object prototype may only be an Object or null'); } return new intrp.Object(state.scope.perms, proto); } }); new this.NativeFunction({ id: 'Object.defineProperty', length: 3, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; var key = args[1]; var attr = args[2]; var perms = state.scope.perms; if (!(obj instanceof intrp.Object)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Object.defineProperty called on non-object'); } key = String(key); if (!(attr instanceof intrp.Object)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Property description must be an object'); } // Can't just use pseudoToNative since descriptors can inherit properties. var desc = new Descriptor; if (attr.has('configurable', perms)) { desc.configurable = Boolean(attr.get('configurable', perms)); } if (attr.has('enumerable', perms)) { desc.enumerable = Boolean(attr.get('enumerable', perms)); } if (attr.has('writable', perms)) { desc.writable = Boolean(attr.get('writable', perms)); } if (attr.has('value', perms)) { desc.value = attr.get('value', perms); } obj.defineProperty(key, desc, perms); return obj; } }); new this.NativeFunction({ id: 'Object.getOwnPropertyDescriptor', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; var prop = args[1]; var perms = state.scope.perms; if (!(obj instanceof intrp.Object)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Object.getOwnPropertyDescriptor called on non-object'); } prop = String(prop); var pd = obj.getOwnPropertyDescriptor(prop, perms); if (!pd) { return undefined; } var descriptor = new intrp.Object(perms); descriptor.set('configurable', pd.configurable, perms); descriptor.set('enumerable', pd.enumerable, perms); descriptor.set('writable', pd.writable, perms); descriptor.set('value', pd.value, perms); return descriptor; } }); new this.NativeFunction({ id: 'Object.getPrototypeOf', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { // N.B.: This conforms to ES6. ES5.1 would throw TypeError for // Object.getPrototypeOf() var o = intrp.toObject(args[0], state.scope.perms); return o.proto; } }); new this.NativeFunction({ id: 'Object.setPrototypeOf', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; var proto = args[1]; var perms = state.scope.perms; if (obj === null || obj === undefined) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Object.setPrototypeOf called on null or undefined'); } if (proto !== null && !(proto instanceof intrp.Object)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Object prototype may only be an Object or null'); } if (obj instanceof intrp.Object) { // obj.setPrototypeOf handles security and circularity checks. if (!obj.setPrototypeOf(proto, perms)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'setPrototypeOf failed'); } } return obj; } }); new this.NativeFunction({ id: 'Object.isExtensible', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; if (!(obj instanceof intrp.Object)) { return false; // ES6 §19.1.2.11. ES5.1 would throw TypeError. } return obj.isExtensible(state.scope.perms); } }); new this.NativeFunction({ id: 'Object.preventExtensions', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; var perms = state.scope.perms; if (!(obj instanceof intrp.Object)) { return obj; // ES6 §19.1.2.15. ES5.1 would throw TypeError. } if (!obj.preventExtensions(perms)) { // Can only happen once we have Proxy objects. throw new intrp.Error(perms, intrp.TYPE_ERROR, obj.toString() + " can't be made non-extensible."); } return obj; } }); // Properties of the Object prototype object. this.createNativeFunction('Object.prototype.toString', this.Object.prototype.toString, false); this.createNativeFunction('Object.prototype.toLocaleString', this.Object.prototype.toLocaleString, false); this.createNativeFunction('Object.prototype.valueOf', this.Object.prototype.valueOf, false); new this.NativeFunction({ id: 'Object.prototype.hasOwnProperty', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var key = args[0]; var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); return Boolean(obj.getOwnPropertyDescriptor(String(key), perms)); } }); new this.NativeFunction({ id: 'Object.prototype.propertyIsEnumerable', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var key = String(args[0]); var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var desc = obj.getOwnPropertyDescriptor(key, perms); if (desc === undefined) { return false; } return desc.enumerable; } }); new this.NativeFunction({ id: 'Object.prototype.isPrototypeOf', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var v = args[0]; if (!(v instanceof intrp.Object)) return false; var o = intrp.toObject(thisVal, state.scope.perms); while (true) { v = v.proto; if (v === null) return false; // No parent; reached the top. if (o === v) return true; } } }); }; /** * Initialize the Function class. * @private */ Interpreter.prototype.initFunction_ = function() { var intrp = this; var wrapper; // Function constructor. new this.NativeFunction({ id: 'Function', length: 1, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { args = args.slice(); // Copy, so we can .pop safely. var body = args.length ? String(args.pop()) : ''; // Concatenate formal parameter names. Let Acorn verify they // are valid Identifiers. var argsStr = args.map(function(arg) {return String(arg);}).join(','); // Acorn needs to parse body in the context of a function or // else 'return' statements will be syntax errors. The name // "anonymous" and extra line breaks were standardised in ES2019 // via https://tc39.es/Function-prototype-toString-revision/ var source = '(function anonymous(' + argsStr + '\n) {\n' + body + '\n})'; var ast = intrp.compile_(source, state.scope.perms); if (ast['body'].length !== 1) { // Function('a', 'return a + 6;}; {alert(1);'); // TODO: there must be a cleaner way to detect this! throw new intrp.Error(state.scope.perms, intrp.SYNTAX_ERROR, 'Invalid code in function body'); } // Interestingly, the scope for constructed functions is the global // scope, even if they were constructed in some other scope. return new intrp.UserFunction(ast['body'][0]['expression'], intrp.global, new Interpreter.Source(source), state.scope.perms); }, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return this.construct.call(this, intrp, thread, state, args); } }); // Properties of the Function prototype object. new this.NativeFunction({ id: 'Function.prototype.toString', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var func = thisVal; if (!(func instanceof intrp.Function)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Function.prototype.toString is not generic'); } // TODO(cpcallen:perms): Perm check here? Or in toString? return func.toString(); } }); new this.NativeFunction({ id: 'Function.prototype.apply', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var func = thisVal; var thisArg = args[0]; var argArray = args[1]; var perms = state.scope.perms; if (!(func instanceof intrp.Function)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, func + ' is not a function'); } else if (argArray === null || argArray === undefined) { var argList = []; } else { argList = intrp.createListFromArrayLike(argArray, perms); } // Rewrite state.info_, as a short-circuit optimisation in case // we get called again due to FunctionResult.CallAgain, and also // to produce more useful callers() output / stack traces. var info = state.info_; info.func = func; info.this = thisArg; info.args = argList; info.construct = false; // But just go and do the first .call directly. return func.call(intrp, thread, state, thisArg, argList); } }); new this.NativeFunction({ id: 'Function.prototype.bind', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var target = thisVal; if (!(target instanceof intrp.Function)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, target + ' is not a function'); } var thisArg = args[0]; var argList = args.slice(1); var perms = state.scope.perms; var f = new intrp.BoundFunction(target, thisArg, argList, perms); var len = 0; if (target.has('length', perms)) { var targetLen = target.get('length', perms); if (typeof targetLen === 'number') { len = Math.max(0, targetLen - argList.length); } } f.defineProperty('length', Descriptor.c.withValue(len), perms); var targetName = target.get('name', perms); if (typeof targetName !== 'string') { targetName = ''; } f.setName(targetName, 'bound'); return f; } }); new this.NativeFunction({ id: 'Function.prototype.call', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var func = thisVal; if (!(func instanceof intrp.Function)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, func + ' is not a function'); } var thisArg = args[0]; var argList = args.slice(1); // Rewrite state.info_, as a short-circuit optimisation in case // we get called again due to FunctionResult.CallAgain, and also // to produce more useful callers() output / stack traces. var info = state.info_; info.func = func; info.this = thisArg; info.args = argList; info.construct = false; // But just go and do the first .call directly. return func.call(intrp, thread, state, thisArg, argList); } }); }; /** * Initialize the Array class. * @private */ Interpreter.prototype.initArray_ = function() { // Array prototype. this.ARRAY = new this.Array(this.ROOT, this.OBJECT); this.builtins.set('Array.prototype', this.ARRAY); // Array constructor. new this.NativeFunction({ id: 'Array', length: 1, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { var len = args[0]; var perms = state.scope.perms; // TODO(ES6): Need to do GetPrototypeFromConstructor, ArrayCreate, etc. var arr = new intrp.Array(perms); if (args.length === 0) { // ES6 §22.1.1.1 // Nothing to do. } else if (args.length === 1) { if (typeof len !== 'number') { arr.defineProperty('0', Descriptor.wec.withValue(len), perms); var intLen = 1; } else { // ES6 §22.1.1.2 intLen = Interpreter.toUint32(len); if (intLen !== len) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'Invalid array length'); } } arr.set('length', intLen, perms); } else { // ES6 §22.1.1.3 arr.set('length', args.length, perms); for (var k = 0; k < args.length; k++) { arr.defineProperty( String(k), Descriptor.wec.withValue(args[k]), perms); } } return arr; }, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return this.construct.call(this, intrp, thread, state, args); } }); // Static methods on Array. new this.NativeFunction({ id: 'Array.isArray', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return args[0] instanceof intrp.Array; } }); // Properties of the Array prototype object. new this.NativeFunction({ id: 'Array.prototype.concat', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var arr = new intrp.Array(perms); var n = 0; var doConcat = function(item) { // TODO(ES6): IsConcatSpreadable? if (item instanceof intrp.Array) { // Add elements of item. var len = Interpreter.toLength(item.get('length', perms)); if (len + n > Number.MAX_SAFE_INTEGER) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Concatenating ' + len + ' elements on an array-like of length ' + n + ' is disallowed, as the total surpasses 2**53-1'); } for (var k = 0; k < len; n++, k++) { var kP = String(k); if (item.has(kP, perms)) { arr.defineProperty(String(n), Descriptor.wec.withValue(item.get(kP, perms)), perms); } } } else { // Add item as single element, rather than spread. if (n >= Number.MAX_SAFE_INTEGER) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Concatenating onto an array-like of length ' + n + ' is disallowed, as the total surpasses 2**53-1'); } arr.defineProperty( String(n++), Descriptor.wec.withValue(item), perms); } }; doConcat(thisVal); for (var i = 0; i < args.length; i++) { doConcat(args[i]); } arr.set('length', n, perms); return arr; } }); new this.NativeFunction({ id: 'Array.prototype.includes', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var searchElement = args[0]; var fromIndex = args[1]; var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); if (len === 0) return false; var n = (fromIndex === undefined ? 0 : Interpreter.toInteger(fromIndex)); if (n >= len) return false; var k = (n >= 0) ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (obj.has(String(k), perms)) { var v = obj.get(String(k), perms); if (v === searchElement || (Number.isNaN(/** @type{?} */(v)) && Number.isNaN(/** @type{?} */(searchElement)))) { return true; } } } return false; } }); new this.NativeFunction({ id: 'Array.prototype.indexOf', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var searchElement = args[0]; var fromIndex = args[1]; var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); if (len === 0) return -1; var n = (fromIndex === undefined ? 0 : Interpreter.toInteger(fromIndex)); if (n >= len) return -1; var k = (n >= 0) ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (obj.has(String(k), perms) && obj.get(String(k), perms) === searchElement) { return k; } } return -1; } }); new this.NativeFunction({ id: 'Array.prototype.lastIndexOf', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var searchElement = args[0]; var fromIndex = args[1]; var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); if (len === 0) return -1; var n = (fromIndex === undefined) ? len - 1 : Interpreter.toInteger(fromIndex); var k = (n >= 0) ? Math.min(n, len - 1) : len - Math.abs(n); for (; k >= 0 ; k--) { if (obj.has(String(k), perms) && obj.get(String(k), perms) === searchElement) { return k; } } return -1; } }); new this.NativeFunction({ id: 'Array.prototype.pop', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); if (len === 0) { obj.set('length', 0, perms); return undefined; } var newLen = len - 1; var element = obj.get(String(newLen), perms); obj.deleteProperty(String(newLen), perms); obj.set('length', newLen, perms); return element; } }); new this.NativeFunction({ id: 'Array.prototype.push', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); var argCount = args.length; if (len + args.length > Number.MAX_SAFE_INTEGER) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Pushing ' + argCount + ' elements on an array-like of length ' + len + ' is disallowed, as the total surpasses 2**53-1'); } for (var i = 0; i < argCount; i++) { obj.set(String(len++), args[i], perms); } obj.set('length', len, perms); return len; } }); new this.NativeFunction({ id: 'Array.prototype.reverse', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); var middle = Math.floor(len / 2); for (var lower = 0; lower < middle; lower++) { var upper = len - lower - 1; var upperP = String(upper); var lowerP = String(lower); var lowerExists = obj.has(lowerP, perms); if (lowerExists) { var lowerValue = obj.get(lowerP, perms); } var upperExists = obj.has(upperP, perms); if (upperExists) { var upperValue = obj.get(upperP, perms); } if (lowerExists && upperExists) { obj.set(lowerP, upperValue, perms); obj.set(upperP, lowerValue, perms); } else if (!lowerExists && upperExists) { obj.set(lowerP, upperValue, perms); obj.deleteProperty(upperP, perms); } else if (lowerExists && !upperExists) { obj.deleteProperty(lowerP, perms); obj.set(upperP, lowerValue, perms); } // else neither exist, and no action required. } // ES spec would have us return obj, which would be a boxed // primitive (Boolean, Number or String object) if thisVal was a // number, boolean or the empty string. We decline to do that. // (Note that nonempty strings will already have thrown // TypeError due to non-writable properties.) return thisVal; } }); new this.NativeFunction({ id: 'Array.prototype.shift', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); if (len === 0) { obj.set('length', 0, perms); return undefined; } var first = obj.get('0', perms); for (var k = 1; k < len; k++) { var from = String(k); var to = String(k - 1); if (obj.has(from, perms)) { obj.set(to, obj.get(from, perms), perms); } else { obj.deleteProperty(to, perms); } } obj.deleteProperty(String(len - 1), perms); obj.set('length', len - 1, perms); return first; } }); new this.NativeFunction({ id: 'Array.prototype.slice', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var start = args[0]; var end = args[1]; var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); var relativeStart = Interpreter.toInteger(start); var k = (relativeStart < 0) ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); var relativeEnd = (end === undefined) ? len : Interpreter.toInteger(end); var final = (relativeEnd < 0) ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len); // TODO(cpcallen): ArraySpeciesCreate should take count as an argument. // var count = Math.max(final - k, 0); var arr = new intrp.Array(perms); for (var n = 0; k < final; k++, n++) { var kP = String(k); if (obj.has(kP, perms)) { arr.defineProperty( String(n), Descriptor.wec.withValue(obj.get(kP, perms)), perms); } } arr.set('length', n, perms); return arr; } }); new this.NativeFunction({ id: 'Array.prototype.splice', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var start = args[0]; var deleteCount = args[1]; var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); var relativeStart = Interpreter.toInteger(start); var actualStart = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len); if (args.length === 0) { var insertCount = 0; var actualDeleteCount = 0; } else if (args.length === 1) { insertCount = 0; actualDeleteCount = len - actualStart; } else { insertCount = args.length - 2; var dc = Interpreter.toInteger(deleteCount); actualDeleteCount = Math.min(Math.max(dc, 0), len - actualStart); } if (len + insertCount - actualDeleteCount > Number.MAX_SAFE_INTEGER) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Splicing ' + insertCount - actualDeleteCount + ' elements on an array-like of length ' + len + ' is disallowed, as the total surpasses 2**53-1'); } var arr = new intrp.Array(perms); for (var k = 0; k < actualDeleteCount; k++) { var from = String(actualStart + k); if (obj.has(from, perms)) { arr.defineProperty( String(k), Descriptor.wec.withValue(obj.get(from, perms)), perms); } } arr.set('length', actualDeleteCount, perms); var itemCount = Math.max(args.length - 2, 0); if (itemCount < actualDeleteCount) { for (k = actualStart; k < len - actualDeleteCount; k++) { from = String(k + actualDeleteCount); var to = String(k + itemCount); if (obj.has(from, perms)) { obj.set(to, obj.get(from, perms), perms); } else { obj.deleteProperty(to, perms); } } for (k = len; k > len - actualDeleteCount + itemCount; k--) { obj.deleteProperty(String(k - 1), perms); } } else if (itemCount > actualDeleteCount) { for (k = len - actualDeleteCount; k > actualStart; k--) { from = String(k + actualDeleteCount - 1); to = String(k + itemCount - 1); if (obj.has(from, perms)) { obj.set(to, obj.get(from, perms), perms); } else { obj.deleteProperty(to, perms); } } } for (var j = 2, k = actualStart; j < args.length; j++, k++) { obj.set(String(k), args[j], perms); } obj.set('length', len - actualDeleteCount + itemCount, perms); return arr; } }); new this.NativeFunction({ id: 'Array.prototype.toString', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var join = obj.get('join', perms); if (join instanceof intrp.Function) { var func = join; } else { func = /** @type {!Interpreter.prototype.Function} */ ( intrp.builtins.get('Object.prototype.toString')); } var newState = Interpreter.State.newForCall(func, thisVal, [], perms); thread.stateStack_.push(newState); return Interpreter.FunctionResult.AwaitValue; } }); new this.NativeFunction({ id: 'Array.prototype.unshift', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var obj = intrp.toObject(thisVal, perms); var len = Interpreter.toLength(obj.get('length', perms)); var argCount = args.length; if (argCount > 0) { if (len + args.length > Number.MAX_SAFE_INTEGER) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Unshifting ' + argCount + ' elements on an array-like of length ' + len + ' is disallowed, as the total surpasses 2**53-1'); } for (var k = len; k > 0; k--) { var from = String(k - 1); var to = String(k); if (obj.has(from, perms)) { obj.set(to, obj.get(from, perms), perms); } else { obj.deleteProperty(to, perms); } } for (var j = 0; j < argCount; j++) { obj.set(String(j), args[j], perms); } } obj.set('length', len + argCount, perms); return len + argCount; } }); }; /** * Initialize the String class. * @private */ Interpreter.prototype.initString_ = function() { var intrp = this; var wrapper; // String prototype. It's a String object (but the only one!) this.STRING = new this.Object(this.ROOT); this.builtins.set('String.prototype', this.STRING); this.STRING.class = 'String'; // String constructor. ES6 §21.1.1.1. new this.NativeFunction({ id: 'String', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { // We don't handle symbols, so String(x) should just return // ToString(x) (ES6 §7.1.12) if x is primitive, or // ToString(ToPrimitive(x, hint String)) if not. Note that // ToPrimitive (ES6 §7.1.1) is guaranteed to return a primitive // or throw. var value = args.length > 0 ? args[0] : ''; var perms = state.scope.perms; if (!(value instanceof intrp.Object)) { return String(value); } var step = Number(state.info_.funcState) || 0; if (step > 0 && !(state.value instanceof intrp.Object)) { // Call of .toString or .valueOf by previous visit returned a // primitive. Convert to string and return. return String(state.value); } switch(step) { case 0: // Try calling toString. var method = value.get('toString', perms); if (method instanceof intrp.Function) { thread.stateStack_[thread.stateStack_.length] = Interpreter.State.newForCall(method, value, [], perms); state.info_.funcState = 1; return Interpreter.FunctionResult.CallAgain; } // FALL THROUGH case 1: // toString call complete (or skipped); try calling valueOf. method = value.get('valueOf', perms); if (method instanceof intrp.Function) { thread.stateStack_[thread.stateStack_.length] = Interpreter.State.newForCall(method, value, [], perms); state.info_.funcState = 2; return Interpreter.FunctionResult.CallAgain; } // FALL THROUGH case 2: // valueOf complete (or skipped); throw TypeError. throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Cannot convert object to primitive value'); default: throw new Error('Invalid funcStep in String??'); } }, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'String objects not supported.'); } }); /** * The thisStringValue specification method from ES6 §21.1.3. * Converts value arg to string or throws TypeError. * @param {!Interpreter} intrp The interpreter. * @param {?Interpreter.Value} value The this value passed into function. * @param {string} name Name of built-in function (for TypeError message). * @param {!Interpreter.Owner} perms Who called built-in? * @return {string} */ var thisStringValue = function(intrp, value, name, perms) { if (typeof value === 'string') { // String primitive. return value; } else if (value === intrp.STRING) { // The only String object. return ''; } throw new intrp.Error(perms, intrp.TYPE_ERROR, name + " requires that 'this' be a String"); }; // Static methods on String. this.createNativeFunction('String.fromCharCode', String.fromCharCode, false); // Properties of the String prototype object. // Methods with exclusively primitive arguments. var functions = ['charAt', 'charCodeAt', 'concat', 'endsWith', 'includes', 'indexOf', 'lastIndexOf', 'slice', 'startsWith', 'substr', 'substring', 'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim']; for (var i = 0; i < functions.length; i++) { this.createNativeFunction('String.prototype.' + functions[i], String.prototype[functions[i]], false); } wrapper = function(compareString /*, locales, options*/) { // Messing around with arguments so that function's length is 1. var locales = arguments.length > 1 ? intrp.pseudoToNative(arguments[1]) : undefined; var options = arguments.length > 2 ? intrp.pseudoToNative(arguments[2]) : undefined; return this.localeCompare(compareString, locales, options); }; this.createNativeFunction('String.prototype.localeCompare', wrapper, false); wrapper = function(separator, limit) { if (separator instanceof intrp.RegExp) { separator = separator.regexp; } var jsList = this.split(separator, limit); return intrp.createArrayFromList(jsList, intrp.thread_.perms()); }; this.createNativeFunction('String.prototype.split', wrapper, false); wrapper = function(regexp) { if (regexp instanceof intrp.RegExp) { regexp = regexp.regexp; } var m = this.match(regexp); return m && intrp.createArrayFromList(m, intrp.thread_.perms()); }; this.createNativeFunction('String.prototype.match', wrapper, false); wrapper = function(regexp) { if (regexp instanceof intrp.RegExp) { regexp = regexp.regexp; } return this.search(regexp); }; this.createNativeFunction('String.prototype.search', wrapper, false); wrapper = function(substr, newSubstr) { // Support for function replacements is the responsibility of a polyfill. if (substr instanceof intrp.RegExp) { substr = substr.regexp; } return String(this).replace(substr, newSubstr); }; this.createNativeFunction('String.prototype.replace', wrapper, false); wrapper = function(count) { try { return this.repeat(count); } catch (e) { // 'abc'.repeat(-1) will throw an error. Catch and rethrow. throw intrp.errorNativeToPseudo(e, intrp.thread_.perms()); } }; this.createNativeFunction('String.prototype.repeat', wrapper, false); new this.NativeFunction({ id: 'String.prototype.toString', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return thisStringValue(intrp, thisVal, 'String.prototype.toString', state.scope.perms); } }); new this.NativeFunction({ id: 'String.prototype.valueOf', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return thisStringValue(intrp, thisVal, 'String.prototype.valueOf', state.scope.perms); } }); }; /** * Initialize the Boolean class. * @private */ Interpreter.prototype.initBoolean_ = function() { // Boolean prototype. It's a Boolean object (but the only one!) this.BOOLEAN = new this.Object(this.ROOT); this.builtins.set('Boolean.prototype', this.BOOLEAN); this.BOOLEAN.class = 'Boolean'; // Boolean constructor. new this.NativeFunction({ id: 'Boolean', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return Boolean(args[0]); }, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Boolean objects not supported.'); } }); /** * The thisBooleanValue specification method from ES6 §19.3.3. * Converts value arg to boolean or throws TypeError. * @param {!Interpreter} intrp The interpreter. * @param {?Interpreter.Value} value The this value passed into function. * @param {string} name Name of built-in function (for TypeError message). * @param {!Interpreter.Owner} perms Who called built-in? * @return {boolean} */ var thisBooleanValue = function(intrp, value, name, perms) { if (typeof value === 'boolean') { // Boolean primitive. return value; } else if (value === intrp.BOOLEAN) { // The only Boolen object. return false; } throw new intrp.Error(perms, intrp.TYPE_ERROR, name + " requires that 'this' be a Boolean"); }; // Instance methods on Boolean. new this.NativeFunction({ id: 'Boolean.prototype.toString', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return String(thisBooleanValue(intrp, thisVal, 'Boolean.prototype.toString', state.scope.perms)); } }); new this.NativeFunction({ id: 'Boolean.prototype.valueOf', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return thisBooleanValue(intrp, thisVal, 'Boolean.prototype.valueOf', state.scope.perms); } }); }; /** * Initialize the Number class. * @private */ Interpreter.prototype.initNumber_ = function() { var intrp = this; var wrapper; // Number prototype. It's a Number object (but the only one!) this.NUMBER = new this.Object(this.ROOT); this.builtins.set('Number.prototype', this.NUMBER); this.NUMBER.class = 'Number'; // Number constructor. new this.NativeFunction({ id: 'Number', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return Number(args.length ? args[0] : 0); }, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Number objects not supported.'); } }); /** * The thisNumberValue specification method from ES6 §20.1.3. * Converts value arg to number or throws TypeError. * @param {!Interpreter} intrp The interpreter. * @param {?Interpreter.Value} value The this value passed into function. * @param {string} name Name of built-in function (for TypeError message). * @param {!Interpreter.Owner} perms Who called built-in? * @return {number} */ var thisNumberValue = function(intrp, value, name, perms) { if (typeof value === 'number') { // Number primitive. return value; } else if (value === intrp.NUMBER) { // The only Boolen object. return 0; } throw new intrp.Error(perms, intrp.TYPE_ERROR, name + " requires that 'this' be a Number"); }; // Static methods on Number. this.createNativeFunction('Number.isFinite', Number.isFinite, false); this.createNativeFunction('Number.isInteger', Number.isInteger, false); this.createNativeFunction('Number.isNaN', Number.isNaN, false); this.createNativeFunction('Number.isSafeInteger', Number.isSafeInteger, false); // Properties of the Number prototype object. wrapper = function(fractionDigits) { try { return this.toExponential(fractionDigits); } catch (e) { // Throws if fractionDigits isn't within 0-20. throw intrp.errorNativeToPseudo(e, intrp.thread_.perms()); } }; this.createNativeFunction('Number.prototype.toExponential', wrapper, false); wrapper = function(digits) { try { return this.toFixed(digits); } catch (e) { // Throws if digits isn't within 0-20. throw intrp.errorNativeToPseudo(e, intrp.thread_.perms()); } }; this.createNativeFunction('Number.prototype.toFixed', wrapper, false); wrapper = function(precision) { try { return this.toPrecision(precision); } catch (e) { // Throws if precision isn't within range (depends on implementation). throw intrp.errorNativeToPseudo(e, intrp.thread_.perms()); } }; this.createNativeFunction('Number.prototype.toPrecision', wrapper, false); wrapper = function(/*locales, options*/) { // Messing around with arguments so that function's length is 0. var locales = arguments.length > 0 ? intrp.pseudoToNative(arguments[0]) : undefined; var options = arguments.length > 1 ? intrp.pseudoToNative(arguments[1]) : undefined; return this.toLocaleString(locales, options); }; this.createNativeFunction('Number.prototype.toLocaleString', wrapper, false); new this.NativeFunction({ id: 'Number.prototype.toString', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var x = thisNumberValue( intrp, thisVal, 'Number.prototype.toString', state.scope.perms); var radix = args[0]; try { // Throws if radix isn't within 2-36. Cast requried because // Closure Compiler thinks radix should be a number. return Number.prototype.toString.call(x, /** @type {?} */(radix)); } catch (e) { throw intrp.errorNativeToPseudo(e, intrp.thread_.perms()); } } }); new this.NativeFunction({ id: 'Number.prototype.valueOf', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return thisNumberValue(intrp, thisVal, 'Number.prototype.valueOf', state.scope.perms); } }); }; /** * Initialize the Date class. * @private */ Interpreter.prototype.initDate_ = function() { var intrp = this; var wrapper; // Date prototype. As of ES6 this is just an ordinary object. (In // ES5 it had [[Class]] Date.) this.DATE = new this.Object(this.ROOT); this.builtins.set('Date.prototype', this.DATE); // Date constructor. wrapper = function(value, var_args) { if (!intrp.calledWithNew()) { // Called as Date(). // Calling Date() as a function returns a string, no arguments are heeded. return Date(); } // Called as new Date(). var args = [null].concat(Array.from(arguments)); var date = new (Function.prototype.bind.apply(Date, args))(); return new intrp.Date(date, intrp.thread_.perms()); }; this.createNativeFunction('Date', wrapper, true); // Static methods on Date. this.createNativeFunction('Date.now', Date.now, false); this.createNativeFunction('Date.parse', Date.parse, false); this.createNativeFunction('Date.UTC', Date.UTC, false); // Instance methods on Date. new this.NativeFunction({ id: 'Date.prototype.toString', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var date = thisVal; if (!(date instanceof intrp.Date)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Date.prototype.toString is not generic'); } // TODO(cpcallen:perms): Perm check here? Or in toString? return date.toString(); } }); var functions = ['getDate', 'getDay', 'getFullYear', 'getHours', 'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime', 'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear', 'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth', 'getUTCSeconds', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toISOString', 'toJSON', 'toGMTString', 'toTimeString', 'toUTCString']; for (var i = 0; i < functions.length; i++) { wrapper = (function(nativeFunc) { return function(var_args) { return this.date[nativeFunc].apply(this.date, arguments); }; })(functions[i]); this.createNativeFunction('Date.prototype.' + functions[i], wrapper, false); } functions = ['toLocaleDateString', 'toLocaleString', 'toLocaleTimeString']; for (var i = 0; i < functions.length; i++) { wrapper = (function(nativeFunc) { return function(/*locales, options*/) { // Messing around with arguments so that function's length is 0. var locales = arguments.length > 0 ? intrp.pseudoToNative(arguments[0]) : undefined; var options = arguments.length > 1 ? intrp.pseudoToNative(arguments[1]) : undefined; return this.date[nativeFunc].call(this.date, locales, options); }; })(functions[i]); this.createNativeFunction('Date.prototype.' + functions[i], wrapper, false); } }; /** * Initialize Regular Expression object. * @private */ Interpreter.prototype.initRegExp_ = function() { var intrp = this; var wrapper; // RegExp prototype. As of ES6 this is just an ordinary object. // (In ES5 it had [[Class]] RegExp.) this.REGEXP = new this.Object(this.ROOT); this.builtins.set('RegExp.prototype', this.REGEXP); // RegExp constructor. new this.NativeFunction({ id: 'RegExp', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var pattern = args[0]; var flags = args[1]; if (pattern instanceof intrp.RegExp && flags === undefined) { // Per ES6 §21.2.3.1 step 4.b, (now // https://tc39.es/ecma262/#sec-regexp-constructor step 2.b), // check pattern.constructor to see if it's RegExp. var patternConstructor = pattern.get('constructor', state.scope.perms); if (patternConstructor === this) return pattern; } return this.construct.call(this, intrp, thread, state, args); }, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { var pattern = args[0]; var flags = args[1]; var perms = state.scope.perms; if (pattern instanceof intrp.RegExp) { pattern = pattern.regexp.source; // ES5.1 required that TypeError be thown here if flags !== // undefined, but ES6 and later do not. } // TODO(ES6): ES6 §21.2.3.1 step 6 (now // https://tc39.es/ecma262/#sec-regexp-constructor step 5). pattern = (pattern === undefined ? '' : String(pattern)); flags = (flags === undefined ? '' : String(flags)); // TODO(ES6): also accept [uy]; ES8: [s], soon: [p]. if (!/^(?:([gim])(?!.*\1))*$/.test(flags)) { // Reject repeated flags. throw new intrp.Error(perms, intrp.SYNTAX_ERROR, "Invalid flags supplied to RegExp constructor '" + flags + "'"); } return new intrp.RegExp(new RegExp(pattern, flags), perms); } }); new this.NativeFunction({ id: 'RegExp.prototype.toString', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var regexp= thisVal; if (!(regexp instanceof intrp.RegExp)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'RegExp.prototype.toString is not generic'); } // TODO(cpcallen:perms): Perm check here? Or in toString? return regexp.toString(); } }); wrapper = function(str) { if (!(this instanceof intrp.RegExp) || !(this.regexp instanceof RegExp)) { throw new intrp.Error(intrp.thread_.perms(), intrp.TYPE_ERROR, 'Method RegExp.prototype.exec called on incompatible receiver' + this); } return this.regexp.test(str); }; this.createNativeFunction('RegExp.prototype.test', wrapper, false); wrapper = function(str) { var perms = intrp.thread_.perms(); if (!(this instanceof intrp.RegExp)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Method RegExp.prototype.exec called on incompatible receiver ' + this); } str = String(str); // Get lastIndex from wrapped regex, since this is settable. this.regexp.lastIndex = this.get('lastIndex', perms); var match = this.regexp.exec(str); this.set('lastIndex', this.regexp.lastIndex, perms); if (match) { var result = new intrp.Array(perms); for (var i = 0; i < match.length; i++) { result.set(String(i), match[i], perms); } // match has additional properties. result.set('index', match.index, perms); result.set('input', match.input, perms); return result; } return null; }; this.createNativeFunction('RegExp.prototype.exec', wrapper, false); }; /** * Initialize the Error class. * @private */ Interpreter.prototype.initError_ = function() { var intrp = this; var createErrorClass = function(name, protoKey) { var protoproto = name === 'Error' ? intrp.OBJECT : intrp.ERROR; var proto = new intrp.Error(intrp.ROOT, protoproto); intrp.builtins.set(name + '.prototype', proto); new intrp.NativeFunction({ id: name, name: name, length: 1, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { var message = (args[0] === undefined) ? undefined : String(args[0]); var perms = state.scope.perms; // Use intrp[protoKey] instead of proto because // deserialisation will set up intrp.ERROR et al correctly but // can't modify values of variables in native closures. /** @suppress {checkTypes} */ var err = new intrp.Error(perms, intrp[protoKey], message); err.makeStack(thread.callers(perms).slice(1), perms); return err; }, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return this.construct.call(this, intrp, thread, state, args); } }); return proto; }; intrp.ERROR = createErrorClass('Error', 'ERROR'); // Must be first! intrp.EVAL_ERROR = createErrorClass('EvalError', 'EVAL_ERROR'); intrp.RANGE_ERROR = createErrorClass('RangeError', 'RANGE_ERROR'); intrp.REFERENCE_ERROR = createErrorClass('ReferenceError', 'REFERENCE_ERROR'); intrp.SYNTAX_ERROR = createErrorClass('SyntaxError', 'SYNTAX_ERROR'); intrp.TYPE_ERROR = createErrorClass('TypeError', 'TYPE_ERROR'); intrp.URI_ERROR = createErrorClass('URIError', 'URI_ERROR'); intrp.PERM_ERROR = createErrorClass('PermissionError', 'PERM_ERROR'); this.createNativeFunction('Error.prototype.toString', this.Error.prototype.toString, false); }; /** * Initialize Math object. * @private */ Interpreter.prototype.initMath_ = function() { var numFunctions = ['abs', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'cbrt', 'ceil', 'clz32', 'cos', 'cosh', 'exp', 'expm1', 'floor', 'fround', 'hypot', 'imul', 'log', 'log10', 'log1p', 'log2', 'max', 'min', 'pow', 'random', 'round', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']; for (var i = 0; i < numFunctions.length; i++) { this.createNativeFunction('Math.' + numFunctions[i], Math[numFunctions[i]], false); } }; /** * Initialize JSON object. * @private */ Interpreter.prototype.initJSON_ = function() { var intrp = this; var wrapper; wrapper = function(text) { try { var nativeObj = JSON.parse(String(text)); } catch (e) { throw intrp.errorNativeToPseudo(e, intrp.thread_.perms()); } return intrp.nativeToPseudo(nativeObj, intrp.thread_.perms()); }; this.createNativeFunction('JSON.parse', wrapper, false); wrapper = function(value, replacer, space) { var nativeObj = intrp.pseudoToNative(value); var perms = intrp.thread_.perms(); if (replacer instanceof intrp.Function) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'Function replacer on JSON.stringify not supported'); } else if (replacer instanceof intrp.Array) { replacer = intrp.createListFromArrayLike(replacer, perms); replacer = replacer.filter(function(word) { // Spec says we should also support boxed primitives here. return typeof word === 'string' || typeof word === 'number'; }); } else { replacer = null; } // Spec says we should also support boxed primitives here. if (typeof space !== 'string' && typeof space !== 'number') { space = undefined; } try { var str = JSON.stringify(nativeObj, replacer, space); } catch (e) { throw intrp.errorNativeToPseudo(e, perms); } return str; }; this.createNativeFunction('JSON.stringify', wrapper, false); }; /** * Initialize the WeakMap class. * @private */ Interpreter.prototype.initWeakMap_ = function() { // WeakMap prototype. this.WEAKMAP = new this.Object(this.ROOT); this.builtins.set('WeakMap.prototype', this.WEAKMAP); // WeakMap constructor. new this.NativeFunction({ id: 'WeakMap', length: 0, // N.B. length is correct; arg is optional! /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { // TODO(cpcallen): Support iterable argument to populate map. return new intrp.WeakMap(state.scope.perms); } }); // Properties of the WeakMap prototype object. /** * A narrowing of Interpreter.NativeCallImpl for decorated WeakMap * .call implementations. * @typedef {function(this: Interpreter.prototype.NativeFunction, * !Interpreter, * !Interpreter.Thread, * !Interpreter.State, * !Interpreter.prototype.WeakMap, * !Array) * : (?Interpreter.Value|!Interpreter.FunctionResult)} */ var WeakMapCallImpl; /** * Decorator to add standard permission and type checks for WeakMap * prototype methods. * @param {!WeakMapCallImpl} func Function to decorate. * @param {string=} name Name of decorated function (default: * func.name). (N.B. needed because 'delete' is a reserve word. * @return {!Interpreter.NativeCallImpl} The decorated function.) */ var withChecks = function(func, name) { name = (name === undefined ? func.name : name); return function call(intrp, thred, state, thisVal, args) { // TODO(cpcallen:perms): add controls()-type and/or // object-readability check(s) here. if (!(thisVal instanceof intrp.WeakMap)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Method WeakMap.prototype.' + name + ' called on incompatible receiver ' + String(thisVal)); } else if (!(args[0] instanceof intrp.Object)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Invalid value used as weak map key'); } return func.apply(this, arguments); }; }; new this.NativeFunction({ id: 'WeakMap.prototype.delete', length: 1, call: withChecks(function(intrp, thread, state, thisVal, args) { return thisVal.weakMap.delete(args[0]); }, 'delete') }); new this.NativeFunction({ id: 'WeakMap.prototype.get', length: 1, call: withChecks(function get(intrp, thread, state, thisVal, args) { return thisVal.weakMap.get(args[0]); }) }); new this.NativeFunction({ id: 'WeakMap.prototype.has', length: 1, call: withChecks(function has(intrp, thread, state, thisVal, args) { return thisVal.weakMap.has(args[0]); }) }); new this.NativeFunction({ id: 'WeakMap.prototype.set', length: 2, call: withChecks(function set(intrp, thread, state, thisVal, args) { thisVal.weakMap.set(args[0], args[1]); return thisVal; }) }); }; /** * Initialize the thread system API. * @private */ Interpreter.prototype.initThread_ = function() { // Thread prototype. this.THREAD = new this.Object(this.ROOT); this.builtins.set('Thread.prototype', this.THREAD); /* Thread constructor. Usage: * * var thread = new Thread(func, delay, thisArg, ...args); * * - func is function to run in thread. (Maybe in future we will * accept src to eval, but not for now.) * - delay is time to wait (in ms) before starting thread. * - thisArg is the 'this' value to use for the call (as if via .apply). * - ...args are additional arguments to pass to func. */ new this.NativeFunction({ id: 'Thread', length: 1, /** @type {!Interpreter.NativeConstructImpl} */ construct: function(intrp, thread, state, args) { var func = args[0]; var delay = Number(args[1]) || 0; var thisArg = args[2]; args = args.slice(3); var perms = state.scope.perms; if (!(func instanceof intrp.Function)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, func + ' is not a function'); } return intrp.createThreadForFuncCall( perms, func, thisArg, args, intrp.now() + delay, thread.timeLimit); } }); new this.NativeFunction({ id: 'Thread.current', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return thread.wrapper; } }); new this.NativeFunction({ id: 'Thread.kill', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var t = args[0]; var perms = state.scope.perms; if (!(t instanceof intrp.Thread)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, t + ' is not a Thread'); } // TODO(cpcallen:perms): add security check here. var id = t.thread.id; if (intrp.threads_[id]) { intrp.threads_[id].status = Interpreter.Thread.Status.ZOMBIE; } } }); new this.NativeFunction({ id: 'Thread.suspend', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var delay = Number(args[0]) || 0; if (delay < 0) { delay = 0; } thread.runAt = intrp.now() + delay; return Interpreter.FunctionResult.Sleep; } }); new this.NativeFunction({ id: 'Thread.callers', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = state.scope.perms; var frames = thread.callers(state.scope.perms); var callers = []; for (var i = 1, frame; (frame = frames[i]); i++) { var caller = new intrp.Object(perms); // Copy properties of frame to caller. for (var key in frame) { if (!frame.hasOwnProperty(key)) continue; var value = frame[key]; if (typeof value === 'function' || typeof value === 'object' && !(value instanceof intrp.Object) && value !== null) { throw new TypeError('Unexpected native object'); } caller.defineProperty(key, Descriptor.wec.withValue(value), perms); } callers.push(caller); } return intrp.createArrayFromList(callers, perms); } }); // Properties of the Thread prototype object. /** * A narrowing of Interpreter.NativeCallImpl for decorated Thread * .call implementations. * @typedef {function(this: Interpreter.prototype.NativeFunction, * !Interpreter, * !Interpreter.Thread, * !Interpreter.State, * !Interpreter.prototype.Thread, * !Array) * : (?Interpreter.Value|!Interpreter.FunctionResult)} */ var ThreadCallImpl; /** * Decorator to add standard permission and type checks for Thread * prototype methods. * @param {!ThreadCallImpl} func Function to decorate. * @return {!Interpreter.NativeCallImpl} The decorated function.) */ var withChecks = function(func) { name = (name === undefined) ? func.name : name; return function call(intrp, thred, state, thisVal, args) { // TODO(cpcallen:perms): add controls()-type and/or // object-readability check(s) here. if (!(thisVal instanceof intrp.Thread)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'Method Thread.prototype.' + name + ' called on incompatible receiver ' + String(thisVal)); } return func.apply(this, arguments); }; }; new this.NativeFunction({ id: 'Thread.prototype.getTimeLimit', length: 0, call: withChecks(function getTimeLimit( intrp, thread, state, thisVal, args) { return thisVal.thread.timeLimit; }) }); // BUG(cpcallen): this only sets the time limit for future slices; // until suspend is called the current Thread will run with its // existing limit. new this.NativeFunction({ id: 'Thread.prototype.setTimeLimit', length: 1, call: withChecks(function setTimeLimit( intrp, thread, state, thisVal, args) { var limit = args[0]; var perms = state.scope.perms; var old = thisVal.thread.timeLimit || Number.MAX_VALUE; if (typeof limit !== 'number' || Number.isNaN(limit)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'new limit must be a number (and not NaN)'); } else if (limit <= 0) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'new limit must be > 0'); } else if (limit > old) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'new limit must be <= previous limit'); } thisVal.thread.timeLimit = limit; }) }); }; /** * Initialize the permissions model API. * @private */ Interpreter.prototype.initPerms_ = function() { // Create object, never available to userland, to be used to // rpresent the permissions of "a generic user" when such a thing is // needed (e.g., for internal toString implementations, which have // no information about caller perms but need to access properties // on the object - something which can't be done with the null // permissions). var anybody = new this.Object(null, this.OBJECT); this.ANYBODY = /** @type {!Interpreter.Owner} */ (anybody); new this.NativeFunction({ id: 'perms', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { return /** @type {!Interpreter.prototype.Object} */ (state.scope.perms); } }); new this.NativeFunction({ id: 'setPerms', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var perms = args[0]; if (!(perms instanceof intrp.Object)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'New perms must be an object'); } // TODO(cpcallen:perms): throw if current perms does not // control new perms. state.scope.perms = /** @type {!Interpreter.Owner} */ (perms); } }); new this.NativeFunction({ id: 'Object.getOwnerOf', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; if (!(obj instanceof intrp.Object)) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, "Can't get owner of non-object"); } return /** @type {?Interpreter.prototype.Object} */(obj.owner); } }); new this.NativeFunction({ id: 'Object.setOwnerOf', length: 0, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; var owner = args[1]; var perms = state.scope.perms; if (!(obj instanceof intrp.Object)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, "Can't set owner of non-object"); } if (!(owner instanceof intrp.Object) && owner !== null) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'New owner must be an object or null'); } // TODO(cpcallen:perms): throw if current perms does not // control obj and (new) owner. obj.owner = /** @type {?Interpreter.Owner} */(owner); return obj; } }); }; /** * Initialize the networking subsystem API. * @private */ Interpreter.prototype.initNetwork_ = function() { new this.NativeFunction({ id: 'CC.connectionListen', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var port = args[0]; var proto = args[1]; var timeLimit = Number(args[2]) || thread.timeLimit; var perms = state.scope.perms; if (port !== (port >>> 0) || port > 0xffff) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'invalid port'); } else if (port in intrp.listeners_) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'port already listened'); } if (!(proto instanceof intrp.Object)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, 'prototype argument to connectionListen must be an object'); } // TODO(cpcallen): do validity check on timeLimit. It should // probaly not be larger than current limit (unless root). var server = new intrp.Server(perms, port, proto, timeLimit); intrp.listeners_[port] = server; var rr = intrp.getResolveReject(thread, state); server.listen(function(error) { if (!error) { rr.resolve(); } else { rr.reject(intrp.errorNativeToPseudo(error, perms), perms); } }); return Interpreter.FunctionResult.Block; } }); new this.NativeFunction({ id: 'CC.connectionUnlisten', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var port = args[0]; var perms = state.scope.perms; if (port !== (port >>> 0) || port > 0xffff) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'invalid port'); } else if (!(port in intrp.listeners_)) { throw new intrp.Error(perms, intrp.RANGE_ERROR, 'port not listening'); } if (!(intrp.listeners_[port].server_ instanceof net.Server)) { throw new Error('no net.Serfer object for port %s??', port); } var rr = intrp.getResolveReject(thread, state); intrp.listeners_[port].unlisten(function() { // Socket (and all open connections on it) now closed. delete intrp.listeners_[/** @type {number} */(port)]; rr.resolve(); }); return Interpreter.FunctionResult.Block; } }); new this.NativeFunction({ id: 'CC.connectionWrite', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; var data = args[1]; if (!(obj instanceof intrp.Object) || !obj.socket) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'object is not connected'); } else if (typeof data !== 'string') { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'data is not a string'); } obj.socket.write(data); } }); new this.NativeFunction({ id: 'CC.connectionClose', length: 2, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var obj = args[0]; if (!(obj instanceof intrp.Object) || !obj.socket) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, 'object is not connected'); } obj.socket.end(); } }); new this.NativeFunction({ id: 'CC.xhr', length: 1, /** @type {!Interpreter.NativeCallImpl} */ call: function(intrp, thread, state, thisVal, args) { var url = String(args[0]); var perms = state.scope.perms; if (url.match(/^http:\/\//)) { var req = http.get(url); } else if (url.match(/^https:\/\//)) { req = https.get(url); } else { throw new intrp.Error(perms, intrp.SYNTAX_ERROR, 'Unrecognized URL "' + url + '"'); } intrp.log('net', 'XHR for %s: connect', url); var rr = intrp.getResolveReject(thread, state); req.on('response', function(res) { intrp.log('net', 'XHR for %s: response', url); if (res.statusCode !== 200) { var err = new intrp.Error(perms, intrp.ERROR, 'HTTP request failed: ' + res.statusCode + ' ' + res.statusMessage); err.set('statusCode', Number(res.statusCode), perms); err.set('statusMessage', String(res.statusMessage), perms); res.resume(); rr.reject(err, perms); return; } var body = ''; res.on('data', function(data) { body += String(data); }); res.on('end', function() { intrp.log('net', 'XHR for %s: end', url); rr.resolve(body); }); }).on('error', function(e) { intrp.log('net', 'XHR for %s: %s', url, e); rr.reject(intrp.errorNativeToPseudo(e, perms), perms); }); return Interpreter.FunctionResult.Block; } }); }; /** * The ToInteger function from ES6 §7.1.4. The abstract operation * ToInteger converts argument to an integral numeric value. * @param {?Interpreter.Value} value * @return {number} An integer if the value can be converted to such; * 0 otherwise. */ Interpreter.toInteger = function toInteger(value) { var number = Number(value); if (isNaN(number)) { return 0; } else if (number === 0 || !isFinite(number)) { return number; } return Math.trunc(number); }; /** * The ToUint32 function from ES6 §7.1.6. The abstract operation * ToUint32 converts argument to one of 2**32 integer values in the * range 0 through 2**32−1, inclusive. * @param {?Interpreter.Value} value * @return {number} A non-negative integer less than 2**32. */ Interpreter.toUint32 = function toUint32(value) { return Interpreter.toInteger(value) >>> 0; }; /** * The ToLength function from ES6 §7.1.15. Note that this does NOT * enforce the actual array length limit of 2**32-1, but deals with * lengths up to 2**53-1, which is correct for the polymorphic * Array.prototype methods. * @param {?Interpreter.Value} value * @return {number} A non-negative integer less than 2**53. */ Interpreter.toLength = function toLength(value) { var len = Interpreter.toInteger(value); if (len <= 0) return 0; return Math.min(len, Number.MAX_SAFE_INTEGER); // Handles len === Infinity. }; /** * Create a new native function. Function will be owned by root. * @param {string} id ID to register new function in builtins registry. * @param {!Function} nativeFunc Any JavaScript function. * @param {boolean} legalConstructor True if the function can be used as a * constructor (e.g. Array), false if not (e.g. escape). * @return {!Interpreter.prototype.Function} New function. */ Interpreter.prototype.createNativeFunction = function( id, nativeFunc, legalConstructor) { if (nativeFunc instanceof this.Object) { throw new TypeError('createNativeFunction passed non-native function??'); } // Make sure impl function has an id for serialization. if (!nativeFunc.id) nativeFunc.id = id; return new this.OldNativeFunction(nativeFunc, legalConstructor, {id: id}); }; /** * Converts from a native JS object or value to a JS interpreter * object. Can handle JSON-style values plus regexps and errors (of * all standard native types), and handles additional properties on * arrays, regexps and errors (just as for plain objects). Ignores * prototype and inherited properties. Efficiently handles * sparse arrays. Does NOT handle cyclic structures. * @param {*} nativeObj The native JS object to be converted. * @return {?Interpreter.Value} The equivalent JS interpreter object. * @param {!Interpreter.Owner} owner Owner for new object. */ Interpreter.prototype.nativeToPseudo = function(nativeObj, owner) { if ((typeof nativeObj !== 'object' && typeof nativeObj !== 'function') || nativeObj === null) { // It's a primitive; just return it. return /** @type {boolean|number|string|undefined|null} */ (nativeObj); } else if (nativeObj instanceof this.Object) { throw new TypeError('nativeToPseudo called on a pseudo-object??'); } var pseudoObj; switch (Object.prototype.toString.apply(nativeObj)) { case '[object Array]': pseudoObj = new this.Array(owner); break; case '[object RegExp]': pseudoObj = new this.RegExp(/** @type {!RegExp} */(nativeObj), owner); break; case '[object Error]': var proto; if (nativeObj instanceof EvalError) { proto = this.EVAL_ERROR; } else if (nativeObj instanceof RangeError) { proto = this.RANGE_ERROR; } else if (nativeObj instanceof ReferenceError) { proto = this.REFERENCE_ERROR; } else if (nativeObj instanceof SyntaxError) { proto = this.SYNTAX_ERROR; } else if (nativeObj instanceof TypeError) { proto = this.TYPE_ERROR; } else if (nativeObj instanceof URIError) { proto = this.URI_ERROR; } else { proto = this.ERROR; } pseudoObj = new this.Error(owner, proto); break; default: pseudoObj = new this.Object(owner); } // Cast to satisfy type-checker; it might be a lie: nativeObj could // be an object (i.e., non-primitive) but not an Object (i.e., // inherits from Object.prototype). Fortunately we don't care. var keys = Object.getOwnPropertyNames(/** @type {!Object} */(nativeObj)); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var desc = Object.getOwnPropertyDescriptor(nativeObj, key); var pd = new Descriptor(desc.writable, desc.enumerable, desc.configurable); pd.value = this.nativeToPseudo(desc.value, owner); pseudoObj.defineProperty(key, pd, owner); } return pseudoObj; }; /** * Converts from a JS interpreter object to native JS object. * Can handle JSON-style values, plus cycles. * * TODO(cpcallen): Audit this to ensure that it can safely accept any * user object (especially because it is used by our implementations * of JSON.stringify, String.prototype.localeCompare, etc.) * * TODO(cpcallen:perms): Audit all callers of this to ensure that they * do not allow circumvention of access control. * @param {?Interpreter.Value} pseudoObj The JS interpreter object to * be converted. * @param {!Object=} cycles Cycle detection (used only in recursive calls). * @return {*} The equivalent native JS object or value. */ Interpreter.prototype.pseudoToNative = function(pseudoObj, cycles) { // BUG(cpcallen:perms): Kludge. Incorrect except when doing .step // or run. Should be an argument instead, forcing caller to decide. try { var perms = this.thread_.perms(); } catch (e) { perms = this.ROOT; } if (typeof pseudoObj === 'boolean' || typeof pseudoObj === 'number' || typeof pseudoObj === 'string' || pseudoObj === null || pseudoObj === undefined) { // It's a primitive; just return it. return pseudoObj; } else if (!(pseudoObj instanceof this.Object)) { throw new TypeError('pseudoToObject called on wrong type??'); } else if (pseudoObj instanceof this.RegExp) { // Regular expression. return pseudoObj.regexp; } else if (pseudoObj instanceof this.Function) { // Function. return undefined; } if (!cycles) { cycles = {pseudo: [], native: []}; } var i = cycles.pseudo.indexOf(pseudoObj); if (i !== -1) { return cycles.native[i]; } cycles.pseudo[cycles.pseudo.length] = pseudoObj; var nativeObj = pseudoObj instanceof this.Array ? [] : {}; cycles.native[cycles.native.length] = nativeObj; var keys = pseudoObj.ownKeys(perms); for (i = 0; i < keys.length; i++) { var key = keys[i]; var pd = pseudoObj.getOwnPropertyDescriptor(key, perms); Object.defineProperty(nativeObj, key, { writable: pd.writable, enumerable: pd.enumerable, configurable: pd.configurable, value: this.pseudoToNative(pd.value, cycles) }); } cycles.pseudo.pop(); cycles.native.pop(); return nativeObj; }; /** * CreateArrayFromList from ES6 §7.3.16 * * Converts from a native array to an Interpreter.prototype.Array. * Does NOT recursively convert the type of the array's contents. * @param {!Array} elements The native array to be * converted. * @param {!Interpreter.Owner} owner Owner for new object. * @return {!Interpreter.prototype.Array} The equivalent interpreter array. */ Interpreter.prototype.createArrayFromList = function(elements, owner) { if (!Array.isArray(elements) || (elements instanceof this.Object)) { throw new TypeError('CreateArrayFromList called on wrong type??'); } var array = new this.Array(owner); for (var n = 0; n < elements.length; n++) { array.defineProperty( String(n), Descriptor.wec.withValue(elements[n]), owner); } return array; }; /** * CreateListFromArrayLike from ES6 §7.3.17. * * This function converts from an Interpreter.prototype.Array (or * array-like I.p.Object) to a native array. This is an evolution of * the algorithm from ES5.1 §15.3.4.3 (Function.prototype.apply). It * does NOT recursively convert the type of the array's contents. * * TODO(ES6): Add elementTypes param and associated type checks. * @param {?Interpreter.Value} obj The interpreter array or array-like * object to be converted. Error thrown if non-object. * @param {!Interpreter.Owner} perms Who is trying convert it? * @return {!Array} The equivalent native JS array. */ Interpreter.prototype.createListFromArrayLike = function(obj, perms) { if (!(obj instanceof this.Object)) { throw new this.Error(perms, this.TYPE_ERROR, 'CreateListFromArrayLike called on non-object'); } var len = Interpreter.toLength(obj.get('length', perms)); var list = []; for (var i = 0; i < len; i++) { list[i] = obj.get(String(i), perms); } return list; }; /** * Converts from a native Error to a JS interpreter Error. Unlike * pseudoToNative, this fucntion only converts type and .message. * @param {!Error} err Native Error value to be converted. * @param {?Interpreter.Owner} owner Owner for new (pseudo) Error object. * @return {!Interpreter.prototype.Error} */ Interpreter.prototype.errorNativeToPseudo = function(err, owner) { var proto; if (err instanceof this.Object) { throw new TypeError('errorNativeToPseudo called on wrong type??'); } if (err instanceof EvalError) { proto = this.EVAL_ERROR; } else if (err instanceof RangeError) { proto = this.RANGE_ERROR; } else if (err instanceof ReferenceError) { proto = this.REFERENCE_ERROR; } else if (err instanceof SyntaxError) { proto = this.SYNTAX_ERROR; } else if (err instanceof TypeError) { proto = this.TYPE_ERROR; } else if (err instanceof URIError) { proto = this.URI_ERROR; } else { proto = this.ERROR; } return new this.Error(owner, proto, err.message); }; /** * Implements the ToObject specification method from ES5.1 §9.9 / ES6 * §7.1.13, but returning temporary Box objects instead of boxed * Boolean, Number or String instances. * @param {?Interpreter.Value} value The value to be converted to an Object. * @param {!Interpreter.Owner} perms Who is trying convert it? * @return {!Interpreter.ObjectLike} */ Interpreter.prototype.toObject = function(value, perms) { if (value === null || value === undefined) { throw new this.Error(perms, this.TYPE_ERROR, "Can't convert " + value + ' to Object'); } else if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') { return new this.Box(value); } return value; }; /** * Retrieves a value from the scope chain. * @param {!Interpreter.Scope} scope Scope to read from. * @param {string} name Name of variable. * @return {?Interpreter.Value} Value (may be undefined). */ Interpreter.prototype.getValueFromScope = function(scope, name) { for (var s = scope; s; s = s.outerScope) { if (name in s.vars) { return s.vars[name]; } } throw new this.Error(this.thread_.perms(), this.REFERENCE_ERROR, name + ' is not defined'); }; /** * Sets a value to the current scope. * @param {!Interpreter.Scope} scope Scope to write to. * @param {string} name Name of variable. * @param {?Interpreter.Value} value Value. */ Interpreter.prototype.setValueToScope = function(scope, name, value) { for (var s = scope; s; s = s.outerScope) { if (name in s.vars) { try { s.vars[name] = value; } catch (e) { // Trying to set immutable binding. // TODO(cpcallen:perms): we have a scope here, but scope.perms // is probably not the right value for owner of new error. throw new this.Error(this.thread_.perms(), this.TYPE_ERROR, 'Assignment to constant variable ' + name); } return; } } throw new this.Error(this.thread_.perms(), this.REFERENCE_ERROR, name + ' is not defined'); }; /** * Populate a scope with declarations from given node. * @param {!Node} node AST node (program or function). * @param {!Interpreter.Scope} scope Scope dictionary to populate. * @param {!Interpreter.Source=} source Original source code. If not * supplied, will use node['source'] instead. * @private */ Interpreter.prototype.populateScope_ = function(node, scope, source) { if (!source) { if (!node['source']) throw new Error('Source not found'); source = node['source']; } // Obtain list of bound names for node. We cache this on the AST // node to save time when repeatedly calling the same function. var boundNames = getBoundNames(node); for (var name in boundNames) { var boundValue = boundNames[name]; var value = boundValue ? new this.UserFunction(boundValue, scope, source, scope.perms) : undefined; if (!scope.hasBinding(name)) scope.createMutableBinding(name, value); if (value) this.setValueToScope(scope, name, value); } }; /** * Is the current state directly being called with as a construction with 'new'. * @return {boolean} True if 'new foo()', false if 'foo()'. */ Interpreter.prototype.calledWithNew = function() { return this.thread_.stateStack_[this.thread_.stateStack_.length - 1] .info_.construct; }; /** * Implements IsUnresolvableReference from ES5 §8.7 / ES6 §6.2.3. * @param {!Interpreter.Scope} scope Current scope dictionary. * @param {!Array} ref Reference tuple. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {boolean} True iff refernece is unresolvable. */ Interpreter.prototype.isUnresolvableReference = function(scope, ref, perms) { // Property references never unresolvable. return ref[0] === null; }; /** * Gets the value of a referenced name from the scope or object referred to. * @param {!Array} ref Reference tuple. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {?Interpreter.Value} Value (may be undefined). */ Interpreter.prototype.getValue = function(ref, perms) { var base = ref[0]; var name = ref[1]; if (base === null) { // Unresolvable reference. throw new this.Error(perms, this.REFERENCE_ERROR, name + ' is not defined'); } else if (base instanceof Interpreter.Scope) { // An environment reference. return base.get(name); } else { // A property reference. return this.toObject(base, perms).get(name, perms); } }; /** * Sets value of a referenced name to the scope or object referred to. * @param {!Array} ref Reference tuple. * @param {?Interpreter.Value} value Value. * @param {!Interpreter.Owner} perms Who is trying to set it? */ Interpreter.prototype.setValue = function(ref, value, perms) { var base = ref[0]; var name = ref[1]; if (base === null) { // Unresolvable reference. throw new this.Error(perms, this.REFERENCE_ERROR, name + ' is not defined'); } else if (base instanceof Interpreter.Scope) { // An environment reference. var err = base.set(name, value); if (err) { throw this.errorNativeToPseudo(err, perms); } } else { // A property reference. this.toObject(ref[0], perms).set(name, value, perms); } }; /** * Check to see if the current thread has run too long. Called at the * top of loops and before making function calls. * @private * @param {!Interpreter.Owner} perms Perm to use to create Error object. */ Interpreter.prototype.checkTimeLimit_ = function(perms) { if (this.threadTimeLimit_ && this.now() > this.threadTimeLimit_) { throw new this.Error(perms, this.RANGE_ERROR, 'Thread ran too long'); } }; /** * Carry out the mechanics of throwing an exception. * * This is intended only to be called from exception handlers in * .step() and .run(), and from async function's reject() callback. * Elsewhere, just throw. * @param {!Interpreter.Thread} thread in which throw is occurring. * @param {?Interpreter.Value} e Exception being thrown. * @param {!Interpreter.Owner} perms Perm to use to obtain (e.g.) * function names, etc. */ Interpreter.prototype.throw_ = function(thread, e, perms) { if (e instanceof this.Error) { // Userland Error object thrown; make sure it has a .stack. // BUG(cpcallen): this will set .stack on Error.prototype, etc. e.makeStack(thread.callers(perms), perms); } else if (e instanceof Error) { // Uh oh. This is an internal error in the interpreter. Kill // thread and rethrow. thread.status = Interpreter.Thread.Status.ZOMBIE; throw e; } else if (!(e instanceof this.Object) && e !== null && (typeof e === 'object' || typeof e === 'function')) { // WTF: not a native exception, not an interpreter object and not // a primitive, but just some random (internal) object. throw new TypeError('Unexpected exception value ' + String(e)); } this.unwind_(thread, Interpreter.CompletionType.THROW, e, undefined); }; /** * Unwind the stack to the innermost relevant enclosing TryStatement, * For/ForIn/WhileStatement or Call. If this results in * the stack being completely unwound the thread will be terminated * and an appropriate error being logged. * * N.B. Normally unwind should be called from the current stack frame * (i.e., do NOT do stack.pop() before calling unwind) because the * target label of a break statement can be the statement itself * (e.g., `foo: break foo;`). * @private * @param {!Interpreter.Thread} thread The thread whose stack is to be unwound. * @param {!Interpreter.CompletionType} type Completion type. * @param {?Interpreter.Value=} value Value computed, returned or thrown. * @param {string=} label Target label for break or return. */ Interpreter.prototype.unwind_ = function(thread, type, value, label) { if (type === Interpreter.CompletionType.NORMAL) { throw new TypeError('Should not unwind for NORMAL completions'); } for (var stack = thread.stateStack_; stack.length > 0; stack.pop()) { var state = stack[stack.length - 1]; switch (state.node['type']) { case 'TryStatement': state.info_ = {type: type, value: value, label: label}; return; case 'Call': switch (type) { case Interpreter.CompletionType.BREAK: case Interpreter.CompletionType.CONTINUE: throw new Error('Unsynatctic break/continue not rejected by Acorn'); case Interpreter.CompletionType.RETURN: state.value = value; return; } break; } if (type === Interpreter.CompletionType.BREAK) { if (label ? (state.labels && state.labels.includes(label)) : (state.isLoop || state.isSwitch)) { // Top of stack is now target of break. But we are breaking // out of this statement, so pop to discard it. stack.pop(); return; } } else if (type === Interpreter.CompletionType.CONTINUE) { if (label ? (state.labels && state.labels.includes(label)) : state.isLoop) { return; } } } // Unhandled completion. Terminate thread. thread.status = Interpreter.Thread.Status.ZOMBIE; if (type === Interpreter.CompletionType.THROW) { // Log exception and stack trace. if (value instanceof this.Error) { this.log('unhandled', 'Unhandled %s', value); var stackTrace = value.get('stack', this.ROOT); if (stackTrace) { this.log('unhandled', stackTrace); } } else { var native = this.pseudoToNative(value); this.log('unhandled', 'Unhandled exception with value: %o', native); } } else { throw new Error('Unsynatctic break/continue/return not rejected by Acorn'); } }; /** * Get a {resovle, reject} tuple for the specified thread and state, * which is presumed to be about to block on an async function call. * * The resolve function takes a single argument and, when called, will * unblock the thread and save its argument in state.value. * * The reject function takes a single argument and, when called, will * unblock the thread and unwind the stack as if its argument had been * thrown. * * Only one of these may be called, and only once, or an internal * Error will be thrown. * @param {!Interpreter.Thread} thread The thread to be controlled. * @param {!Interpreter.State} state The state in which thread to block. * @return {{resolve: function(?Interpreter.Value=):void, * reject: function(?Interpreter.Value, !Interpreter.Owner):void}} */ Interpreter.prototype.getResolveReject = function(thread, state) { var /** boolean */ done = false; /** * Throw an internal error if previously invoked or if the thread * does not appear to be in a plausible state. */ var check = function() { if (done) { throw new Error('Async resolved or rejected more than once??'); } done = true; if (thread.status !== Interpreter.Thread.Status.BLOCKED || thread.stateStack_[thread.stateStack_.length - 1] !== state) { throw new Error('Thread state corrupt at async resolve/reject??'); } }; var intrp = this; return { resolve: function resolve(value) { check(); state.value = value; thread.status = Interpreter.Thread.Status.READY; intrp.go_(); }, reject: function reject(value, perms) { check(); thread.status = Interpreter.Thread.Status.READY; intrp.throw_(thread, value, perms); intrp.go_(); } }; }; /** * Log something. * @param {string} category About what topic is this log? * @param {...*} var_args */ Interpreter.prototype.log = function(category, var_args) { if (this.options.noLog && this.options.noLog.includes(category)) { return; } console.log.apply(console, Array.prototype.slice.call(arguments, 1)); }; /////////////////////////////////////////////////////////////////////////////// // Nested types & constants (not fully-fledged classes) /////////////////////////////////////////////////////////////////////////////// /** * The Completion Specification Type, from ES5.1 §8.9 * @typedef {{type: Interpreter.CompletionType, * value: ?Interpreter.Value, * label: (string|undefined)}} */ Interpreter.Completion; /** * Completion Value Types. * @enum {number} */ Interpreter.CompletionType = { NORMAL: 0, BREAK: 1, CONTINUE: 2, RETURN: 3, THROW: 4 }; /** * Special sentinel values returned by the call or construct method of * a (pseudo)Function to indicate that a return value is not * immediately available (e.g., in the case of a user function that * needs to be evaluated, or an async function that blocks). * @constructor * @struct */ Interpreter.FunctionResult = function() {}; /** * Please evaluate whatever state(s) have been pushed onto the stack, * and use their completion value as the return value of the function. * @const */ Interpreter.FunctionResult.AwaitValue = new Interpreter.FunctionResult; /** * Please mark this thread as blocked awaiting eternal event (e.g., * async callback). * @const */ Interpreter.FunctionResult.Block = new Interpreter.FunctionResult; /** * Please invoke .call or .construct again the next time this state is * encountered. * @const */ Interpreter.FunctionResult.CallAgain = new Interpreter.FunctionResult; /** * Please mark this thread as sleeping until its .runAt time. * @const */ Interpreter.FunctionResult.Sleep = new Interpreter.FunctionResult; /** * Options object for Interpreter constructor. * @typedef {{ * noLog: (!Array|undefined), * trimEval: (boolean|undefined), * trimProgram: (boolean|undefined), * stackLimit: (number|undefined), * }} */ Interpreter.Options; /** * Interpreter statuses. * @enum {number} */ Interpreter.Status = { /** * Won't run code. Any listening sockets are unlistened. No time * passes (as measured by .uptime() and .now(), which underly * setTimeout etc.) */ STOPPED: 0, /** * Will run code *only* if .step() or .run() is called. Will listen * on network sockets (including re-listening on any that were * unlistened because the interpreter was stopped). Time will pass * (as measured by .uptime() and .now()). */ PAUSED: 1, /** * Will run code automatically in response to thread creation, * timeouts and network activity. */ RUNNING: 2 }; /////////////////////////////////////////////////////////////////////////////// // Nested (but not fully inner) classes: Scope, State, Thread, etc. /////////////////////////////////////////////////////////////////////////////// /** * Typedef for the functions used to implement NativeFunction.call. * @typedef {function(this: Interpreter.prototype.NativeFunction, * !Interpreter, * !Interpreter.Thread, * !Interpreter.State, * ?Interpreter.Value, * !Array) * : (?Interpreter.Value|!Interpreter.FunctionResult)} */ Interpreter.NativeCallImpl; /** * Typedef for the functions used to implement NativeFunction.construct. * @typedef {function(this: Interpreter.prototype.NativeFunction, * !Interpreter, * !Interpreter.Thread, * !Interpreter.State, * !Array) * : (?Interpreter.Value|!Interpreter.FunctionResult)} */ Interpreter.NativeConstructImpl; /** * An iterator over the properties of an ObjectLike and its * prototypes, following the usual for-in loop rules. * @constructor * @struct * @param {!Interpreter.ObjectLike} obj Object or Box whose properties * are to be iterated over. * @param {!Interpreter.Owner} perms Who is doing the iteration? */ Interpreter.PropertyIterator = function(obj, perms) { if (obj === undefined) { // Deserializing return; } /** @private @type {?Interpreter.ObjectLike} */ this.obj_ = obj; /** @private @const {!Interpreter.Owner} */ this.perms_ = perms; /** @private @type {!Array} */ this.keys_ = this.obj_.ownKeys(this.perms_); /** @private @type {number} */ this.i_ = 0; /** @private @const {!Set} */ this.visited_ = new Set(); }; /** * Return the next key in the iteration, skipping non-enumerable keys * or keys already seen earlier in the prototype chain (even if they * were non-enumerable). Returns undefined when iteration is done. * @return {string|undefined} */ Interpreter.PropertyIterator.prototype.next = function() { while (true) { if (this.i_ >= this.keys_.length) { this.obj_ = this.obj_.proto; if (this.obj_ === null) { // Done iteration. return undefined; } this.keys_ = this.obj_.ownKeys(this.perms_); this.i_ = 0; } var key = this.keys_[this.i_++]; var pd = this.obj_.getOwnPropertyDescriptor(key, this.perms_); // Skip deleted or already-visited properties. if (!pd || this.visited_.has(key)) { continue; } this.visited_.add(key); if (pd.enumerable) { return key; } } }; /** * Class for a scope. Implements Lexical Environments and the * Environment Record specification type from E5.1 §10.2 / ES6 §8.1. * @constructor * @struct * @param {!Interpreter.Scope.Type} type What variety of scope is it? * @param {!Interpreter.Owner} perms The permissions with which code * in the current scope is executing. * @param {?Interpreter.Scope} outerScope The enclosing scope ("outer * lexical environment reference", in ECMAScript spec parlance) * @param {?Interpreter.Value=} thisVal Value of 'this' in scope. * (Default: copy value from outerScope. N.B.: passing undefined * is NOT treated the same as passing no value!) */ Interpreter.Scope = function(type, perms, outerScope, thisVal) { /** @type {!Interpreter.Scope.Type} */ this.type = type; /** @type {!Interpreter.Owner} */ this.perms = perms; /** @type {?Interpreter.Scope} */ this.outerScope = outerScope; /** @type {?Interpreter.Value} */ this.this = (outerScope && arguments.length < 4) ? outerScope.this : thisVal; /** @const {!Object} */ this.vars = Object.create(null); }; /** * Returns true iff this scope has a binding for the given name. * * Based on HasBinding for declarative environment records, * from ES5.1 §10.2.1.1.1 / ES6 §8.1.1.1.1. * @param {string} name Name of variable. * @return {boolean} True iff name is bound in this scope. */ Interpreter.Scope.prototype.hasBinding = function(name) { return name in this.vars; }; /** * Returns true iff this scope has an immutable binding for the given * name. * * @param {string} name Name of variable. * @return {boolean} True iff name is immutably bound in this scope. */ Interpreter.Scope.prototype.hasImmutableBinding = function(name) { var pd = Object.getOwnPropertyDescriptor(this.vars, name); return Boolean(pd && !pd.writable); }; /** * Creates a mutable binding in this scope and initialises it to * undefined or the provided value. * * Based on CreateMutableBinding for declarative environment records, * from ES5.1 §10.2.1.1.2 / ES6 §8.1.1.1.2. * @param {string} name Name of variable. * @param {?Interpreter.Value=} value Initial value (default: undefined). */ Interpreter.Scope.prototype.createMutableBinding = function(name, value) { if (name in this.vars) { throw new Error(name + ' already has binding in this scope??'); } this.vars[name] = value; }; /** * Creates an immutable binding in this scope and initialises it * to the provided value. * * Based on CreateImmutableBinding for declarative environment records, * from ES5.1 §10.2.1.1.7 / ES6 §8.1.1.1.3. * @param {string} name Name of variable. * @param {?Interpreter.Value} value Initial value. */ Interpreter.Scope.prototype.createImmutableBinding = function(name, value) { if (name in this.vars) { throw new Error(name + ' already has binding in this scope??'); } Object.defineProperty(this.vars, name, Descriptor.ec.withValue(value)); }; /** * Updates a mutable binding in this scope to the the provided value. * * Based on SetMutableBinding for declarative environment records, * from ES5.1 §10.2.1.1.3 / ES6 §8.1.1.1.5. * @param {string} name Name of variable. * @param {?Interpreter.Value} value New value to set it to. * @return {!Error|undefined} If an error occurs, a (native) Error * object is returned. It shoud be converted into a user error * (e.g., by errorNativeToPseudo) and thrown. (This is done * because Scope is not an inner class of interpreter, and thus * this method has no access to the Error constructor or error * prototypes.) */ Interpreter.Scope.prototype.set = function(name, value) { try { this.vars[name] = value; } catch (e) { // Trying to set immutable binding. return TypeError('Assignment to constant variable ' + name); } }; /** * Returns the value of a binding in this scope. * * Based on GetBindingValue for declarative environment records, from * ES5.1 §10.2.1.1.4 / ES6 §8.1.1.1.6. * @param {string} name Name of variable. * @return {?Interpreter.Value} The current value of the named variable * in this scope. */ Interpreter.Scope.prototype.get = function(name) { return this.vars[name]; }; /** * Searches through this scope and its outer scopes to find a binding * for name, and returns the scope containing that binding or null if * name is not bound. * * Based on the Identifier Resolution algorithm of ES5.1 §10.3.1, or * equivalently the ResolveBinding specification function from ES6 * §8.3.1. * @param {string} name Name of variable. * @return {?Interpreter.Scope} The scope that binds name, or null if none. */ Interpreter.Scope.prototype.resolve = function(name) { for (var s = this; s; s = s.outerScope) { if (name in s.vars) return s; } return null; }; /** * Scope types. These correspond roughly to the list of environment * record types in ES6 §8.1.1 (declarative, object, function, global), * but omit ones we do not use (e.g., object), and distinguish between * different uses of declarative environment records (e.g., for * binding the name of a named function expression vs. binding the * name of the exception in a catch clause). * @enum {string} */ Interpreter.Scope.Type = { /** The global scope. */ GLOBAL: 'global', /** A function invocation scope. */ FUNCTION: 'function', /** A scope to contain the name of a named function expression. */ FUNEXP: 'funexp', /** An eval body scope. */ EVAL: 'eval', /** A catch clause scope. */ CATCH: 'catch', /** For use as a dummy - e.g. the caller scope in createThreadForFuncCall */ DUMMY: 'dummy', }; /** * Source is an encapsulated hunk of source text. Source objects can * be sliced to obtain a Source object representing a substring of the * original source text. Such sliced objects "remember" their * position within the original source text. * @constructor * @struct * @param {string} src Some source text * @param {number=} offset_ For internal use only. */ Interpreter.Source = function(src, offset_) { if (src === undefined) return; // Deserializing. /** @private @type {string} */ this.src_ = src; /** @private @type {number} */ this.offset_ = offset_ || 0; Object.freeze(this); }; /** * Return the contents of a Source object as an ordinary string. * @return {string} */ Interpreter.Source.prototype.toString = function() { return this.src_; }; /** * Return a Source object representing a substring of this Source * object. * @param {number} start Offset of first character of slice, as an absolute * position within the original source text. * @param {number} end Offset of character following last character of * slice, as an absolute position within the original source text. * @return {!Interpreter.Source} The sliced source. */ Interpreter.Source.prototype.slice = function(start, end) { if (start < this.offset_ || start > this.offset_ + this.src_.length) { throw new RangeError('Source slice start out of range'); } if (end < this.offset_ || end > this.offset_ + this.src_.length) { throw new RangeError('Source slice end out of range'); } if (start > end) { throw new RangeError('Source slice start past end'); } return new Interpreter.Source( this.src_.slice(start - this.offset_, end - this.offset_), start); }; /** * Return the (1-based) line and column numbers of a given position * within the Source object. * @param {number} pos Position whose line number we are interested * in, as an absolute position within the original source text. * @return {{line: number, col: number}} {line, col} tuple for the * position pos, relative to the start of this particular slice. */ Interpreter.Source.prototype.lineColForPos = function(pos) { if (pos < this.offset_ || pos > this.offset_ + this.src_.length) { throw new RangeError('Source position out of range'); } var lines = this.src_.slice(0, pos - this.offset_).split('\n'); return {line: lines.length, col: lines[lines.length - 1].length + 1}; }; /** * Class for a state. * @constructor * @struct * @param {!Node} node AST node for the state. * @param {!Interpreter.Scope} scope Scope dictionary for the state. * @param {boolean=} wantRef Does parent state want reference (rather * than evaluated value)? (Default: false.) */ Interpreter.State = function(node, scope, wantRef) { /** @const {!Node} */ this.node = node; /** @const {!Interpreter.Scope} */ this.scope = scope; /** @const {!Interpreter.StepFunction} */ this.stepFunc = node['stepFunc']; /** @private @const {boolean} */ this.wantRef_ = wantRef || false; /** @type {?Interpreter.Value} */ this.value = undefined; /** @type {?Array} */ this.ref = null; /** @type {?Array} */ this.labels = null; /** @type {boolean} */ this.isLoop = false; /** @type {boolean} */ this.isSwitch = false; /** @private @type {number} */ this.step_ = 0; /** @private @type {number} */ this.n_ = 0; /** @private @type {?Interpreter.Value|undefined} */ this.tmp_ = undefined; /** @private @type {?Interpreter.CallInfo| * ?Interpreter.ForInInfo| * ?Interpreter.SwitchInfo| * ?Interpreter.Completion} */ this.info_ = null; }; /** * Create a new State pre-configured to begin executing a function call. * @param {!Interpreter.prototype.Function} func Function to call. * @param {?Interpreter.Value} thisVal value of 'this' in function call. * @param {!Array} args Arguments to pass. * @param {!Interpreter.Owner} perms Who is doing the call? * @return {!Interpreter.State} The newly-created state. */ Interpreter.State.newForCall = function(func, thisVal, args, perms) { // Dummy node (used only for type). var node = new Node; node['type'] = 'Call'; node['stepFunc'] = stepFuncs_['Call']; // Dummy outer scope (used ony for perms, which will be caller perms). var scope = new Interpreter.Scope(Interpreter.Scope.Type.DUMMY, perms, null); var state = new Interpreter.State(node, scope); state.info_ = {func: func, this: thisVal, arguments: args, directEval: false, construct: false, funcState: undefined}; return state; }; /** * Information about a single call stack frame. * @typedef{(!{func: !Interpreter.prototype.Function, * this: ?Interpreter.Value, * callerPerms: !Interpreter.Owner}| * !{func: !Interpreter.prototype.Function, * this: ?Interpreter.Value, * callerPerms: !Interpreter.Owner, * line: number, * col: number}| * !{program: string}| * !{program: string, * line: number, * col: number}| * !{eval: string}| * !{eval: string, * line: number, * col: number})} */ var FrameInfo; /** * If this state represents a call stack frame, or otherwise should be * reported in the output of callers() or in the .stack of an Error * object, return an object containing information about it; * otherwise return undefined. * @return {!FrameInfo|undefined} */ Interpreter.State.prototype.frame = function() { switch (this.node['type']) { case 'Call': var info = /** @type{!Interpreter.CallInfo} */(this.info_); if (!info.func) throw new Error('No function for Call??'); return { func: info.func, this: info.this, callerPerms: this.scope.perms, // BUG(cpcallen:perms): wrong for bind. }; case 'Program': var source = this.node['source']; if (!source) throw new Error('No source for Program??'); return {program: String(source)}; case 'EvalProgram_': source = this.node['source']; if (!source) throw new Error('No source for EvalProgram_??'); return {eval: String(source)}; default: return undefined; } }; /** * Class for a thread of execution. * * Note that this is an internal class; it has a companion wrapper * class - Interpreter.prototype.Thread a.k.a. intrp.Thread - which * serves as a user-visible wrapper for this class. The two are * separate for performance reasons only. * @constructor * @struct * @param {number} id Thread ID. Should correspond to index of this * thread in .threads_ array. * @param {!Interpreter.State} state Starting state for thread. * @param {number} runAt Time at which to start running thread. * @param {number=} timeLimit Maximum runtime without suspending (in ms). */ Interpreter.Thread = function(id, state, runAt, timeLimit) { /** @type {number} */ this.id = id; // Say it's sleeping for now. May be woken immediately. /** @type {!Interpreter.Thread.Status} */ this.status = Interpreter.Thread.Status.SLEEPING; /** @private @type {!Array} */ this.stateStack_ = [state]; /** @type {number} */ this.runAt = runAt; /** @type {number} */ this.timeLimit = timeLimit || 0; /** @type {?Interpreter.prototype.Thread} */ this.wrapper = null; /** @type {?Interpreter.Value} */ this.value = undefined; }; /** * Returns the original source code for current state. * @param {number=} index Optional index in stack to look from. * @return {?Interpreter.Source} Source code or null if none. */ Interpreter.Thread.prototype.getSource = function(index) { index = (index === undefined) ? this.stateStack_.length - 1 : index; for (var i = index; i >= 0; i--) { var source = this.stateStack_[i].node['source']; if (source) return source; } return null; }; /** * Return information about the call stack. * @param {!Interpreter.Owner} perms Who wants callers info? * @return {!Array} The thread's call stack. */ Interpreter.Thread.prototype.callers = function(perms) { var frames = []; var pos; var lc; for (var i = this.stateStack_.length - 1; i >= 0; i--) { var state = this.stateStack_[i]; var node = state.node; if (pos !== undefined && 'source' in node) { lc = node['source'].lineColForPos(pos); } var frame; if ((frame = state.frame())) { // TODO(cpcallen:perms): Only include line/column info if func // is readable by perms - otherwise it leaks some information // about a supposedly-unreadable function. if (lc) { frame.line = lc.line; frame.col = lc.col; } lc = pos = undefined; frames[frames.length++] = frame; } if ((frame || frames.length === 0) && pos === undefined) { pos = node['start']; } } // TODO(cpcallen): add thread-initiator info. return frames; }; /** * Returns the permissions with which currently-executing code is * running (equivalent to a unix EUID, but in the form of a * user/group/etc. object). It is an error to call this function on a * thread that is a zombie. * @deprecated * @return {!Interpreter.Owner} */ Interpreter.Thread.prototype.perms = function() { if (this.status === Interpreter.Thread.Status.ZOMBIE) { throw new Error('Zombie thread has no perms'); } return this.stateStack_[this.stateStack_.length - 1].scope.perms; }; /** * Legal thread statuses. * @enum {number} */ Interpreter.Thread.Status = { /** Execution of the thread has terminated. */ ZOMBIE: 0, /** The thread is ready to run (or is running). */ READY: 1, /** The thread is blocked, awaiting an external event (e.g. callback). */ BLOCKED: 2, /** The thread is sleeping, awaiting arrival of its .runAt time. */ SLEEPING: 3, }; /////////////////////////////////////////////////////////////////////////////// // Inner classes of Interpreter: Declarations. /////////////////////////////////////////////////////////////////////////////// // Types representing JS objects - Object, Function, Array, etc. /** * Typedef for JS values. * @typedef {!Interpreter.prototype.Object|boolean|number|string|undefined|null} */ Interpreter.Value; /** * Interface for owners. Anything that is an Owner is really just a * normal !Interpreter.prototype.Object, but since since no concrete * class @implements this interface we force oruselves to cast back * and forth, helping to catch type errors. * @interface */ Interpreter.Owner = function() {}; /** * An interface for object-like entities: either actual * Interpreter.prototype.Objects or by non-user-visible boxed * primitives. * @interface */ Interpreter.ObjectLike = function() {}; /** @type {?Interpreter.prototype.Object} */ Interpreter.ObjectLike.prototype.proto; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {!Interpreter.Descriptor|undefined} */ Interpreter.ObjectLike.prototype.getOwnPropertyDescriptor = function(key, perms) {}; /** * @param {string} key * @param {!Interpreter.Descriptor} desc * @param {!Interpreter.Owner} perms */ Interpreter.ObjectLike.prototype.defineProperty = function(key, desc, perms) {}; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.ObjectLike.prototype.has = function(key, perms) {}; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {?Interpreter.Value} */ Interpreter.ObjectLike.prototype.get = function(key, perms) {}; /** * @param {string} key * @param {?Interpreter.Value} value * @param {!Interpreter.Owner} perms */ Interpreter.ObjectLike.prototype.set = function(key, value, perms) {}; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.ObjectLike.prototype.deleteProperty = function(key, perms) {}; /** @param {!Interpreter.Owner} perms @return {!Array} */ Interpreter.ObjectLike.prototype.ownKeys = function(perms) {}; /** @return {string} */ Interpreter.ObjectLike.prototype.toString = function() {}; /** @return {?Interpreter.Value} */ Interpreter.ObjectLike.prototype.valueOf = function() {}; /** * @constructor * @struct * @implements {Interpreter.ObjectLike} * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.Object = function(owner, proto) { /** @type {?Interpreter.Owner} */ this.owner; /** @type {?Interpreter.prototype.Object} */ this.proto; /** @const {!Object} */ this.properties; // TODO(cpcallen): this is kind of ugly, because connected Objects // have their shape mutated by the on('connect') handler in Server. // Consider rewriting it so that there is a WeakMap on Interpreter // instances mapping objects to their corresponding Socket. /** @type {!net.Socket|undefined} */ this.socket; throw new Error('Inner class constructor not callable on prototype'); }; /** @type {?Interpreter.prototype.Object} */ Interpreter.prototype.Object.prototype.proto = null; /** @type {string} */ Interpreter.prototype.Object.prototype.class = ''; /** * @param {?Interpreter.prototype.Object} proto * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.prototype.Object.prototype.setPrototypeOf = function(proto, perms) { throw new Error('Inner class method not callable on prototype'); }; /** @param {!Interpreter.Owner} perms @return {boolean} */ Interpreter.prototype.Object.prototype.isExtensible = function(perms) { throw new Error('Inner class method not callable on prototype'); }; /** @param {!Interpreter.Owner} perms @return {boolean} */ Interpreter.prototype.Object.prototype.preventExtensions = function(perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {!Interpreter.Descriptor|undefined} */ Interpreter.prototype.Object.prototype.getOwnPropertyDescriptor = function( key, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Descriptor} desc * @param {!Interpreter.Owner=} perms */ Interpreter.prototype.Object.prototype.defineProperty = function( key, desc, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.prototype.Object.prototype.has = function(key, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {?Interpreter.Value} */ Interpreter.prototype.Object.prototype.get = function(key, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {?Interpreter.Value} value * @param {!Interpreter.Owner} perms */ Interpreter.prototype.Object.prototype.set = function(key, value, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.prototype.Object.prototype.deleteProperty = function(key, perms) { throw new Error('Inner class method not callable on prototype'); }; /** @param {!Interpreter.Owner} perms @return {!Array} */ Interpreter.prototype.Object.prototype.ownKeys = function(perms) { throw new Error('Inner class method not callable on prototype'); }; /** @return {string} */ Interpreter.prototype.Object.prototype.toString = function() { throw new Error('Inner class method not callable on prototype'); }; /** @return {?Interpreter.Value} */ Interpreter.prototype.Object.prototype.valueOf = function() { throw new Error('Inner class method not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.Function = function(owner, proto) { throw new Error('Inner class constructor not callable on prototype'); }; /** * @param {?Interpreter.Value} value * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.prototype.Function.prototype.hasInstance = function(value, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} name * @param {string=} prefix */ Interpreter.prototype.Function.prototype.setName = function(name, prefix) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {!Interpreter} intrp The interpreter. * @param {!Interpreter.Thread} thread The current thread. * @param {!Interpreter.State} state The current state. * @param {?Interpreter.Value} thisVal The this value passed into function. * @param {!Array} args The arguments to the call. * @return {?Interpreter.Value|!Interpreter.FunctionResult} */ Interpreter.prototype.Function.prototype.call = function( intrp, thread, state, thisVal, args) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {!Interpreter} intrp The interpreter. * @param {!Interpreter.Thread} thread The current thread. * @param {!Interpreter.State} state The current state. * @param {!Array} args The arguments to the call. * @return {?Interpreter.Value|!Interpreter.FunctionResult} */ Interpreter.prototype.Function.prototype.construct = function( intrp, thread, state, args) { throw new Error('Inner class method not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Function} * @param {!Node} node * @param {!Interpreter.Scope} scope Enclosing scope. * @param {!Interpreter.Source} source * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.UserFunction = function( node, scope, source, owner, proto) { /** @type {!Node} */ this.node; /** @type {!Interpreter.Scope} */ this.scope; throw new Error('Inner class constructor not callable on prototype'); }; /** * @param {!Interpreter.Owner} owner * @param {?Interpreter.Value} thisVal * @param {!Array} args * @return {!Interpreter.Scope} * @private */ Interpreter.prototype.UserFunction.prototype.instantiateDeclarations_ = function(owner, thisVal, args) { throw new Error('Inner class method not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Function} * @param {!Interpreter.prototype.Function} func * @param {?Interpreter.Value} thisVal * @param {!Array} args * @param {?Interpreter.Owner=} owner */ Interpreter.prototype.BoundFunction = function(func, thisVal, args, owner) { /** @type {!Interpreter.prototype.Function} */ this.boundFunc; /** @type {?Interpreter.Value} */ this.thisVal; /** @type {!Array} */ this.args; throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Function} * @param {!NativeFunctionOptions=} options */ Interpreter.prototype.NativeFunction = function(options) { throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.NativeFunction} * @param {!Function} impl * @param {boolean} legalConstructor * @param {!NativeFunctionOptions=} options */ Interpreter.prototype.OldNativeFunction = function(impl, legalConstructor, options) { throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.Array = function(owner, proto) { throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {!Date} date * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.Date = function(date, owner, proto) { /** @type {!Date} */ this.date; throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {!RegExp=} re * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.RegExp = function(re, owner, proto) { /** @type {!RegExp} */ this.regexp; throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto * @param {string=} message * @param {!Array=} callers */ Interpreter.prototype.Error = function(owner, proto, message, callers) { throw new Error('Inner class constructor not callable on prototype'); }; /** * @param {!Array} callers * @param {!Interpreter.Owner} perms */ Interpreter.prototype.Error.prototype.makeStack = function(callers, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.Arguments = function(owner, proto) { throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {?Interpreter.Owner=} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.WeakMap = function(owner, proto) { /** @type {!IterableWeakMap} */ this.weakMap; throw new Error('Inner class constructor not callable on prototype'); }; /** * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {!Interpreter.Thread} thread * @param {!Interpreter.Owner} owner * @param {?Interpreter.prototype.Object=} proto */ Interpreter.prototype.Thread = function(thread, owner, proto) { /** @type {!Interpreter.Thread} */ this.thread; throw new Error('Inner class constructor not callable on prototype'); }; /////////////////////////////////////////////////////////////////////////////// // Other types, not representing JS objects. /** * @constructor * @struct * @implements {Interpreter.ObjectLike} * @param {(boolean|number|string)} prim */ Interpreter.prototype.Box = function(prim) { /** @private @type {(undefined|null|boolean|number|string)} */ this.primitive_; /** @type {!Interpreter.prototype.Object} */ this.proto; throw new Error('Inner class constructor not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {!Interpreter.Descriptor|undefined} */ Interpreter.prototype.Box.prototype.getOwnPropertyDescriptor = function( key, perms) { throw new Error('Inner class method not callable on prototype'); } /** * @param {string} key * @param {!Interpreter.Descriptor} desc * @param {!Interpreter.Owner} perms */ Interpreter.prototype.Box.prototype.defineProperty = function( key, desc, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.prototype.Box.prototype.has = function(key, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {?Interpreter.Value} */ Interpreter.prototype.Box.prototype.get = function(key, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @param {?Interpreter.Value} value */ Interpreter.prototype.Box.prototype.set = function(key, value, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {string} key * @param {!Interpreter.Owner} perms * @return {boolean} */ Interpreter.prototype.Box.prototype.deleteProperty = function(key, perms) { throw new Error('Inner class method not callable on prototype'); }; /** * @param {!Interpreter.Owner} perms * @return {!Array} */ Interpreter.prototype.Box.prototype.ownKeys = function(perms) { throw new Error('Inner class method not callable on prototype'); }; /** @return {string} String value. */ Interpreter.prototype.Box.prototype.toString = function() { throw new Error('Inner class method not callable on prototype'); }; /** @return {?Interpreter.Value} Value. */ Interpreter.prototype.Box.prototype.valueOf = function() { throw new Error('Inner class method not callable on prototype'); }; /** * @constructor * @struct * @param {!Interpreter.Owner} owner * @param {number} port * @param {!Interpreter.prototype.Object} proto * @param {number=} timeLimit */ Interpreter.prototype.Server = function(owner, port, proto, timeLimit) { /** @type {!Interpreter.Owner} */ this.owner; /** @type {number} */ this.port; /** @type {!Interpreter.prototype.Object} */ this.proto; /** @type {number} */ this.timeLimit; /** @private @type {!net.Server} */ this.server_; throw new Error('Inner class constructor not callable on prototype'); }; /** @param {!function(!Error=)=} callback */ Interpreter.prototype.Server.prototype.listen = function(callback) { throw new Error('Inner class method not callable on prototype'); }; /** @param {!function()=} callback */ Interpreter.prototype.Server.prototype.unlisten = function(callback) { throw new Error('Inner class method not callable on prototype'); }; /////////////////////////////////////////////////////////////////////////////// // Inner classes of Interpreter: Implementations. /////////////////////////////////////////////////////////////////////////////// /** * Install the actual Object, Function, Array, RegExp, Error, * etc. constructors on an Interpreter instance. Should * be called just once, from the Interpreter constructor. */ Interpreter.prototype.installTypes = function() { var intrp = this; // The interpreter instance to which these classes belong. ///////////////////////////////////////////////////////////////////////////// // Types representing JS objects - Object, Function, Array, etc. /** * Class for an object. * @constructor * @struct * @extends {Interpreter.prototype.Object} * @param {?Interpreter.Owner=} owner Owner object or null. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.Object = function(owner, proto) { if (proto === undefined) { proto = intrp.OBJECT; } if (owner === undefined) { owner = null; } this.owner = owner; this.proto = proto; this.properties = Object.create((proto === null) ? null : proto.properties); }; /** @type {?Interpreter.prototype.Object} */ intrp.Object.prototype.proto = null; /** @type {string} */ intrp.Object.prototype.class = 'Object'; /** * The [[SetPrototypeOf]] internal method from ES6 §9.1.2, with * substantial adaptations for Code City including added perms * checks. * * N.B.: Note that instead of returning false, this implementation * will throw a more specific error in the event that the set fails. * approriate error upon failure. * @param {?Interpreter.prototype.Object} proto The new prototype or null. * @param {!Interpreter.Owner} perms Who is trying set the prototype? * @return {boolean} True iff the set succeeded. */ intrp.Object.prototype.setPrototypeOf = function(proto, perms) { if (perms === null) throw new TypeError("null can't check extensibility"); // TODO(cpcallen:perms): add "controls"-type perm check. if (proto === this.proto) { // Doing nothing always succeeds. return true; } else if (!this.isExtensible(perms)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, "Can't set prototype of non-extensible object"); } for (var p = proto; p !== null; p = p.proto) { if (p === this) { throw new intrp.Error(perms, intrp.TYPE_ERROR, "An object's prototype chain can't include the object itself"); } } Object.setPrototypeOf(this.properties, proto && proto.properties); this.proto = proto; return true; }; /** * The [[IsExtensible]] internal method from ES6 §9.1.3, with * substantial adaptations for Code City including added perms * checks. * @param {!Interpreter.Owner} perms Who is trying to check? * @return {boolean} Is the object extensible? */ intrp.Object.prototype.isExtensible = function(perms) { if (perms === null) throw new TypeError("null can't check extensibility"); // TODO(cpcallen:perms): add check for (object) readability. return Object.isExtensible(this.properties); }; /** * The [[PreventExtensions]] internal method from ES6 §9.1.4, with * substantial adaptations for Code City including added perms * checks. * @param {!Interpreter.Owner} perms Who is trying to prevent extensions? * @return {boolean} Is the object extensible afterwards? */ intrp.Object.prototype.preventExtensions = function(perms) { if (perms === null) throw new TypeError("null can't prevent extensibions"); // TODO(cpcallen:perms): add "controls"-type perm check. Object.preventExtensions(this.properties); return true; }; /** * The [[GetOwnOwnProperty]] internal method from ES5.1 §8.12.1, * with substantial adaptations for Code City including added perms * checks (but no support for getter or setters). * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {!Interpreter.Descriptor|undefined} The property * descriptor, or undefined if no such property exists. */ intrp.Object.prototype.getOwnPropertyDescriptor = function(key, perms) { if (perms === null) { throw new TypeError("null can't getOwnPropertyDescriptor"); } // TODO(cpcallen:perms): add check for (property) readability. var pd = Object.getOwnPropertyDescriptor(this.properties, key); // TODO(cpcallen): can we eliminate this pointless busywork while // still maintaining type safety? return pd && new Descriptor(pd.writable, pd.enumerable, pd.configurable) .withValue(/** @type {?Interpreter.Value} */ (pd.value)); }; /** * The [[DefineOwnProperty]] internal method from ES5.1 §8.12.9, * with substantial adaptations for Code City including added perms * checks (but no support for getter or setters). * @param {string} key Key (name) of property to set. * @param {!Interpreter.Descriptor} desc The property descriptor. * @param {!Interpreter.Owner=} perms Who is trying to set it? If * omitted, defaults to this.owner but skips perm check. (This * is intended to be used only when constructing.) */ intrp.Object.prototype.defineProperty = function(key, desc, perms) { if (perms !== undefined) { if (perms === null) throw new TypeError("null can't defineProperty"); // TODO(cpcallen:perms): add "controls"-type perm check. } try { Object.defineProperty(this.properties, key, desc); } catch (e) { throw intrp.errorNativeToPseudo(e, perms || this.owner); } }; /** * The [[HasProperty]] internal method from ES5.1 §8.12.6, with * substantial adaptations for Code City including added perms * checks. * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {boolean} The value of the property, or undefined. */ intrp.Object.prototype.has = function(key, perms) { if (perms === null) throw new TypeError("null can't has"); // TODO(cpcallen:perms): add check for (object) readability. return key in this.properties; }; /** * The [[Get]] internal method from ES5.1 §8.12.3, with substantial * adaptations for Code City including added perms checks (but no * support for getters). * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {?Interpreter.Value} The value of the property, or undefined. */ intrp.Object.prototype.get = function(key, perms) { if (perms === null) throw new TypeError("null can't get"); // TODO(cpcallen:perms): add check for (property) readability. return this.properties[key]; }; /** * The [[Set]] internal method from ES5.1 §8.12.5, with substantial * adaptations for Code City including added perms checks (but no * support for setters). * @param {string} key Key (name) of property to set. * @param {!Interpreter.Owner} perms Who is trying to set it? * @param {?Interpreter.Value} value The new value of the property. */ intrp.Object.prototype.set = function(key, value, perms) { if (perms === null) throw new TypeError("null can't set"); // TODO(cpcallen:perms): add "controls"-type perm check. try { this.properties[key] = value; } catch (e) { throw intrp.errorNativeToPseudo(e, perms); } }; /** * The [[Delete]] internal method from ES5.1 §8.12.7, with * substantial adaptations for Code City including added perms * checks (but no support for getters). * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {boolean} True iff successful. */ intrp.Object.prototype.deleteProperty = function(key, perms) { if (perms === null) throw new TypeError("null can't delete"); // TODO(cpcallen:perms): add "controls"-type perm check. try { delete this.properties[key]; } catch (e) { throw intrp.errorNativeToPseudo(e, perms); } return true; }; /** * The [[OwnPropertyKeys]] internal method from ES6 §9.1.12, with * substantial adaptations for Code City including added perms * checks. * * TODO(cpcallen:perms): decide whether null user can read * properties. (At the moment this is forbidden redundantly by type * signature an runtime check; one or both should be removed.) * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {!Array} An array of own property keys. */ intrp.Object.prototype.ownKeys = function(perms) { if (perms === null) throw new TypeError("null can't ownPropertyKeys"); // TODO(cpcallen:perms): add check for (object) readability. return Object.getOwnPropertyNames(this.properties); }; /** * Convert this object into a string. * @return {string} String value. * @override */ intrp.Object.prototype.toString = function() { var c; // TODO(cpcallen:perms): perms check here? if (this instanceof intrp.Object) { c = this.class; } else { c = ({ undefined: 'Undefined', null: 'Null', boolean: 'Boolean', number: 'Number', string: 'String', })[typeof this]; } return '[object ' + c + ']'; }; /** * Return the object value. * @return {?Interpreter.Value} Value. * @override */ intrp.Object.prototype.valueOf = function() { return this; }; /** * Class for a function. * @constructor * @struct * @extends {Interpreter.prototype.Function} * @param {?Interpreter.Owner=} owner Owner object (default: null). * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.Function = function(owner, proto) { intrp.Object.call(/** @type {?} */ (this), owner, (proto === undefined ? intrp.FUNCTION : proto)); }; intrp.Function.prototype = Object.create(intrp.Object.prototype); intrp.Function.prototype.constructor = intrp.Function; intrp.Function.prototype.class = 'Function'; /** * Convert this function into a string. * @override * @this {!Interpreter.prototype.Function} */ intrp.Function.prototype.toString = function() { // Just do the simplest possible (spec-compliant) thing here. return 'function () { [native code] }'; }; /** * The [[HasInstance]] internal method from §15.3.5.3 of the ES5.1 spec. * @param {?Interpreter.Value} value The value to be checked for * being an instance of this function. * @param {!Interpreter.Owner} perms Who wants to know? Used in * readability check of .constructor property and as owner of * any Errors thrown. * @return {boolean} * @override */ intrp.Function.prototype.hasInstance = function(value, perms) { if (!(value instanceof intrp.Object)) { return false; } var prot = this.get('prototype', perms); if (!(prot instanceof intrp.Object)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, "Function has non-object prototype '" + prot + "' in instanceof check"); } for (var v = value.proto; v !== null; v = v.proto) { if (v === prot) { return true; } } return false; }; /** * Add a .name property to this function object. Implements * SetFunctionName from ES6 §9.2.11. * * N.B.: The setting is not subject to any perms checks, so it must * not be possible for a user to cause this internal method to be * invoked on any function object owned by another user. Typically * this will be enforced by only invoking this method at the time * the function is constructed, or immediately afterwards by a * lexically-enclosing expression having first used tested the * expression which resulted in the function value with * isAnonymousFunctionDefinition (q.v.). * * TODO(ES6): allow name to be type Symbol. * @param {string} name Name of function. * @param {string=} prefix Prefix for function name (e.g. 'get', 'bound'). * @override */ intrp.Function.prototype.setName = function(name, prefix) { if (prefix) { name = prefix + ' ' + name; } this.defineProperty('name', Descriptor.c.withValue(name)); }; /** * The [[Call]] internal method defined by §13.2.1 of the ES5.1 spec. * Generic functions (neither native nor user) can't be called. * @param {!Interpreter} intrp The interpreter. * @param {!Interpreter.Thread} thread The current thread. * @param {!Interpreter.State} state The current state. * @param {?Interpreter.Value} thisVal The this value passed into function. * @param {!Array} args The arguments to the call. * @return {?Interpreter.Value} * @override */ intrp.Function.prototype.call = function( intrp, thread, state, thisVal, args) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, "Class constructor " + this + " cannot be invoked without 'new'"); }; /** * The [[Construct]] internal method defined by §13.2.2 of the ES5.1 * spec. * Generic functions (neither native nor user) can't be constructed. * @param {!Interpreter} intrp The interpreter. * @param {!Interpreter.Thread} thread The current thread. * @param {!Interpreter.State} state The current state. * @param {!Array} args The arguments to the call. * @return {?Interpreter.Value} * @override */ intrp.Function.prototype.construct = function( intrp, thread, state, args) { throw new intrp.Error(state.scope.perms, intrp.TYPE_ERROR, this + ' is not a constructor'); }; /** * Class for a user-defined function. * @constructor * @struct * @extends {Interpreter.prototype.UserFunction} * @param {!Node} node AST node for function body. * @param {!Interpreter.Scope} scope Enclosing scope. * @param {!Interpreter.Source} source Source from which AST was parsed. * @param {?Interpreter.Owner=} owner Owner object (default: null). * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.UserFunction = function(node, scope, source, owner, proto) { if (!node) { // Deserializing return; } intrp.Function.call(/** @type {?} */ (this), owner, proto); this.node = node; this.scope = scope; if (node['id']) { this.setName(node['id']['name']); } var length = node['params'].length; this.defineProperty('length', Descriptor.none.withValue(length)); // Record the source on the function node's body node. Store it // on the AST (rather than on the UserFunction instance) because // each time a function expression is evaluated a new UserFunction // is created, but they all have identical source code. Store it // on the body node (rather than on the function node) because the // function node never appears on the stateStack_ when the // function is being executed. if (!node['body']['source']) { node['body']['source'] = source.slice(node['start'], node['end']); } // Add .prototype property pointing at a new plain Object. var protoObj = new intrp.Object(this.owner); this.defineProperty('prototype', Descriptor.w.withValue(protoObj)); protoObj.defineProperty('constructor', Descriptor.wc.withValue(this)); }; intrp.UserFunction.prototype = Object.create(intrp.Function.prototype); intrp.UserFunction.prototype.constructor = intrp.UserFunction; /** * Convert this function into a string. * @override */ intrp.UserFunction.prototype.toString = function() { // TODO(cpcallen:perms): perms check here? return String(this.node['body']['source']); }; /** * The [[Call]] internal method defined by §13.2.1 of the ES5.1 spec. * N.B.: This function (or any called from or overriding it) must * not use state.info_.funcState, as that it used by * Userfunction.prototype.construct, which calls us. * @override */ intrp.UserFunction.prototype.call = function( intrp, thread, state, thisVal, args) { if (this.owner === null) { throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR, 'Functions with null owner are not executable'); } var scope = this.instantiateDeclarations_(this.owner, thisVal, args); state.value = undefined; // Default value if no explicit return. thread.stateStack_[thread.stateStack_.length] = new Interpreter.State(this.node['body'], scope); return Interpreter.FunctionResult.AwaitValue; }; /** * The [[Construct]] internal method defined by §13.2.2 of the ES5.1 * spec. * @override */ intrp.UserFunction.prototype.construct = function( intrp, thread, state, args) { if (!state.info_.funcState) { // First visit. if (this.owner === null) { throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR, 'Functions with null owner are not constructable'); } // TODO(cpcallen:perms): Is it really OK to construct if caller // can't read .prototype? var proto = this.get('prototype', this.owner); // Per ES5.1 §13.2.2 step 7: if .prototype is primitive, use // Object.prototype instead. if (!(proto instanceof intrp.Object)) { proto = intrp.OBJECT; } state.info_.funcState = new intrp.Object(state.scope.perms, proto); this.call(intrp, thread, state, state.info_.funcState, args); return Interpreter.FunctionResult.CallAgain; } else { // Construction done. Check result. // Per ES5.1 §13.2.2 steps 9, 10: if constructor returns // primitive, return constructed object instead. if (!(state.value instanceof intrp.Object)) { return /** @type {?Interpreter.Value} */ (state.info_.funcState); } return state.value; } }; /** * A simplified version of the FunctionDeclarationInstantiation * specification function from ES6 §9.2.12 (see also Declaration * Binding Instantiation in ES5.1 §10.5). * * Creates a new Scope and sets up the bindings of the function's * parameters and variables. * @param {!Interpreter.Owner} owner Owner for new Scope. * @param {?Interpreter.Value} thisVal The value of 'this' for the call. * @param {!Array} args The arguments to the call. * @return {!Interpreter.Scope} The initialised scope * @private */ intrp.UserFunction.prototype.instantiateDeclarations_ = function( owner, thisVal, args) { // Aside: we need to pass owner, rather than // this.scope.perms, for the new scope perms because (1) we want // to be able to change the owner of a function after it's // created, and (2) functions created using the Function // constructor have this.scope set to the global scope, which is // owned by root! var scope = new Interpreter.Scope( Interpreter.Scope.Type.FUNCTION, owner, this.scope, thisVal); // Add all arguments to the scope. var params = this.node['params']; for (var i = 0; i < params.length; i++) { var paramName = params[i]['name']; var paramValue = args.length > i ? args[i] : undefined; scope.createMutableBinding(paramName, paramValue); } var body = this.node['body']; if (!('arguments' in getBoundNames(body)) && hasArgumentsOrEval(body)) { // Build arguments object. var argsObj = new intrp.Arguments(owner); argsObj.defineProperty( 'length', Descriptor.wc.withValue(args.length), owner); for (i = 0; i < args.length; i++) { argsObj.defineProperty( String(i), Descriptor.wec.withValue(args[i]), owner); } scope.createImmutableBinding('arguments', argsObj); } // Populate local variables and other inner declarations. intrp.populateScope_(body, scope); return scope; }; /** * Class for bound functions. See ES5 §15.3.4.5 / ES6 §9.4.1. * @constructor * @struct * @extends {Interpreter.prototype.BoundFunction} * @param {!Interpreter.prototype.Function} func Function to be bound. * @param {?Interpreter.Value} thisVal The this value passed into function. * @param {!Array} args Arguments to prefix to the call. * @param {?Interpreter.Owner=} owner Owner object (default: null). */ intrp.BoundFunction = function(func, thisVal, args, owner) { if (!func) return; // Deserializing intrp.Function.call(/** @type {?} */ (this), owner, func.proto); /** @type {!Interpreter.prototype.Function} */ this.boundFunc = func; /** @type {?Interpreter.Value} */ this.thisVal = thisVal; /** @type {!Array} */ this.args = args; }; intrp.BoundFunction.prototype = Object.create(intrp.Function.prototype); intrp.BoundFunction.prototype.constructor = intrp.BoundFunction; /** * The [[Call]] internal method for bound functions, defined by * ES5.1 §15.3.4.5.1 / ES6 §9.4.1.1. * * BUG(cpcallen:perms): the target function will see callerPerms * being whoever called the bound function, but should see * callerPerms being the owner of the bound function. * @override */ intrp.BoundFunction.prototype.call = function( intrp, thread, state, thisVal, args) { // TODO(cpcallen:perms): Consider carefully whose perms should be // used where! if (this.owner === null) { throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR, 'Functions with null owner are not executable'); } var argList = this.args.concat(args); // Rewrite state.info_, as a short-circuit optimisation in case // we get called again due to FunctionResult.CallAgain, and also // to produce more useful callers() output / stack traces. var info = state.info_; info.func = this.boundFunc; info.this = this.thisVal; info.args = argList; info.construct = false; // But just go and do the first .call directly. return this.boundFunc.call(intrp, thread, state, this.thisVal, argList); }; /** * The [[Construct]] internal method for bound functions, defined by * ES5.1 §15.3.4.5.2 / ES6 §9.4.1.2. * * BUG(cpcallen:perms): the target function will see callerPerms * being whoever called the bound function, but should see * callerPerms being the owner of the bound function. * @override */ intrp.BoundFunction.prototype.construct = function( intrp, thread, state, args) { // TODO(cpcallen:perms): Consider carefully whose perms should be // used where! if (this.owner === null) { throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR, 'Functions with null owner are not constructable'); } var argList = this.args.concat(args); // Rewrite state.info_, as a short-circuit optimisation in case // we get called again due to FunctionResult.CallAgain, and also // to produce more useful callers() output / stack traces. var info = state.info_; info.func = this.boundFunc; info.this = this.thisVal; info.args = argList; info.construct = true; // But just go and do the first .construct directly. return this.boundFunc.construct(intrp, thread, state, argList); }; /** * Class for a native function. Options are as follows: * * If options.name is a non-empty string, the new function object's * .name property will be set to this value. Otherwise, if * options.id is a non-empty string, the part following the last '.' * will be used instead. * * If options.length is supplied, the new object's .length will be * set to this value. * * If options.id is a non-empty string, the new native function * object will be registered as a builtin with that id value. * * The options.call and .construct will be used for the [[Call]] and * [[Construct]] specifications methods respectively. If omitted, * the function will not be callable / constructable. * * The new object will be owned by options.owner (default: * intrp.ROOT), and have prototype options.proto (default: * intrp.FUNCTION - i.e., Function.prototype). * * @constructor * @struct * @extends {Interpreter.prototype.NativeFunction} * @param {!NativeFunctionOptions=} options Options object for * constructing native function. */ intrp.NativeFunction = function(options) { options = options || {}; var owner = (options.owner !== undefined ? options.owner : intrp.ROOT); // Invoke super constructor. intrp.Function.call(/** @type {?} */ (this), owner, options.proto); // Set .name if name or id supplied, and save original name internally. // N.B.: Function.prototype gets .name === ''. /** The initial value of the .name property. @type {string|undefined} */ this.name = undefined; if (options.name !== undefined) { this.name = options.name; } else if (options.id) { this.name = options.id.replace(/^.*\./, ''); } if (this.name !== undefined) this.setName(this.name); // Set .length if length supplied. if (options.length !== undefined) { this.defineProperty('length', Descriptor.none.withValue(options.length), owner); } // Register as builtin if id supplied. if (options.id) { intrp.builtins.set(options.id, this); } // Install [[Call]] and [[Construct]] methods, making sure they // are labelled for serialization (if possible and not already). var serialId = options.id || options.name; if (options.call) { this.call = options.call; if (serialId && !('id' in this.call)) { this.call.id = serialId + ' [[Call]]'; } } if (options.construct) { this.construct = options.construct; if (serialId && !('id' in this.construct)) { this.construct.id = serialId + ' [[Construct]]'; } } }; intrp.NativeFunction.prototype = Object.create(intrp.Function.prototype); intrp.NativeFunction.prototype.constructor = intrp.NativeFunction; /** * Convert this function into a string. This implements * https://tc39.es/Function-prototype-toString-revision/#proposal-sec-function.prototype.tostring * (now adopted) as it applies to "Well-known Intrinsic Object[s]" * as well as any other NativeFunction constructed with specified * name or id. * @override */ intrp.NativeFunction.prototype.toString = function() { if (this.name === undefined) { return intrp.Function.prototype.toString.call(this); } // TODO(cpcallen): include formal parameter names? return 'function ' + this.name + '() { [native code] }'; }; /** * Class for an old native function. * @constructor * @struct * @extends {Interpreter.prototype.OldNativeFunction} * @param {!Function} impl Old-style native function implementation * @param {boolean} legalConstructor True if the function can be used as a * constructor (e.g. Array), false if not (e.g. escape). * @param {!NativeFunctionOptions=} options Options object for * constructing the underlying NativeFunction. */ intrp.OldNativeFunction = function(impl, legalConstructor, options) { if (!impl) return; // Deserializing intrp.NativeFunction.call(/** @type {?} */ (this), options); /** @type {!Function} */ this.impl = impl; /** @type {boolean} */ this.illegalConstructor = !legalConstructor; }; intrp.OldNativeFunction.prototype = Object.create(intrp.NativeFunction.prototype); intrp.OldNativeFunction.prototype.constructor = intrp.OldNativeFunction; /** @override */ intrp.OldNativeFunction.prototype.call = function( intrp, thread, state, thisVal, args) { if (this.owner === null) { throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR, 'Functions with null owner are not executable'); } return this.impl.apply(thisVal, args); }; /** @override */ intrp.OldNativeFunction.prototype.construct = function( intrp, thread, state, args) { if (this.illegalConstructor) { // Pass to super, which will complain about non-callability: intrp.Function.prototype.construct.call( /** @type {?} */ (this), intrp, thread, state, args); } if (this.owner === null) { throw new intrp.Error(state.scope.perms, intrp.PERM_ERROR, 'Functions with null owner are not constructable'); } return this.impl.apply(undefined, args); }; /** * Class for an array * @constructor * @struct * @extends {Interpreter.prototype.Array} * @param {?Interpreter.Owner=} owner Owner object or null. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.Array = function(owner, proto) { if (proto === undefined) { proto = intrp.ARRAY; } intrp.Object.call(/** @type {?} */ (this), owner, proto); this.properties = []; Object.setPrototypeOf(this.properties, (proto === null) ? null : proto.properties); }; intrp.Array.prototype = Object.create(intrp.Object.prototype); intrp.Array.prototype.constructor = intrp.Array; intrp.Array.prototype.class = 'Array'; /** * Convert array-like objects into a string. * @override */ intrp.Array.prototype.toString = function() { // BUG(cpcallen): toString should access properties on this with // the caller's permissions - but at present there is no way to // determine who it was called by, so use intrp.ANYBODY instead. var visited = intrp.toStringVisited_; if (visited.has(this)) { return ''; } visited.add(this); try { var strs = []; var len = this.get('length', intrp.ANYBODY); for (var i = 0; i < this.properties.length; i++) { var value = this.get(String(i), intrp.ANYBODY); if (value === null || value === undefined) { strs[i] = ''; } else { strs[i] = String(value); } } } finally { visited.delete(this); } return strs.join(','); }; /** * Class for a date. * @constructor * @struct * @extends {Interpreter.prototype.Date} * @param {!Date} date Date value for this Date object. * @param {?Interpreter.Owner=} owner Owner object or null. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.Date = function(date, owner, proto) { if (!date) return; // Deserializing intrp.Object.call(/** @type {?} */ (this), owner, (proto === undefined ? intrp.DATE : proto)); /** @type {!Date} */ this.date = date; }; intrp.Date.prototype = Object.create(intrp.Object.prototype); intrp.Date.prototype.constructor = intrp.Date; intrp.Date.prototype.class = 'Date'; /** * Return the date as a string. * @override */ intrp.Date.prototype.toString = function() { // TODO(cpcallen:perms): perms check here? return this.date.toString(); }; /** * Return the date as a numeric value. * @override */ intrp.Date.prototype.valueOf = function() { return this.date.valueOf(); }; /** * Class for a regexp * @constructor * @struct * @extends {Interpreter.prototype.RegExp} * @param {!RegExp=} re The RegExp value for this RegExp object. * @param {?Interpreter.Owner=} owner Owner object or null. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.RegExp = function(re, owner, proto) { if (!re) return; // Deserializing intrp.Object.call(/** @type {?} */ (this), owner, (proto === undefined ? intrp.REGEXP : proto)); /** @type {!RegExp} */ this.regexp = re; // lastIndex is settable, all others are read-only attributes this.defineProperty('lastIndex', Descriptor.w.withValue(re.lastIndex)); this.defineProperty('source', Descriptor.none.withValue(re.source)); this.defineProperty('global', Descriptor.none.withValue(re.global)); this.defineProperty('ignoreCase', Descriptor.none.withValue(re.ignoreCase)); this.defineProperty('multiline', Descriptor.none.withValue(re.multiline)); }; intrp.RegExp.prototype = Object.create(intrp.Object.prototype); intrp.RegExp.prototype.constructor = intrp.RegExp; intrp.RegExp.prototype.class = 'RegExp'; /** * Return the regexp as a string. * @override */ intrp.RegExp.prototype.toString = function() { // TODO(cpcallen:perms): perms check here? if (!(this.regexp instanceof RegExp)) { // TODO(cpcallen): ES5.1 §15.10.6.4 doesn't say what happens // when this is applied to a non-RegExp. ES6 §21.2.5.14 does - // and the results are possibly weird, e.g. returning // "/undefined/undefined" or the like... :-/ return '//'; } return this.regexp.toString(); }; /** * Class for an error object * @constructor * @struct * @extends {Interpreter.prototype.Error} * @param {?Interpreter.Owner=} owner Owner object or null. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. * @param {string=} message Optional message to be attached to error object. */ intrp.Error = function(owner, proto, message) { intrp.Object.call(/** @type {?} */ (this), owner, (proto === undefined ? intrp.ERROR : proto)); if (message !== undefined) { this.defineProperty('message', Descriptor.wc.withValue(message)); } }; intrp.Error.prototype = Object.create(intrp.Object.prototype); intrp.Error.prototype.constructor = intrp.Error; intrp.Error.prototype.class = 'Error'; /** * Return the error as a string. * @override */ intrp.Error.prototype.toString = function() { // BUG(cpcallen): toString should access properties on this with // the caller's permissions - but at present there is no way to // determine who it was called by, so use intrp.ANYBODY instead. var visited = intrp.toStringVisited_; if (visited.has(this)) { return ''; } visited.add(this); try { var name = this.get('name', intrp.ANYBODY); var message = this.get('message', intrp.ANYBODY); name = (name === undefined) ? 'Error' : String(name); message = (message === undefined) ? '' : String(message); if (name) { return message ? (name + ': ' + message) : name; } return message; } finally { visited.delete(this); } }; /** * Create a .stack property on the error from the given call stack * information, if it does not already have one. The stack property * will be created with the permissions of the owner of the Error * object. * * BUG(cpcallen): because this is called before unwinding the stack * when an intrp.Error is thrown, and because .stack is set * unconditionally (without perm check), any user can set .stack on * any Error object that doesn't already have one (including * e.g. Error.prototype) just by throwing it. * @param {!Array} callers List of call stack frames, * as returned by Thread.prototype.callers. * @param {!Interpreter.Owner} perms Whose perms should be used to * obtain (e.g.) function names, etc.? * @override */ intrp.Error.prototype.makeStack = function(callers, perms) { if (this.has('stack', intrp.ROOT)) { return; // Do not overwrite existing .stack } var stack = []; for (var i = 0; i < callers.length; i++) { var /** string */ line = ' '; var frame = callers[i]; if ('func' in frame) { var /** !Interpreter.prototype.Function */ func = frame.func; var /** string */ name; try { var pd = func.getOwnPropertyDescriptor('name', perms); if (pd) { name = String(pd.value); } else { name = 'anonymous function'; } } catch (e) { name = 'unreadable function'; } } else if ('eval' in frame) { name = '"' + frame.eval + '"'; } else if ('program' in frame) { name = '"' + frame.program + '"'; } if ('line' in frame) { line += 'at ' + name + ' ' + frame.line + ':' + frame.col; } else { line += 'in ' + name; } stack.push(line); } this.defineProperty('stack', Descriptor.wc.withValue(stack.join('\n'))); }; /** * Class for an arguments object. See ES5 §10.6 / ES6 §9.4.4. * * N.B.: Does not support mapped properties because we are always in * strict mode. Does not implement the special always-throw getters * for .callee and .caller, because we do not support getters. * What's left is basically an ordinary object with a special * [[Class]]. * @constructor * @struct * @extends {Interpreter.prototype.Arguments} * @param {?Interpreter.Owner=} owner Owner object or null. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.Arguments = function(owner, proto) { intrp.Object.call(/** @type {?} */ (this), owner, proto); }; intrp.Arguments.prototype = Object.create(intrp.Object.prototype); intrp.Arguments.prototype.constructor = intrp.Arguments; intrp.Arguments.prototype.class = 'Arguments'; /** * The WeakMap class from ES6. * @constructor * @struct * @extends {Interpreter.prototype.WeakMap} * @param {?Interpreter.Owner=} owner Owner object or null. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.WeakMap = function(owner, proto) { intrp.Object.call(/** @type {?} */ (this), owner, (proto === undefined ? intrp.WEAKMAP : proto)); /** @type {!IterableWeakMap} */ this.weakMap = new IterableWeakMap; }; intrp.WeakMap.prototype = Object.create(intrp.Object.prototype); intrp.WeakMap.prototype.constructor = intrp.WeakMap; intrp.WeakMap.prototype.class = 'WeakMap'; /** * Class for the user-visible representation of an Interpreter.Thread. * * Note that there should be at most one of these wrappers for each * Interpreter.Thread, and this constructor enforces this. * @constructor * @struct * @extends {Interpreter.prototype.Thread} * @param {!Interpreter.Thread} thread Thread represented by this object. * @param {!Interpreter.Owner} owner Owner of this thread. * @param {?Interpreter.prototype.Object=} proto Prototype object or null. */ intrp.Thread = function(thread, owner, proto) { if (!thread) return; // Deserializing if (thread.wrapper) { throw new Error('Duplicate Thread wrapper??'); } intrp.Object.call(/** @type {?} */ (this), owner, (proto === undefined ? intrp.THREAD : proto)); /** @type {!Interpreter.Thread} */ this.thread = thread; this.thread.wrapper = this; this.defineProperty('id', Descriptor.none.withValue(thread.id), owner); }; intrp.Thread.prototype = Object.create(intrp.Object.prototype); intrp.Thread.prototype.constructor = intrp.Thread; intrp.Thread.prototype.class = 'Thread'; ///////////////////////////////////////////////////////////////////////////// // Other types, not representing JS objects. /** * Class for a boxed primitive. Does not @extend * Interpreter.prototype.Object, because we do not want to expose * these to the users. They're just used internally to simplify the * implementation of various bits of code that are specified by * ES5.1 or ES6 to do ToObject(). * * @constructor * @struct * @extends {Interpreter.prototype.Box} * @param {(boolean|number|string)} prim Primitive to box */ intrp.Box = function(prim) { /** @private @type {(undefined|null|boolean|number|string)} */ this.primitive_ = prim; if (typeof prim === 'boolean') { /** @type {!Interpreter.prototype.Object} */ this.proto = intrp.BOOLEAN; } else if (typeof prim === 'number') { this.proto = intrp.NUMBER; } else if (typeof prim === 'string') { this.proto = intrp.STRING; } else { throw new Error('Invalid type in Box'); } }; /** * The [[GetOwnOwnProperty]] internal method from ES5.1 §8.12.1, as * applied to temporary Boolean, Number and String class objects. * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {!Interpreter.Descriptor|undefined} The property * descriptor, or undefined if no such property exists. * @override */ intrp.Box.prototype.getOwnPropertyDescriptor = function(key, perms) { var pd = Object.getOwnPropertyDescriptor(this.primitive_, key); // TODO(cpcallen): can we eliminate this pointless busywork while // still maintaining type safety? return pd && new Descriptor(pd.writable, pd.enumerable, pd.configurable) .withValue(/** @type {?Interpreter.Value} */ (pd.value)); }; /** * The [[DefineOwnProperty]] internal method from ES5.1 §8.12.9, as * applied to temporary Boolean, Number and String class objects. * @param {string} key Key (name) of property to set. * @param {!Interpreter.Descriptor} desc The property descriptor. * @param {!Interpreter.Owner} perms Who is trying to set it? * @override */ intrp.Box.prototype.defineProperty = function(key, desc, perms) { throw new intrp.Error(perms, intrp.TYPE_ERROR, "Cannot create property '" + key + "' on " + typeof this.primitive_ + " '" + this.primitive_ + "'"); }; /** * The [[HasProperty]] internal method from ES5.1 §8.12.6, as * applied to temporary Boolean, Number and String class objects. * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {boolean} The value of the property, or undefined. * @override */ intrp.Box.prototype.has = function(key, perms) { // Important: we want to ignore any extra properties on (e.g.) the // native String.prototype, but be sure to find ones on // intrp.String.prototype. if (Object.getOwnPropertyDescriptor(this.primitive_, key)) { return true; } // Defer to prototype. return this.proto.has(key, perms); }; /** * The [[Get]] internal method from ES5.1 §8.12.3, as applied to * temporary Boolean, Number and String class objects. * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {?Interpreter.Value} The value of the property, or undefined. * @override */ intrp.Box.prototype.get = function(key, perms) { // Important: we want to ignore any extra properties on (e.g.) the // native String.prototype, but be sure to find ones on // intrp.String.prototype. var pd = Object.getOwnPropertyDescriptor(this.primitive_, key); if (pd) { return /** @type {string|number} */(pd.value); } // Defer to prototype. return this.proto.get(key, perms); }; /** * The [[Set]] internal method from ES5.1 §8.12.5, as * applied to temporary Boolean, Number and String class objects. * @param {string} key Key (name) of property to set. * @param {!Interpreter.Owner} perms Who is trying to set it? * @param {?Interpreter.Value} value The new value of the property. * @override */ intrp.Box.prototype.set = function(key, value, perms) { throw new intrp.Error(perms, intrp.TYPE_ERROR, "Cannot set property '" + key + "' on " + typeof this.primitive_ + " '" + this.primitive_ + "'"); }; /** * The [[Delete]] internal method from ES5.1 §8.12.7, as applied to * temporary Boolean, Number and String class objects. * @param {string} key Key (name) of property to get. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {boolean} True iff successful. */ intrp.Box.prototype.deleteProperty = function(key, perms) { // Attempting to delete property from primitive value. Succeeds // only if property doesn't exist. if (Object.getOwnPropertyDescriptor(this.primitive_, key)) { throw new intrp.Error(perms, intrp.TYPE_ERROR, "Cannot delete property '" + key + "' on " + typeof this.primitive_ + " '" + this.primitive_ + "'"); } return true; }; /** * The [[OwnPropertyKeys]] internal method from ES6 §9.1.12, as * applied to temporary Boolean, Number and String class objects. * @param {!Interpreter.Owner} perms Who is trying to get it? * @return {!Array} An array of own property keys. */ intrp.Box.prototype.ownKeys = function(perms) { // Cast necessitated by compiler bug: // https://github.com/google/closure-compiler/issues/2878 return Object.getOwnPropertyNames(/** @type {?} */(this.primitive_)); }; /** * Convert this boxed primitive into a string. * @return {string} String value. * @override */ intrp.Box.prototype.toString = function() { return String(this.primitive_); }; /** * Return the boxed primitive value. * @return {?Interpreter.Value} Value. * @override */ intrp.Box.prototype.valueOf = function() { return this.primitive_; }; /** * Server is an (owner, port, proto, (extra info)) tuple representing a * listening server. It encapsulates node's net.Server type, with * some additional info needed to implement the connectionListen() * API. In its present form it is not suitable for exposure as a * userland pseduoObject, but it is intended to be easily adaptable * for that if desired. * @constructor * @struct * @extends {Interpreter.prototype.Server} * @param {!Interpreter.Owner} owner Owner object or null. * @param {number} port Port to listen on. * @param {!Interpreter.prototype.Object} proto Prototype object for * new connections. * @param {number=} timeLimit Maximum runtime without suspending (in ms). */ intrp.Server = function(owner, port, proto, timeLimit) { // Special excepetion: port === undefined when deserializing, in // violation of usual type rules. if ((port !== (port >>> 0) || port > 0xffff) && port !== undefined) { throw new RangeError('invalid port ' + port); } /** @type {!Interpreter.Owner} */ this.owner = owner; /** @type {number} */ this.port = port; /** @type {!Interpreter.prototype.Object} */ this.proto = proto; /** @type {number} */ this.timeLimit = timeLimit || 0; /** @type {!net.Server} */ this.server_ = new net.Server({allowHalfOpen: true}); // Create the net.Server instance and set up event handlers but // don't yet start it listening. var server = this; // So we can refer to it in handlers below. this.server_.on('connection', function(socket) { intrp.log('net', 'Connection on :%s from %s:%s', server.port, socket.remoteAddress, socket.remotePort); // TODO(cpcallen): Add localhost test here, like this - only // also allow IPV6 connections: // if (socket.remoteAddress != '127.0.0.1') { // // Reject connections other than from localhost. // intrp.log('net', 'Rejecting connection from ' + // socket.remoteAddress); // socket.end('Connection rejected.'); // return; // } // Create new object from proto and call onConnect. var obj = new intrp.Object(server.owner, server.proto); obj.socket = socket; var func = obj.get('onConnect', server.owner); if (func instanceof intrp.Function && server.owner !== null) { // TODO(cpcallen:perms): Is server.owner the correct owner for // the thread? Note that this will typically be root, and // .onConnect will therefore get caller perms === root, which // is probably dangerous. Here and several places below. intrp.createThreadForFuncCall( server.owner, func, obj, [], undefined, server.timeLimit); } // Handle socket closing completely. socket.on('close', function() { intrp.log('net', 'Connection on :%s from %s:%s closed', server.port, socket.remoteAddress, socket.remotePort); var func = obj.get('onClose', server.owner); if (func instanceof intrp.Function && server.owner !== null) { intrp.createThreadForFuncCall( server.owner, func, obj, [], undefined, server.timeLimit); } }); // Handle incoming data from clients. N.B. that data is a // node buffer object, so we must convert it to a string // before passing it to user code. socket.on('data', function(data) { var func = obj.get('onReceive', server.owner); if (func instanceof intrp.Function && server.owner !== null) { intrp.createThreadForFuncCall( server.owner, func, obj, [String(data)], undefined, server.timeLimit); } }); // Handle far end closing connection. socket.on('end', function() { intrp.log('net', 'Connection on :%s from %s:%s ended', server.port, socket.remoteAddress, socket.remotePort); var func = obj.get('onEnd', server.owner); if (func instanceof intrp.Function && server.owner !== null) { intrp.createThreadForFuncCall( server.owner, func, obj, [], undefined, server.timeLimit); } }); // Handle errors. socket.on('error', function(error) { intrp.log('net', 'Socket error on :%s from %s:%s: %s: %s', server.port, socket.remoteAddress, socket.remotePort, error.name, error.message); var func = obj.get('onError', server.owner); if (func instanceof intrp.Function && server.owner !== null) { var userError = intrp.errorNativeToPseudo(error, server.owner); intrp.createThreadForFuncCall( server.owner, func, obj, [userError], undefined, server.timeLimit); } }); // TODO(cpcallen): save new object somewhere we can find it // later (when we want to obtain list of connected objects). }); this.server_.on('listening', function() { var addr = this.address(); intrp.log('net', 'Listening on %s %s:%s', addr.family, addr.address, addr.port); }); this.server_.on('error', function(error) { intrp.log('net', 'Error on :%s: %s: %s', server.port, error.name, error.message); }); this.server_.on('close', function() { intrp.log('net', 'Stopped listening on :%s', server.port); }); }; /** * Start a Server object listening on its assigned port. * @param {!function(!Error=)=} callback * Callback that will be called once listening has begun, or with * an Error argument if listening fails. */ intrp.Server.prototype.listen = function(callback) { // Invariant checks. if (this.port === undefined || !(this.proto instanceof intrp.Object) || !(this.server_ instanceof net.Server)) { throw new Error('invalid Server state'); } if (intrp.listeners_[this.port] !== this) { throw new Error('Listening on server not listed in .listeners_??'); } // Set up callbacks. Fiddly, because we want to temporarily hook // the error handler but be sure to unhook it whether the listen // call succeeds or fails. var /** boolean */ done = false; /** @type {function(this:net.Server, !Error=)} */ function hook(error) { if (done) throw new Error('unexpected multiple callbacks'); done = true; this.removeListener(events.errorMonitor, hook); if (callback) callback(error); }; this.server_.on(events.errorMonitor, hook); this.server_.listen(this.port, hook); }; /** * Stop a Server object listening on its assigned port. * @param {!function()=} callback Callback that will be called after * listening has ceased. */ intrp.Server.prototype.unlisten = function(callback) { // Invariant checks. if (this.port === undefined || !(this.proto instanceof intrp.Object) || !(this.server_ instanceof net.Server)) { throw new Error('invalid Server state'); } this.server_.close(callback); }; }; /////////////////////////////////////////////////////////////////////////////// // Miscellaneous internal classes not used for storing state and not exported /////////////////////////////////////////////////////////////////////////////// /** * Type for options object for constructing a NativeFunction. * @typedef {{name: (string|undefined), * length: (number|undefined), * id: (string|undefined), * call: (Interpreter.NativeCallImpl|undefined), * construct: (Interpreter.NativeConstructImpl|undefined), * owner: (!Interpreter.Owner|undefined), * proto: (?Interpreter.prototype.Object|undefined)}} */ var NativeFunctionOptions; /** * Type for property descriptors, as used by * Interpreter.prototype.Object.prototype.defineProperty and * ...getOwnPropertyDescriptor. * @record */ Interpreter.Descriptor = function() {}; /** @type {(?Interpreter.Value|undefined)} */ Interpreter.Descriptor.prototype.value; /** @type {boolean|undefined} */ Interpreter.Descriptor.prototype.writable; /** @type {boolean|undefined} */ Interpreter.Descriptor.prototype.enumerable; /** @type {boolean|undefined} */ Interpreter.Descriptor.prototype.configurable; /** * Convenience class for creating Interpreter.Descriptors, with * commonly-used examples and a function to easily create new * descriptors from a prototype. * @constructor * @struct * @implements {Interpreter.Descriptor} * @param {boolean=} writable Is the property writable? * @param {boolean=} enumerable Is the property enumerable? * @param {boolean=} configurable Is the property configurable? */ var Descriptor = function(writable, enumerable, configurable) { if (writable !== undefined) this.writable = writable; if (enumerable !== undefined) this.enumerable = enumerable; if (configurable !== undefined) this.configurable = configurable; }; /* Type declaration for the properties that * intrp.Object.prototype.defineProperty expects to see on a * descriptor. We use "|undefined)", but what we really mean is "|not * defined)" because unfortunately Closure Compiler's type system has * no way to represent the latter. */ /** @type {(?Interpreter.Value|undefined)} */ Descriptor.prototype.value; /** @type {boolean|undefined} */ Descriptor.prototype.writable; /** @type {boolean|undefined} */ Descriptor.prototype.enumerable; /** @type {boolean|undefined} */ Descriptor.prototype.configurable; /** * Returns a new descriptor with the same properties as this one, with * the addition of a value: member with the given value. * @param {?Interpreter.Value} value Value for the new descriptor. * @return {!Descriptor} */ Descriptor.prototype.withValue = function(value) { var desc = /** @type{!Descriptor} */(Object.create(this)); desc.value = value; return desc; }; /** @const */ Descriptor.wec = new Descriptor(true, true, true); /** @const */ Descriptor.ec = new Descriptor(false, true, true); /** @const */ Descriptor.wc = new Descriptor(true, false, true); /** @const */ Descriptor.we = new Descriptor(true, true, false); /** @const */ Descriptor.w = new Descriptor(true, false, false); /** @const */ Descriptor.e = new Descriptor(false, true, false); /** @const */ Descriptor.c = new Descriptor(false, false, true); /** @const */ Descriptor.none = new Descriptor(false, false, false); /////////////////////////////////////////////////////////////////////////////// // Static Analysis Functions /////////////////////////////////////////////////////////////////////////////// /** * Get the list of BoundNames for an AST sub-tree. * @param {!Node} node AST node (program or function). * @return {!Object} A map of * bound names. The keys are var and function declarations * appearing in the subtree rooted at node; the values are * undefined for VariableDeclarations or a FunctionDeclaration * node for FunctionDeclarations. */ var getBoundNames = function(node) { if (!node['boundNames']) { performStaticAnalysis(node); } return node['boundNames']; }; /** * Check if an AST contains Identifiers named "arguments" or "eval". * @param {!Node} node AST node (program or function). * @return boolean True iff tree rooted at node contains an Identifier * named "arguments" or "eval", not including any * FunctionDeclaration or FunctionExpression subtrees. */ var hasArgumentsOrEval = function(node) { if (node['hasArgumentsOrEval'] === undefined) { performStaticAnalysis(node); } return node['hasArgumentsOrEval']; }; /** * The IsAnonymousFunctionDefinition specification method from ES6 §14.1.9 * @param {!Node} node The node to be tested. * @return {boolean} True if node is an anonymous function expression. */ var isAnonymousFunctionDefinition = function(node) { return node['type'] === 'FunctionExpression' && !node['id']; }; /** * The IsIdentifierRef specification method from ES6 §12.2.1.4 and §12.3.1.4 * @param {!Node} node The node to be tested. * @return {boolean} True if node is an identifier. */ var isIdentifierRef = function(node) { return node['type'] === 'Identifier'; }; /** * Returns true iff node is a MemberExpression. * @param {!Node} node The node to be tested. * @return {boolean} True if node is an identifier. */ var isMemberRef = function(node) { return node['type'] === 'MemberExpression'; }; /** * Walk an AST (or sub-tree), collecting bound names by looking for * VariableDeclaration and FunctionDeclaration nodes, and checking for * Identifiers named "arguments" or "eval". * * The BoundNames will be stored on node['boundNames'] as an * !Object, where the keys are * the names of VariableDeclaration and FunctionDeclarations, and the * values are undefined for VariableDeclarations or a * FunctionDeclaration node for FunctionDeclarations. * * If any Identifier named "arguments" or "eval" is seen, and * node['hasArgumentsOrEval'] will be set to true; otherwise it will * be set to false. * * @param {!Node} node AST node (program or function). * @return {void} */ var performStaticAnalysis = function(node) { /** !Object */ var boundNames = node['boundNames'] = Object.create(null); var hasArgumentsOrEval = false; walk(node); node['hasArgumentsOrEval'] = hasArgumentsOrEval; /** * Recursively Walk an AST sub-tree, populating boundNames as we go. * @param {!Node} node AST node (program or function). * Nested function writes to boundNames and hasArgumentsOrEval. * @return {void} * TODO(cpcallen): Limit recursion to only AST nodes that can * contain declarations (e.g. no ExpressionStatements?) */ function walk(node) { if (node['type'] === 'VariableDeclaration') { for (var i = 0; i < node['declarations'].length; i++) { // VariableDeclarations can't overwrite previous // FunctionDeclarations (but initializer might at run time). var name = node['declarations'][i]['id']['name']; if (!(name in boundNames)) { boundNames[name] = undefined; } } } else if (node['type'] === 'Identifier') { name = node['name']; if (name === 'arguments' || name === 'eval') { hasArgumentsOrEval = true; } } else if (node['type'] === 'FunctionDeclaration') { // FunctionDeclarations overwrite any previous decl of the same name. name = node['id']['name']; boundNames[name] = node; return; // Do not recurse into function. } else if (node['type'] === 'FunctionExpression') { return; // Do not recurse into function. } // Visit node's children. for (var key in node) { var prop = node[key]; if (prop && typeof prop === 'object') { if (Array.isArray(prop)) { for (var i = 0; i < prop.length; i++) { if (prop[i] && prop[i] instanceof Node) { walk(prop[i]); } } } else { if (prop instanceof Node) { walk(prop); } } } } } }; /////////////////////////////////////////////////////////////////////////////// // Step Functions: one to handle each node type. /////////////////////////////////////////////////////////////////////////////// /** * Typedef for step functions. * * TODO(cpcallen): It should be possible to declare individual * functions below using this typedef (instead of listing full type * details for each once * https://github.com/google/closure-compiler/issues/2857 is fixed. * @typedef {function(this: Interpreter, * !Interpreter.Thread, * !Array, * !Interpreter.State, * !Node) * : (!Interpreter.State|undefined)} */ Interpreter.StepFunction; /** * 'Map' of node types to their corresponding step functions. Note * that a Map is much slower than a null-parent object (v8 in 2017). * @const {!Object} */ var stepFuncs_ = Object.create(null); /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ArrayExpression'] = function(thread, stack, state, node) { var n = state.n_; if (!state.tmp_) { // Create Array object state.tmp_ = new this.Array(state.scope.perms); } else { // Save most recently-evaluated element. state.tmp_.set(String(n), state.value, state.scope.perms); n++; } var /** !Array */ elements = node['elements']; // Skip any elided elements - they're not defined, not undefined. while (n < elements.length && ! elements[n]) { n++; } // Evaluate next element, if we've not run past end. if (n < elements.length) { state.n_ = n; return new Interpreter.State(elements[n], state.scope); } state.tmp_.set('length', elements.length, state.scope.perms); stack.pop(); stack[stack.length - 1].value = state.tmp_; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['AssignmentExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Get Reference to left. state.step_ = 1; // Get Reference for left subexpression. return new Interpreter.State(node['left'], state.scope, true); } if (!state.ref) throw new TypeError('left subexpression not an LVALUE??'); if (state.step_ === 1) { // Evaluate right. if (node['operator'] !== '=') { state.tmp_ = this.getValue(state.ref, state.scope.perms); } state.step_ = 2; return new Interpreter.State(node['right'], state.scope); } // state.step_ === 2: Got operand(s); do assignment. var rightValue = state.value; var value = state.tmp_; switch (node['operator']) { // Regular assignment is special due to function naming & destructuring. case '=': value = rightValue; // Set name if anonymous function expression. if (isAnonymousFunctionDefinition(node['right']) && (isIdentifierRef(node['left']) || (this.options.methodNames && isMemberRef(node['left'])))) { var func = /** @type {!Interpreter.prototype.Function} */(value); // TODO(ES6): Check that func does not already have a 'name' // own property before calling setName? (Spec requires, but // unclear why since we know RHS is anonymous. Proxies?) func.setName(state.ref[1]); } break; // All the rest are simple and similar. case '+=': value += rightValue; break; case '-=': value -= rightValue; break; case '*=': value *= rightValue; break; case '/=': value /= rightValue; break; case '%=': value %= rightValue; break; case '<<=': value <<= rightValue; break; case '>>=': value >>= rightValue; break; case '>>>=': value >>>= rightValue; break; case '&=': value &= rightValue; break; case '^=': value ^= rightValue; break; case '|=': value |= rightValue; break; default: throw new SyntaxError( 'Unknown assignment expression: ' + node['operator']); } this.setValue(state.ref, value, state.scope.perms); stack.pop(); stack[stack.length - 1].value = value; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['BinaryExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Evaluate left. state.step_ = 1; return new Interpreter.State(node['left'], state.scope); } if (state.step_ === 1) { // Save left; evaluate right. state.step_ = 2; state.tmp_ = state.value; return new Interpreter.State(node['right'], state.scope); } // state.step_ === 2: Got operands; do binary operation. var leftValue = state.tmp_; var rightValue = state.value; var /** ?Interpreter.Value */ value; switch (node['operator']) { case '==': value = leftValue == rightValue; break; case '!=': value = leftValue != rightValue; break; case '===': value = leftValue === rightValue; break; case '!==': value = leftValue !== rightValue; break; case '>': value = leftValue > rightValue; break; case '>=': value = leftValue >= rightValue; break; case '<': value = leftValue < rightValue; break; case '<=': value = leftValue <= rightValue; break; case '+': value = leftValue + rightValue; break; case '-': value = leftValue - rightValue; break; case '*': value = leftValue * rightValue; break; case '/': value = leftValue / rightValue; break; case '%': value = leftValue % rightValue; break; case '&': value = leftValue & rightValue; break; case '|': value = leftValue | rightValue; break; case '^': value = leftValue ^ rightValue; break; case '<<': value = leftValue << rightValue; break; case '>>': value = leftValue >> rightValue; break; case '>>>': value = leftValue >>> rightValue; break; case 'in': if (!(rightValue instanceof this.Object)) { throw new this.Error(state.scope.perms, this.TYPE_ERROR, "'in' expects an object, not '" + rightValue + "'"); } value = rightValue.has(String(leftValue), state.scope.perms); break; case 'instanceof': if (!(rightValue instanceof this.Function)) { throw new this.Error(state.scope.perms, this.TYPE_ERROR, 'Right-hand side of instanceof is not a function'); } value = rightValue.hasInstance(leftValue, state.scope.perms); break; default: throw new SyntaxError('Unknown binary operator: ' + node['operator']); } stack.pop(); stack[stack.length - 1].value = value; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['BlockStatement'] = function(thread, stack, state, node) { var n = state.n_; var /** ?Node */ statement = node['body'][n]; if (statement) { state.n_ = n + 1; return new Interpreter.State(statement, state.scope); } stack.pop(); }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['BreakStatement'] = function(thread, stack, state, node) { if (!thread) throw new Error('No thread in BreakStatement??'); this.unwind_(thread, Interpreter.CompletionType.BREAK, undefined, node['label'] ? node['label']['name'] : undefined ); }; /** * Extra info used by CallExpression, NewExpression and Call step * functions: * - func: the function to be called or constructed. * - this: the value of 'this' for the call. * - arguments: (evaluated) arguments to the call. * - directEval: is this a direct call to the global eval function? * - construct: is this a [[Construct]] call (rather than default [[Call]])? * - funcState: place for NativeFunction impls to save additional state info. * TODO(cpcallen): give funcState a narrower type. * @typedef {{func: ?Interpreter.prototype.Function, * this: ?Interpreter.Value, * arguments: !Array, * directEval: boolean, * construct: boolean, * funcState: *}} */ Interpreter.CallInfo; /** * CallExpression AND NewExpression: the initial part that evaluates * the arguments etc. * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['CallExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Evaluate callee. // Special hack for Code City's "new 'foo'" syntax. if (node['type'] === 'NewExpression' && node['callee']['type'] === 'Literal' && typeof node['callee']['value'] === 'string' && node['arguments'].length === 0) { var builtin = node['callee']['value']; if (!this.builtins.has(builtin)) { throw new this.Error(state.scope.perms, this.REFERENCE_ERROR, builtin + ' is not a builtin'); } stack.pop(); stack[stack.length - 1].value = this.builtins.get(builtin); return; } state.step_ = 1; // Get reference for callee, because we need to get value of 'this'. return new Interpreter.State(node['callee'], state.scope, true); } if (state.step_ === 1) { // Evaluated callee, possibly got a reference. // Determine value of the function. state.step_ = 2; var info = {func: null, this: undefined, // Since we have no global object. arguments: [], directEval: false, construct: state.node['type'] === 'NewExpression', funcState: undefined}; if (state.ref) { // Callee was MemberExpression or Identifier. state.tmp_ = this.getValue(state.ref, state.scope.perms); if (state.ref[0] instanceof Interpreter.Scope) { // (Globally or locally) named function - maybe named 'eval'? info.directEval = (state.ref[1] === 'eval'); } else { // Method call; save 'this' value. info.this = state.ref[0]; } } else { // Callee already fully evaluated. state.tmp_ = state.value; } state.info_ = info; state.n_ = 0; } if (state.step_ === 2) { // Evaluating arguments. if (state.n_ !== 0) { // Save previous arg. state.info_.arguments[state.info_.arguments.length] = state.value; } if (node['arguments'][state.n_]) { // Evaluate next arg. return new Interpreter.State(node['arguments'][state.n_++], state.scope); } // All args evaluated. Check info_.func is actually a function. state.step_ = 3; // N.B: SEE NOTE 1 ABOVE! if (!(state.tmp_ instanceof this.Function)) { throw new this.Error(state.scope.perms, this.TYPE_ERROR, state.tmp_ + ' is not a function'); } state.info_.func = state.tmp_; } // state.step_ === 3: Done evaluating arguments; do function call. // Dummy Node (used only for type and position). var callNode = new Node; callNode['type'] = 'Call'; callNode['stepFunc'] = stepFuncs_['Call']; callNode['start'] = node['start']; // New State for Call (or Construct). var callState = new Interpreter.State(callNode, state.scope); callState.info_ = state.info_; // Replace this CallExpression State with the new Call State. stack[stack.length - 1] = callState; // We know exactly which step function will get called next, so go // straight there: return stepFuncs_['Call'].call(this, thread, stack, callState, callNode); }; /** * Call: the latter part of CallExpression / NewExpression, when the * actual call/construct takes place. * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['Call'] = function(thread, stack, state, node) { /* NOTE: Beware that, because * * - an async function might not *actually* be async, and thus * - its .call function might call its reject before returning, and * - reject will unwind the stack, and * - Interpreter#step and Interpreter#run will push any State * returned by a step function such as this one, * * this Call step function MUST NOT return a State after * calling .call (or .construct), or the thread might end up in some * nonsensical, corrupt configuration. * * (It's fine to return a State if it *hasn't* called .call or * .construct - for example, on a subsequent invocation - though * there is no obvious reason to do so.) */ if (state.step_ === 0) { // Done evaluating arguments; do function call. state.step_ = 1; if (this.options.stackLimit && stack.length > this.options.stackLimit) { throw new this.Error(state.scope.perms, this.RANGE_ERROR, 'Maximum call stack size exceeded'); } var func = state.info_.func; var args = state.info_.arguments; // Abort call if out of time, unless it's a call to Thread.suspend(). if (func !== this.builtins.get('Thread.suspend')) { try { this.checkTimeLimit_(state.scope.perms); } catch (e) { stack.pop(); // Remove not-called function from stack trace. throw e; } } var r = state.info_.construct ? func.construct(this, thread, state, args) : func.call(this, thread, state, state.info_.this, args); if (r instanceof Interpreter.FunctionResult) { switch (r) { case Interpreter.FunctionResult.AwaitValue: return; case Interpreter.FunctionResult.Block: thread.status = Interpreter.Thread.Status.BLOCKED; return; case Interpreter.FunctionResult.CallAgain: state.step_ = 0; return; case Interpreter.FunctionResult.Sleep: thread.status = Interpreter.Thread.Status.SLEEPING; return; default: throw new Error('Unknown FunctionResult??'); } } state.value = r; } // state.step_ === 1: Execution done; handle return value. stack.pop(); // Previous stack frame may not exist if this is a setTimeout function. if (stack.length > 0) { stack[stack.length - 1].value = state.value; } }; /** * ConditionalExpression AND IfStatement. The only difference is the * latter does not return a value to the parent state. * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ConditionalExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Evaluate test. state.step_ = 1; return new Interpreter.State(node['test'], state.scope); } // state.step_ === 1: Test evaluated; result is in .value var value = Boolean(state.value); stack.pop(); if (value && node['consequent']) { // Execute 'if' block. return new Interpreter.State(node['consequent'], state.scope); } if (!value && node['alternate']) { // Execute 'else' block. return new Interpreter.State(node['alternate'], state.scope); } // eval('1;if(false){2}') -> undefined thread.value = undefined; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ContinueStatement'] = function(thread, stack, state, node) { this.unwind_(thread, Interpreter.CompletionType.CONTINUE, undefined, node['label'] ? node['label']['name'] : undefined); }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['DebuggerStatement'] = function(thread, stack, state, node) { // Do nothing. May be overridden by developers. stack.pop(); }; /** * DoWhileStatement AND WhileStatement. The only difference is the * former skips evaluating the test expression the first time through. * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['DoWhileStatement'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Decide whether to skip first test. state.step_ = 1; if (node['type'] === 'DoWhileStatement') { // First iteration of do/while executes without checking test. state.value = true; state.step_ = 2; } } if (state.step_ === 1) { // Evaluate condition. // Terminate loop if out of time. this.checkTimeLimit_(state.scope.perms); state.step_ = 2; return new Interpreter.State(node['test'], state.scope); } // state.step_ === 2: Check result of evaluation. if (!state.value) { // Done, exit loop. stack.pop(); } else if (node['body']) { // Execute the body. state.step_ = 1; state.isLoop = true; return new Interpreter.State(node['body'], state.scope); } }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['EmptyStatement'] = function(thread, stack, state, node) { stack.pop(); }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['EvalProgram_'] = function(thread, stack, state, node) { var n = state.n_; var /** ?Node */ expression = node['body'][n]; if (expression) { state.n_ = n + 1; return new Interpreter.State(expression, state.scope); } stack.pop(); stack[stack.length - 1].value = thread.value; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ExpressionStatement'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Evaluate expression. state.step_ = 1; return new Interpreter.State(node['expression'], state.scope); } // state.step_ === 1: Handle completion value. stack.pop(); // Save this value to interpreter.value for use as a return value if // this code is inside an eval function. // // TODO(cpcallen): This is suspected to not be strictly correct // compared to how the ES5.1 spec defines completion values. Add // tests to prove it one way or the other. thread.value = state.value; }; /** * Extra info used by ForInStatement step function. * @typedef {{iter: !Interpreter.PropertyIterator, key: string}} */ Interpreter.ForInInfo; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ForInStatement'] = function(thread, stack, state, node) { while (true) { switch (state.step_) { case 0: // Initial set-up. // First, variable initialization is illegal in strict mode. if (node['left']['declarations'] && node['left']['declarations'][0]['init']) { throw new this.Error(state.scope.perms, this.SYNTAX_ERROR, 'for-in loop variable declaration may not have an initializer.'); } state.step_ = 1; state.isLoop = true; // TODO(cpcallen): remove or declare. // Second, look up the object. Only do so once, ever. return new Interpreter.State(node['right'], state.scope); case 1: // Check right, create PropertyIterator. if (state.value === null || state.value === undefined) { // No iterations to do; exit loop. stack.pop(); return; } var obj = this.toObject(state.value, state.scope.perms); var iter = new Interpreter.PropertyIterator(obj, state.scope.perms); state.info_ = {iter: iter, key: ''}; // FALL THROUGH case 2: // Find the property name for this iteration; do node.left. // Terminate loop if out of time. this.checkTimeLimit_(state.scope.perms); var key = state.info_.iter.next(); if (key === undefined) { // Done; exit loop. stack.pop(); return; } state.info_.key = key; // Get (or create) a Reference to node.left: var /** ?Node */ left = node['left']; if (left['type'] !== 'VariableDeclaration') { state.step_ = 3; // Arbitrary left side, e.g.: for (foo().bar in y). // Get Reference to whatever left side turns out to be. return new Interpreter.State(left, state.scope, true); } // Inline variable declaration: for (var x in y) var lhsName = left['declarations'][0]['id']['name']; state.ref = [state.scope.resolve(lhsName), lhsName]; // FALL THROUGH case 3: // Got .ref to variable to set. Set it next key. if (!state.ref) throw new TypeError('loop variable not an LVALUE??'); this.setValue(state.ref, state.info_.key, state.scope.perms); // Execute the body if there is one, followed by next iteration. state.step_ = 2; if (node['body']) { return new Interpreter.State(node['body'], state.scope); } } } }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ForStatement'] = function(thread, stack, state, node) { // If we've just evaluated node.test, and result was false, terminate loop. if (state.step_ === 2 && !state.value) { stack.pop(); return; } while (true) { switch (state.step_) { case 0: // Eval init expression. state.step_ = 1; state.isLoop = true; // TODO(cpcallen): remove or declare. if (node['init']) { return new Interpreter.State(node['init'], state.scope); } // FALL THROUGH case 1: // Eval test expression. // Terminate loop if out of time. this.checkTimeLimit_(state.scope.perms); state.step_ = 2; if (node['test']) { return new Interpreter.State(node['test'], state.scope); } // FALL THROUGH case 2: // Eval body. state.step_ = 3; return new Interpreter.State(node['body'], state.scope); case 3: // Eval update expression. state.step_ = 1; if (node['update']) { return new Interpreter.State(node['update'], state.scope); } } } }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['FunctionDeclaration'] = function(thread, stack, state, node) { // This was found and handled when the scope was populated. stack.pop(); }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['FunctionExpression'] = function(thread, stack, state, node) { var source = thread.getSource(); if (!source) { throw new Error("No source found when evaluating function expression??"); } var scope = state.scope; var perms = scope.perms; // If the function expression has a name, create an outer scope to // bind that name. See ES5.1 §13 / ES6 §14.1.20. var name = node['id'] && node['id']['name']; if (name) { scope = new Interpreter.Scope(Interpreter.Scope.Type.FUNEXP, perms, scope); } var func = new this.UserFunction(node, scope, source, perms); if (name) scope.createImmutableBinding(name, func); stack.pop(); stack[stack.length - 1].value = func; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['Identifier'] = function(thread, stack, state, node) { var /** string */ name = node['name']; if (state.wantRef_) { stack.pop(); stack[stack.length - 1].ref = [state.scope.resolve(name), name]; } else { var value = this.getValueFromScope(state.scope, name); stack.pop(); // Must be after call to getValueFromScope, which might throw. stack[stack.length - 1].value = value; } }; stepFuncs_['IfStatement'] = stepFuncs_['ConditionalExpression']; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['LabeledStatement'] = function(thread, stack, state, node) { // Note that a statement might have multiple labels. var /** !Array */ labels = state.labels || []; labels[labels.length] = node['label']['name']; var nextState = new Interpreter.State(node['body'], state.scope); nextState.labels = labels; // No need to hit LabelStatement node again on the way back up the stack. stack.pop(); return nextState; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['Literal'] = function(thread, stack, state, node) { var /** (null|boolean|number|string|!RegExp) */ literal = node['value']; var /** ?Interpreter.Value */ value; if (literal instanceof RegExp) { value = new this.RegExp(literal, state.scope.perms); } else { value = literal; } stack.pop(); stack[stack.length - 1].value = value; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['LogicalExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Eval left. state.step_ = 1; return new Interpreter.State(node['left'], state.scope); } // state.step_ == 1: Check for short-circuit; optionally eval right. stack.pop(); var /** string */ op = node['operator']; if (op !== '&&' && op !== '||') { throw new SyntaxError("Unknown logical operator '" + op + "'"); } else if ((op === '&&' && !state.value) || (op === '||' && state.value)) { // Short circuit. Return left value. stack[stack.length - 1].value = state.value; } else { // Tail-eval right. return new Interpreter.State(node['right'], state.scope); } }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['MemberExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Evaluate LHS (object). state.step_ = 1; return new Interpreter.State(node['object'], state.scope); } else if (state.step_ === 1) { // Evaluate RHS (property key) if necessary. state.tmp_ = state.value; if (node['computed']) { // obj[foo] -- Compute value of 'foo'. state.step_ = 2; return new Interpreter.State(node['property'], state.scope); } } // TODO(cpcallen): add test for order of following two specification // method calls from the algorithm in ES6 §2.3.2.1. // Step 7: bv = RequireObjectCoercible(baseValue). var /** ?Interpreter.Value */ base = state.tmp_; var /** !Interpreter.Owner */ perms = state.scope.perms; if (base === null || base === undefined) { throw new this.Error(perms, this.TYPE_ERROR, "Can't convert " + base + ' to Object'); } // Step 9: propertyKey = ToPropertyKey(propertyNameValue). var /** string */ key = node['computed'] ? String(state.value) : node['property']['name']; stack.pop(); // Must be after last throw new this.Error... if (state.wantRef_) { stack[stack.length - 1].ref = [base, key]; } else { // toObject guaranteed not to throw because of earlier check. stack[stack.length - 1].value = this.toObject(base, perms).get(key, perms); } }; stepFuncs_['NewExpression'] = stepFuncs_['CallExpression']; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ObjectExpression'] = function(thread, stack, state, node) { var n = state.n_; if (!state.tmp_) { // First execution. Create object. state.tmp_ = new this.Object(state.scope.perms); } else { // Save just-evaluated property value in object. // Determine property name. var /** ?Node */ keyNode = node['properties'][n]['key']; if (keyNode['type'] === 'Identifier') { var /** string */ key = keyNode['name']; } else if (keyNode['type'] === 'Literal') { key = keyNode['value']; } else { throw new SyntaxError('Unknown object structure: ' + keyNode['type']); } var value = state.value; var perms = state.scope.perms; // Set name if anonymous function expression. if (isAnonymousFunctionDefinition(node['properties'][n]['value'])) { var func = /** @type {!Interpreter.prototype.Function} */(value); // TODO(ES6): Check that func does not already have a 'name' own // property before calling setName? (Spec requires, but unclear // why since we know RHS is anonymous. Proxies?) func.setName(key); } // Set the property computed in the previous execution. state.tmp_.defineProperty(key, Descriptor.wec.withValue(value), perms); state.n_ = ++n; } var /** ?Node */ property = node['properties'][n]; if (property) { if (property['kind'] !== 'init') { throw new this.Error(state.scope.perms, this.SYNTAX_ERROR, 'Only plain properties are supported - not getters or setters'); } return new Interpreter.State(property['value'], state.scope); } stack.pop(); stack[stack.length - 1].value = state.tmp_; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['Program'] = function(thread, stack, state, node) { var n = state.n_; var /** ?Node */ expression = node['body'][n]; if (expression) { state.n_ = n + 1; return new Interpreter.State(expression, state.scope); } stack.pop(); }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ReturnStatement'] = function(thread, stack, state, node) { if (node['argument'] && state.step_ === 0) { state.step_ = 1; return new Interpreter.State(node['argument'], state.scope); } this.unwind_( thread, Interpreter.CompletionType.RETURN, state.value, undefined); }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['SequenceExpression'] = function(thread, stack, state, node) { var n = state.n_; var /** !Node */ expression = node['expressions'][n++]; if (n >= node['expressions'].length) { stack.pop(); } state.n_ = n; return new Interpreter.State(expression, state.scope); }; /** * Extra info used by SwitchStatement step function. * @typedef {{default: number}} */ Interpreter.SwitchInfo; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['SwitchStatement'] = function(thread, stack, state, node) { // First check return value to see if case test succeeded. if (state.step_ === 2 && state.value === state.tmp_) { state.step_ = 3; } switch (state.step_) { case 0: // Start by evaluating discriminant. state.step_ = 1; return new Interpreter.State(node['discriminant'], state.scope); case 1: // Got evaluated discriminant. Save it. state.tmp_ = state.value; state.isSwitch = true; state.info_ = {default: -1}; state.n_ = -1; state.step_ = 2; // FALL THROUGH case 2: // Find case with non-empty test and evaluate test expression. var /** Array */ cases = node['cases']; var /** number */ len = cases.length; var n = state.n_ + 1; if (n < len && !cases[n]['test']) { // Found default case. Record & skip. state.info_.default = n++; } if (n < len) { // Found non-empty test expression. Evaluate. state.n_ = n; return new Interpreter.State(cases[n]['test'], state.scope); } // Ran out of cases to test. if (state.info_.default === -1) { // And there's no default. Terminate. stack.pop(); return; } // Use default case. state.n_ = state.info_.default; // FALL THROUGH case 3: // Found correct case. Prep for executing consequents. state.tmp_ = 0; // Begin with the 0th consequent of current case. state.step_ = 4; // FALL THROUGH case 4: // Execute case[n_].consequent[tmp_] (or next available). cases = node['cases']; len = cases.length; for (n = state.n_; n < len; n++) { var /** ?Node */ conseq = cases[n]['consequent']; if (conseq && conseq[state.tmp_]) { state.n_ = n; return new Interpreter.State(conseq[state.tmp_++], state.scope); } state.tmp_ = 0; // Done this case; fall through 0th statement of next. } stack.pop(); // All done. } }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ThisExpression'] = function(thread, stack, state, node) { stack.pop(); stack[stack.length - 1].value = state.scope.this; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['ThrowStatement'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Evaluate value to throw. state.step_ = 1; return new Interpreter.State(node['argument'], state.scope); } throw state.value; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['TryStatement'] = function(thread, stack, state, node) { switch (state.step_) { case 0: // Evaluate 'try' block. state.step_ = 1; return new Interpreter.State(node['block'], state.scope); case 1: // Back from 'try' block. Run catch? state.step_ = 2; var /** ?Node */ handler = node['handler']; var cv = /** ?Interpreter.Completion */ (state.info_); if (handler && cv && cv.type === Interpreter.CompletionType.THROW) { state.info_ = null; // This error is being handled, don't rethrow. // Execute catch clause with varible bound to exception value. var scope = new Interpreter.Scope( Interpreter.Scope.Type.CATCH, state.scope.perms, state.scope); scope.createMutableBinding(handler['param']['name'], cv.value); return new Interpreter.State(handler['body'], scope); } // FALL THROUGH case 2: // Done 'try' and 'catch'. Do 'finally'? if (node['finalizer']) { state.step_ = 3; return new Interpreter.State(node['finalizer'], state.scope); } // FALL TRHOUGH case 3: // Regardless of whether we are exiting normally or about to // resume unwinding the stack, we are done with this // TryStatement and do not want to examine it again. stack.pop(); if (state.info_) { // There was no catch handler, or the catch/finally threw an // error. Resume unwinding the stack in search of // TryStatement / Call / target of break or continue. this.unwind_( thread, state.info_.type, state.info_.value, state.info_.label); } } }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['UnaryExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Evaluate (or get reference) to argument. state.step_ = 1; // Get argument - need Reference if operator is 'delete' or 'typeof: var wr = (node['operator'] === 'delete') || (node['operator'] === 'typeof'); return new Interpreter.State(node['argument'], state.scope, wr); } var value = state.value; if (node['operator'] === '-') { value = -value; } else if (node['operator'] === '+') { value = +value; } else if (node['operator'] === '!') { value = !value; } else if (node['operator'] === '~') { value = ~value; } else if (node['operator'] === 'delete') { if (state.ref) { if (state.ref[0] instanceof Interpreter.Scope) { // Whoops; this should have been caught by Acorn (because strict). throw new Error('Uncaught illegal deletion of unqualified identifier'); } var obj = this.toObject(state.ref[0], state.scope.perms); value = obj.deleteProperty(state.ref[1], state.scope.perms); } else { // Attempted to deleted some expression that wasn't a reference // to a variable or property. Skip delete; return true. value = true; } } else if (node['operator'] === 'typeof') { if (state.ref) { var perms = state.scope.perms; if (this.isUnresolvableReference(state.scope, state.ref, perms)) { value = undefined; } else { value = this.getValue(state.ref, perms); } } value = (value instanceof this.Function) ? 'function' : typeof value; } else if (node['operator'] === 'void') { value = undefined; } else { throw new SyntaxError('Unknown unary operator: ' + node['operator']); } stack.pop(); stack[stack.length - 1].value = value; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['UpdateExpression'] = function(thread, stack, state, node) { if (state.step_ === 0) { // Get Reference to argument. state.step_ = 1; return new Interpreter.State(node['argument'], state.scope, true); } if (!state.ref) throw new TypeError('argument not an LVALUE??'); var value = Number(this.getValue(state.ref, state.scope.perms)); var prefix = Boolean(node['prefix']); var /** ?Interpreter.Value */ rval; if (node['operator'] === '++') { rval = (prefix ? ++value : value++); } else if (node['operator'] === '--') { rval = (prefix ? --value : value--); } else { throw new SyntaxError('Unknown update expression: ' + node['operator']); } this.setValue(state.ref, value, state.scope.perms); stack.pop(); stack[stack.length - 1].value = rval; }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['VariableDeclaration'] = function(thread, stack, state, node) { var declarations = node['declarations']; var n = state.n_; var decl = declarations[n]; if (state.step_ === 1) { // Initialise variable with evaluated init value. var name = decl['id']['name']; var value = state.value; if (isAnonymousFunctionDefinition(decl['init'])) { var func = /** @type {!Interpreter.prototype.Function} */(value); // TODO(ES6): Check that func does not already have a 'name' own // property before calling setName? (Spec requires, but unclear // why since we know RHS is anonymous. Proxies?) func.setName(name); } // Note that this is setting the value, not defining the variable. // Variable definition is done when scope is populated. this.setValueToScope(state.scope, name, value); decl = declarations[++n]; } while (decl) { // Skip any declarations that are not initialized. They have already // been defined as undefined in populateScope_. if (decl['init']) { state.n_ = n; state.step_ = 1; return new Interpreter.State(decl['init'], state.scope); } decl = declarations[++n]; } stack.pop(); }; /** * @this {!Interpreter} * @param {!Interpreter.Thread} thread * @param {!Array} stack * @param {!Interpreter.State} state * @param {!Node} node * @return {!Interpreter.State|undefined} */ stepFuncs_['WithStatement'] = function(thread, stack, state, node) { throw new this.Error(state.scope.perms, this.SYNTAX_ERROR, 'Strict mode code may not include a with statement'); }; stepFuncs_['WhileStatement'] = stepFuncs_['DoWhileStatement']; // Give each step function a serialisation id. for (var name in stepFuncs_) { stepFuncs_[name].id = 'Step Function: ' + name; } /////////////////////////////////////////////////////////////////////////////// // Exports /////////////////////////////////////////////////////////////////////////////// exports = module.exports = Interpreter; exports.testOnly = { getBoundNames: getBoundNames, hasArgumentsOrEval: hasArgumentsOrEval, }; ================================================ FILE: server/iterable_weakmap.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview A WeakMap that's iterable. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; /** * A (WeakRef, value) tuple in an IterableWeakMap. * @template KEY, VALUE */ class Cell { /** * @param {!WeakRef} ref A WeakRef to the key for this cell. * @param {VALUE} value The value for this cell. */ constructor(ref, value) { /** @type {!WeakRef} */ this.ref = ref; /** @type {VALUE} */ this.value = value; } } /** * A WeakMap implementing the full Map interface, including iterability. * @struct * @implements {Iterable>} * @template KEY, VALUE */ // TODO(cpcallen): Make KEY a bounded to {!Object} once // Closure Compiler supports bounded generic types class IterableWeakMap extends WeakMap { /** * @param {!Iterable>|!Array>=} iterable */ constructor(iterable = undefined) { super(); /** @private @const @type {!Set>} */ this.refs_ = new Set(); /** * @private @const * @type {!FinalizationRegistry, !WeakRef>} */ this.finalisers_ = new FinalizationRegistry(ref => { this.refs_.delete(ref); }); if (iterable === null || iterable === undefined) { return; } const adder = this.set; if (typeof adder !== 'function') { throw new TypeError("'" + this.set + "' returned for property 'set' " + 'of object ' + this + ' is not a function'); } for (const /** ?Array> */ entry of iterable) { if (typeof entry !== 'object' && typeof entry !== 'function' || entry === null) { throw new TypeError( 'Iterator value ' + entry + ' is not an entry object'); } adder.call(this, entry[0], entry[1]); } } /** * Remove all entries from the map. * @return {void} * @override */ clear() { for (const ref of this.refs_) { const key = ref.deref(); if (key !== undefined) this.delete(key); } this.refs_.clear(); // Remove anything GCed but not finalised. } /** * Remove a single entry from the map. * @param {KEY} key The key to be deleted. * @return {boolean} Was anything deleted? * @override */ delete(key) { const cell = super.get(key); if (cell) { this.refs_.delete(cell.ref); this.finalisers_.unregister(cell.ref); } return super.delete(key); } /** * Return a iterator over [key, value] pairs of the map. * @return {!IteratorIterable>} */ *entries() { for (const ref of this.refs_) { const key = ref.deref(); if (key === undefined) { // key was garbage collected. Remove ref. this.refs_.delete(ref); } else { yield [key, super.get(key).value]; } } } /** * Execute the provided callback for each entry in the map, calling * it with thisArg as its this value and arguments key, value and * this map. * @this {MAP} * @param {function(this:THIS, VALUE, KEY, IterableWeakMap)} * callback * @param {THIS=} thisArg * @return {void} * @template MAP, THIS */ forEach(callback, thisArg = undefined) { for (const [key, value] of this) { callback.call(thisArg, value, key, this); } } /** * Return the value corresponding to a given key. * @param {KEY} key The key whose corresponding value is desired. * @return {VALUE} The value corresponging to key, or undefined if not found. * @override */ get(key) { const cell = super.get(key); return cell && cell.value; } /** * Return an iterator over the keys of the map. * @return {!IteratorIterable} */ *keys() { for (const [key, value] of this) { yield key; } } /** * Add or update the value associated with key in the map. * @this {THIS} * @param {KEY} key The key to add or update. * @param {VALUE} value The new value to associate with key. * @return {THIS} * @override * @template THIS */ set(key, value) { if (super.has(key)) { super.get(key).value = value; } else { const ref = new WeakRef(key); const cell = new Cell(ref, value); super.set(key, cell); this.refs_.add(ref); this.finalisers_.register(key, ref, ref); } return this; } /** * @return {number} */ get size() { return this.refs_.size; } /** * Return an iterator over the value of the map. * @return {!IteratorIterable} */ *values() { for (const [key, value] of this) { yield value; } } } IterableWeakMap.prototype[Symbol.iterator] = IterableWeakMap.prototype.entries; module.exports = IterableWeakMap; ================================================ FILE: server/iterable_weakset.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview A WeakSet that's iterable. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; /** * A WeakSet implementing the full Set interface, including iterability. * @struct * @extends {WeakSet} * @implements {Iterable>} * @template VALUE */ // TODO(cpcallen): Make VALUE bounded to {!Object} once // Closure Compiler supports bounded generic types. class IterableWeakSet { /** * @param {!Iterable>|!Array>=} iterable */ constructor(iterable = undefined) { /** @private @const @type {!Set>} */ this.refs_ = new Set(); /** @private @const @type {!WeakMap>}} */ this.map_ = new WeakMap(); /** * @private @const * @type {!FinalizationRegistry, !WeakRef>} */ this.finalisers_ = new FinalizationRegistry(ref => { this.refs_.delete(ref); }); if (iterable === null || iterable === undefined) { return; } const adder = this.add; if (typeof adder !== 'function') { throw new TypeError("'" + this.add + "' returned for property 'add' " + 'of object ' + this + ' is not a function'); } for (const /** !VALUE */ value of iterable) { if (typeof value !== 'object' && typeof value !== 'function' || value === null) { throw new TypeError('Iterator value ' + value + ' is not an object'); } adder.call(this, value); } } /** * Add the value to the set. * @this {THIS} * @param {VALUE} value The value to add. * @return {THIS} * @override * @template THIS */ add(value) { if (!this.map_.has(value)) { const ref = new WeakRef(value); this.map_.set(value, ref); this.refs_.add(ref); this.finalisers_.register(value, ref, ref); } return this; } /** * Remove all entries from the set. * @return {void} * @override */ clear() { for (const ref of this.refs_) { const key = ref.deref(); if (key !== undefined) this.delete(key); } this.refs_.clear(); // Remove anything GCed but not finalised. } /** * Remove a single entry from the set. * @param {VALUE} value The value to be deleted. * @return {boolean} Was anything deleted? * @override */ delete(value) { const ref = this.map_.get(value); if (ref) { this.refs_.delete(ref); this.finalisers_.unregister(ref); } return this.map_.delete(value); } /** * Return a iterator over [value, value] pairs of the set. * @return {!IteratorIterable>} */ *entries() { for (const value of this) { yield [value, value]; } } /** * Execute the provided callback for each entry in the set, calling * it with thisArg as its this value and argument value (twice) and * this set. * @this {SET} * @param {function(this:THIS, VALUE, VALUE, SET)} callback * @param {THIS=} thisArg * @return {void} * @template SET, THIS */ forEach(callback, thisArg = undefined) { for (const value of this) { callback.call(thisArg, value, value, this); } } /** * Return true iff value is a member of this set. * @param {VALUE} value * @return {boolean} */ has(value) { return this.map_.has(value); } /** * @return {number} */ get size() { return this.refs_.size; } /** * Return an iterator over the value of the set. * @return {!IteratorIterable} */ *values() { for (const ref of this.refs_) { const value = ref.deref(); if (value === undefined) { // value was garbage collected. Remove ref. this.refs_.delete(ref); } else { yield value; } } } } IterableWeakSet.prototype[Symbol.iterator] = IterableWeakSet.prototype.values; IterableWeakSet.prototype.keys = IterableWeakSet.prototype.values; module.exports = IterableWeakSet; ================================================ FILE: server/package.json ================================================ { "name": "codecity-server", "version": "0.0.0", "description": "Server for the Code City project", "main": "codecity.js", "dependencies": { "acorn": "^8.1.1" }, "devDependencies": { "google-closure-compiler": "^20210406.0.0" }, "scripts": { "compile": "./compile", "test": "tests/run" }, "repository": { "type": "git", "url": "git+https://github.com/google/CodeCity.git" }, "author": "Google", "license": "Apache-2.0", "bugs": { "url": "https://github.com/google/CodeCity/issues" }, "homepage": "https://github.com/google/CodeCity#readme" } ================================================ FILE: server/parser.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Parser for Code City interpreter. * @author cpcallen@google.com (Christopher Allen) */ var acorn = require('acorn'); /////////////////////////////////////////////////////////////////////////////// // Externs for Acorn. /////////////////////////////////////////////////////////////////////////////// // These are supplied here because Closure Compiler doesn't appear to // provide any good way to specify externs for a Node module, and the // mechanisms used to provide separate externs for Node's built-in // modules don't work with NPMs. // // Trivial 'initialisers' are provided for acorn.Node and acorn.Parser // to satisfy the compiler's requirement that constructors be // initialised at declaration. /** * @constructor * @param {!acorn.Parser} parser * @param {?} pos * @param {?} loc */ acorn.Node = acorn.Node; /** * @constructor * @param {!Object} options Parse options. * @param {string} input The text to be parsed. * @param {number=} startPos Character offset to start parsing at. */ acorn.Parser = acorn.Parser; /** * @return {!Node} */ acorn.Parser.prototype.startNode; /** * @param {?} pos * @param {?} loc * @return {!Node} */ acorn.Parser.prototype.startNodeAt; /** * @param {string} input * @param {!Object=} options */ acorn.Parser.parse; /** * @param {string} input * @param {number} pos * @param {!Object=} options */ acorn.Parser.parseExpressionAt; /////////////////////////////////////////////////////////////////////////////// // Custom Parser subclass for Code City. /////////////////////////////////////////////////////////////////////////////// /** @const {!Object} Default options for Parser. */ var PARSE_OPTIONS = {ecmaVersion: 5, strict: true}; /** * A subclass of acorn.Node, which has a constructor that can be * called without arguments (and in particular without the Parser * argument). * * This is mainly to facilitate deserialisation, but is also used * directly to create a fake (but but correctly typed) AST node for * 'eval'. * * @constructor * @extends {acorn.Node} * @param {!acorn.Parser=} parser * @param {?=} pos * @param {?=} loc */ var Node = function(parser, pos, loc) { acorn.Node.call(this, parser || {options: PARSE_OPTIONS}, pos, loc); }; Object.setPrototypeOf(Node, acorn.Node); Object.setPrototypeOf(Node.prototype, acorn.Node.prototype); /** * A subclass of acorn.Parser that: * * - Supports a strict option which, if true, forces strict mode. * - Defaults to using Interpreter.PARSE_OPTIONS if no options are * supplied. * - Uses the overridden Node constructor above to create nodes. * * See https://github.com/acornjs/acorn/tree/master/acorn#interface * for details on how to use it, valid option values, etc. * * @constructor * @extends {acorn.Parser} * @param {!Object|undefined} options Parse options. Defaults to * Interpreter.PARSE_OPTIONS * @param {string} input The text to be parsed. * @param {number=} startPos Character offset to start parsing at. */ var Parser = function(options, input, startPos) { if (!options) options = PARSE_OPTIONS; acorn.Parser.call(this, options, input, startPos); if (options.strict) this.strict = true; }; Object.setPrototypeOf(Parser, acorn.Parser); Object.setPrototypeOf(Parser.prototype, acorn.Parser.prototype); /** @override */ Parser.prototype.startNode = function() { return new Node(this, this.start, this.startLoc); }; /** @overide */ Parser.prototype.startNodeAt = function(pos, loc) { return new Node(this, pos, loc); }; // Redeclare static methods because Closure Compiler isn't too smart // about static method inheritance in ES5. /** @override */ Parser.parse; /** @override */ Parser.parseExpressionAt; /////////////////////////////////////////////////////////////////////////////// // Exports /////////////////////////////////////////////////////////////////////////////// exports.Parser = Parser; exports.PARSE_OPTIONS = PARSE_OPTIONS; exports.Node = Node; ================================================ FILE: server/priorityqueue.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview A priority queue implemented using a heap. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; // Rant: I can't believe I have to write this myself, but a fairly // extensive search of GitHub and NPM did not turn up an existing // package that: // // - Allowed arbitrary JS values (including objects) in the queue, // - Does comparison by ===, SameValueZero or SameValue (Object.is) // rather than using deepEquals or something equally foolish, // - Provided a decreasePriority method. /** * Returns the parent index of a given index in a heap. * @private * @param {number} i Index to get parent of. * @return {number} Index of parent, or -1 if i is 0. */ function parent(i) { if (i <= 0) return -1; return Math.floor((i - 1) / 2); } /** * Returns the child indices of a given index in a heap. * @private * @param {number} i Index to get children of. * @return !Array Two-element array of indicies of the chilren. */ function children(i) { return [(i * 2) + 1, (i * 2) + 2]; } /** * A priority queue. * @stuct * @template T */ class PriorityQueue { constructor() { /** @private @const {!Array<{value: T, priority: number}>} */ this.heap_ = []; /** @private @const {!Map} */ this.indices_ = new Map(); } /** * Remove the minimum * @return {T} The minimum-priority item just removed. */ deleteMin() { if (this.heap_.length === 0) { throw RangeError('queue is empty'); } const value = this.heap_[0].value; this.indices_.delete(value); if (this.heap_.length > 1) { this.heap_[0] = this.heap_.pop(); // percolateDown_ will update indices_. this.percolateDown_(0); } else { this.heap_.pop(); } return value; } /** * Insert an item in the queue. * @param {T} value The item to be inserted. * @param {number} priority The priority value to insert it with. * @return {void} */ insert(value, priority) { this.set.call(this, value, priority); } /** @return {number} */ get length() { return this.heap_.length; } /** * Move the entry at .heap_[i] towards the leaves of the heap as * required to retain heap ordering. * @private * @param {number} i Index of node to percolate up. */ percolateDown_(i) { const entry = this.heap_[i]; while (true) { const [l, r] = children(i); if (l >= this.heap_.length) break; // No children. let c = l; if (r < this.heap_.length && // Two children. Pick smallest. this.heap_[r].priority < this.heap_[l].priority) { c = r; } if (entry.priority <= this.heap_[c].priority) break; this.heap_[i] = this.heap_[c]; this.indices_.set(this.heap_[c].value, i); i = c; } this.heap_[i] = entry; this.indices_.set(entry.value, i); } /** * Move the entry at .heap_[i] towards the root of the heap as * required to retain heap ordering. * @private * @param {number} i Index of node to percolate up. */ percolateUp_(i) { const entry = this.heap_[i]; while (i > 0) { const p = parent(i); if (this.heap_[p].priority <= entry.priority) break; this.heap_[i] = this.heap_[p]; this.indices_.set(this.heap_[p].value, i); i = p; } this.heap_[i] = entry; this.indices_.set(entry.value, i); } /** * Reduce the priority of a given value. * @param {T} value The item to be modified. * @param {number} priority The new priority value. Must not be * greater than the existing value. * @return {void} */ reducePriority(value, priority) { return this.set.call(this, value, priority); } /** * Insert an item into the queue or update its priority. If the * value is already in the queue then priority must not be greater * than the previous priority or RangeError will be thrown. * @param {T} value The item to be inserted/updated. * @param {number} priority The (new) priority for value. * @return {void} */ set(value, priority) { let i = this.indices_.get(value); if (i === undefined) { i = this.heap_.length; this.heap_.push({value, priority}); } else if (this.heap_[i].priority < priority) { throw new RangeError('attempting to increase priority'); } else { this.heap_[i].priority = priority; } // percolateUp will set/update this.indices_ entry for value. this.percolateUp_(i); } } exports.PriorityQueue = PriorityQueue; exports.testOnly = {parent, children}; ================================================ FILE: server/registry.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview The Registry class, for e.g. registering built-ins. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const util = require('util'); /** * Class for a registry providing a bijective[1] mapping between * string-valued keys and arbitrary values. * * N.B.: a Map is used for reverse lookups; as Maps use the * sameValueZero algorithm to compare keys[2] it is not possible to * register both 0 and -0, but NaN will work correctly. * * [1] This means no key may have more than one value, and no value * may have more than one key. * [2] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality * * @constructor * @template T */ class Registry { constructor() { /** @private @const @type {!Object} */ this.values_ = Object.create(null); /** @private @const @type {!Map} */ this.keys_ = new Map(); } /** * Return an array of [key, value] pairs of the registry. * @return {!Array>} */ entries() { return Object.entries(this.values_); } /** * Look up a registered value. Throws an error if the given key has * not been registered. * @param {string} key The key to get the registered value for. * @return {T} The registered value. */ get(key) { if (!this.has(key)) { throw new Error('Key "' + key + '" not registered'); } return this.values_[key]; } /** * Look up the key for a registered value. Returns undefined if the * given value has not been registered. * @param {T} value The value to get the key for. * @return {string|undefined} The key for value, or undefined if * value never registered. */ getKey(value) { return this.keys_.get(value); } /** * Check if a key exists in the registry. * @param {string} key The key to check. * @return {boolean} True iff key has previously been registered. */ has(key) { return key in this.values_; } /** * Return an array of keys of the registry. * @return {!Array} */ keys() { return Object.keys(this.values_); } /** * Register a value. Throws an error if the given key has already * been used for a previous registration. * @param {string} key The key to register value with. * @param {T} value The value to be registered. */ set(key, value) { if (key in this.values_) { throw new Error('Key "' + key + '" already in use'); } if (this.keys_.has(value)) { throw new Error(util.format('Value %O already registered', value)); } this.values_[key] = value; this.keys_.set(value, key); } /** * Return an array of values of the registry. * @return {!Array} */ values() { return Object.values(this.values_); } } module.exports = Registry; ================================================ FILE: server/repl ================================================ #!/usr/bin/env node /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Read Eval Print Loop (REPL) for JavaScript Interpreter. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const readline = require('readline'); const Interpreter = require('./interpreter'); const fs = require('fs'); const intrp = new Interpreter; intrp.createThreadForSrc(fs.readFileSync('startup/es5.js', 'utf8')); intrp.run(); intrp.createThreadForSrc(fs.readFileSync('startup/es6.js', 'utf8')); intrp.run(); intrp.createThreadForSrc(fs.readFileSync('startup/es7.js', 'utf8')); intrp.run(); intrp.createThreadForSrc(fs.readFileSync('startup/esx.js', 'utf8')); intrp.run(); intrp.createThreadForSrc(fs.readFileSync('startup/cc.js', 'utf8')); intrp.run(); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, removeHistoryDuplicates: true, }); rl.prompt(); rl.on('line', function(line) { try { let thread; try { thread = intrp.createThreadForSrc(line).thread; } catch (e) { console.log('%s: %s', e.name, e.message); return; } intrp.run(); const value = thread.value; if (value instanceof intrp.Function) { console.log(value.toString()); } else { console.log('%o', intrp.pseudoToNative(thread.value)); } } finally { rl.prompt(); } }).on('close', function() { process.exit(0); }); ================================================ FILE: server/selector.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview CSS-style selectors for JS objects. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; var code = require('./code'); /** * Type for all "special" selector parts (ones which do not represent * named variables / properties). * @constructor * @struct */ var SpecialPart = function(type) { this.type = type; }; /** @override */ SpecialPart.prototype.toString = function() { return '{' + this.type + '}'; }; /** * A Selector is just an array of Parts, which happens to have * Selector.prototype (with various useful convenience methods) in its * prototype chain. * @constructor * @extends {Array} * @param {string|!Array|!Selector} s A Selector, parts * array or selector string. */ var Selector = function(s) { var /** !Array */ parts; if (typeof s === 'string') { // Parse selector text. parts = parse(s); } else if (Array.isArray(s)) { parts = []; // Validate & copy parts array. if (typeof s.length < 1) throw new RangeError('Zero-length parts array??'); if (s.length < 1) throw new RangeError('Zero-length parts array??'); if (typeof s[0] !== 'string' || !code.regexps.identifierExact.test(s[0])) { throw new TypeError('Parts array must begin with an identifier'); } parts[0] = s[0]; for (var i = 1; i < s.length; i++) { if (typeof s[i] !== 'string' && !(s[i] instanceof SpecialPart)) { throw new TypeError('Invalid part in parts array'); } else if ((s[i] instanceof SpecialPart) && s[i] !== Selector.PROTOTYPE && s[i] !== Selector.OWNER) { throw new TypeError('Invalid SpecialPart in parts array'); } parts[i] = s[i]; } } else { throw new TypeError('Not a selector or parts array'); } Object.setPrototypeOf(parts, Selector.prototype); return parts; }; Object.setPrototypeOf(Selector.prototype, Array.prototype); /** * Return a "badness" score, inversely proportional to how desirable a * particular selector is amongst other selectors referring to the * same binding. In general, longer selectors are more bad, but * selectors containing special parts are especially bad. * TODO(cpcallen): reintroduce penalty for non-builtins? * @return {number}; */ Selector.prototype.badness = function() { var penalties = 0; for (var i = 0; i < this.length; i++) { penalties += Selector.partBadness(this[i]); } return penalties; }; /** * Returns true iff the selector represents an object owner * binding. * @return {boolean} Is selector for owner? */ Selector.prototype.isOwner = function() { return this.length > 1 && this[this.length - 1] === Selector.OWNER; }; /** * Returns true iff the selector represents an object property * binding. * @return {boolean} Is selector for a property? */ Selector.prototype.isProp = function() { return this.length > 1 && typeof this[this.length - 1] === 'string'; }; /** * Returns true iff the selector represents an object prototype * binding. * @return {boolean} Is selector for prototype? */ Selector.prototype.isProto = function() { return this.length > 1 && this[this.length - 1] === Selector.PROTOTYPE; }; /** * Returns true iff the selector represents a top-level variable * binding. * @return {boolean} Is selector for a variable? */ Selector.prototype.isVar = function() { return this.length === 1 && typeof this[0] === 'string'; }; /** * Return the selector as an evaluable expression yeilding the * selected value. * @return {string} The selector as a string. */ Selector.prototype.toExpr = function() { return this.toString(function(part, out) { if (part === Selector.PROTOTYPE) { out.unshift('Object.getPrototypeOf('); out.push(')'); } else if (part === Selector.OWNER) { out.unshift('Object.getOwnerOf('); out.push(')'); } else { throw new TypeError('Invalid part in parts array'); } }); }; /** * Return an expression setting the selected value to the value of the * supplied expression. * @param {string} valueExpr A JS expression that evaluates to the new * value to be assigned to the selected location. It must not * contain any non-parenthesized operators with lower precedence * than '=' - specifically, the yield and comma operators. * @return {string} The selector as a string. */ Selector.prototype.toSetExpr = function(valueExpr) { var lastPart = this[this.length - 1]; if (!(lastPart instanceof SpecialPart)) { return this.toExpr() + ' = ' + valueExpr; } var objExpr = new Selector(this.slice(0, -1)).toExpr(); if (lastPart === Selector.PROTOTYPE) { return 'Object.setPrototypeOf(' + objExpr + ', ' + valueExpr + ')'; } else if (lastPart === Selector.OWNER) { return 'Object.setOwnerOf(' + objExpr + ', ' + valueExpr + ')'; } else { throw new TypeError('Invalid part in parts array'); } }; /** * Return the selector string corresponding to this selector. * @param {function(!SpecialPart, !Array)=} specialHandler * Optional function to handle stringifying SpecialParts. * @return {string} The selector as a string. */ Selector.prototype.toString = function(specialHandler) { var /** !Array */ out = [this[0]]; for (var i = 1; i < this.length; i++) { var part = this[i]; if (part instanceof SpecialPart) { if (specialHandler) { specialHandler(part, out); } else { out.push(String(part)); } } else if (code.regexps.identifierExact.test(part)) { out.push('.', part); } else if (String(Number(part)) === part) { // String represents a number with same string representation. out.push('[', part, ']'); } else { out.push('[', code.quote(part), ']'); } } return out.join(''); }; /** * Return a "badness" score for a single Selector.Part, inversely * proportional to how desirable the part is as part of selector * amongst other selectors referring to the same binding. * @return {number}; */ Selector.partBadness = function(part) { if (part instanceof SpecialPart) { return 100; // We don't like SpecialParts. } else if (code.regexps.identifierExact.test(part)) { return 10 + part.length; // We like identifiers. } else if (String(Number(part)) === part) { return 25 + part.length; // Numbers are OK. } else { return 30 + part.length; // Quoted strings are less desirable. } }; /** * Special singleton Part for refering to an object's prototype. */ Selector.PROTOTYPE = new SpecialPart('proto'); /** * Special singleton Part for refering to an object's owner. */ Selector.OWNER = new SpecialPart('owner'); /** * A Selector fundamentally an array of Parts, and Parts are either * strings (representing variable or property names) or SpecialParts * (representing everything else, like {proto} or {owner}). * @typedef {string|!SpecialPart} */ Selector.Part; /** * Parse a selector into an array of Parts. * @return !Array */ var parse = function(selector) { var tokens = tokenize(selector); var parts = []; /** @enum {number} */ var State = { START: 0, GOOD: 1, DOT: 2, BRACKET: 3, BRACKET_DONE: 4, BRACE: 5, BRACE_DONE: 6 }; var state = State.START; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type === 'whitespace') continue; switch (state) { case State.START: if (token.type !== 'id') { throw new SyntaxError('Selector must start with an identifier'); } parts.push(token.raw); state = State.GOOD; break; case State.GOOD: if (token.type === '.') { state = State.DOT; } else if (token.type === '[') { state = State.BRACKET; } else if (token.type === '{') { state = State.BRACE; } else if (token.type === '^') { // state remains unchanged. parts.push(Selector.PROTOTYPE); } else { throw new SyntaxError( 'Invalid token ' + code.quote(token.raw) + ' in selector'); } break; case State.DOT: if (token.type !== 'id') { throw new SyntaxError( '"." must be followed by identifier in selector'); } parts.push(token.raw); state = State.GOOD; break; case State.BRACKET: if (token.type === 'number') { parts.push(String(token.raw)); } else if (token.type === 'str') { parts.push(String(token.value)); } else { throw new SyntaxError('"[" must be followed by numeric or string ' + 'literal in selector'); } state = State.BRACKET_DONE; break; case State.BRACKET_DONE: if (token.type !== ']') { throw new SyntaxError( 'Invalid token ' + code.quote(token.raw) + ' after subscript'); } state = State.GOOD; break; case State.BRACE: if (token.type === 'id' && token.raw === 'proto') { parts.push(Selector.PROTOTYPE); } else if (token.type === 'id' && token.raw === 'owner') { parts.push(Selector.OWNER); } else { throw new SyntaxError('"{" must be followed by "proto" or "owner"'); } state = State.BRACE_DONE; break; case State.BRACE_DONE: if (token.type !== '}') { throw new SyntaxError( 'Invalid token ' + code.quote(token.raw) + ' after special'); } state = State.GOOD; break; default: throw new Error('Invalid State in parse??'); } } if (state !== State.GOOD) { throw new SyntaxError('Incomplete selector ' + selector); } return parts; }; /** @typedef {{type: string, * raw: string, * valid: boolean, * index: number, * value: (string|number|undefined)}} */ var Token; /** * Tokenizes a selector string. Throws a SyntaxError if any text is * found which does not form a valid token. * @param {string} selector A selector string. * @return {!Array} An array of tokens. */ var tokenize = function(selector) { var REs = { whitespace: /\s+/y, '.': /\./y, id: new RegExp(code.regexps.identifier, 'y'), number: /\d+/y, '[': /\[/y, ']': /\]/y, '{': /\{/y, '}': /\}/y, '^': /\^/y, str: new RegExp(code.regexps.string, 'y'), }; var tokens = []; NEXT_TOKEN: for (var index = 0; index < selector.length; ) { for (var tokenType in REs) { if (!REs.hasOwnProperty(tokenType)) continue; var re = REs[tokenType]; re.lastIndex = index; var m = re.exec(selector); if (!m) continue; // No match. Try next regexp. tokens.push({ type: tokenType, raw: m[0], valid: true, index: index, }); index = re.lastIndex; continue NEXT_TOKEN; } // No token matched. throw new SyntaxError('invalid selector ' + selector); } // Postprocess token list to get values. for(var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type === 'number') { token.value = Number(token.raw); } else if (token.type === 'str') { token.value = code.parseString(token.raw); } } return tokens; }; module.exports = Selector; ================================================ FILE: server/serialize.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Saving and restoring the state of the interpreter. * @author fraser@google.com (Neil Fraser) */ 'use strict'; var Interpreter = require('./interpreter'); var IterableWeakMap = require('./iterable_weakmap'); var IterableWeakSet = require('./iterable_weakset'); var net = require('net'); var Node = require('./parser').Node; var Registry = require('./registry'); var Serializer = {}; /** * A record of a single serializalbe type, including a type tag, a * constructor function to call when deserializing an instance, and an * optional list of properties to exclude when serializing. * * @typedef {{ * tag: string, * constructor: !Function, * prune: (!Array|undefined), * }} */ var TypeInfo; /** * A configuration object containing an array of TypeInfo objects and * indexes by tag an prototype object. * * @typedef {{ * types: !Array, * byTag: !Object, * byProto: !Map, * }} */ var Config; /** * Create a configuration object for serializing or desieralizing a * particular Interpreter instance. * * @param {!Interpreter} intrp The interpreter instance being serialized * (needed for inner classes). * @return {!Config} The configuration object. */ Serializer.getConfig_ = function(intrp) { var /** !Array */ types = [ // Generic JavaScript types, not including those requring special // construction (like Functions, Dates, RegExps, etc.) {tag: 'Object', constructor: Object}, {tag: 'Array', constructor: Array}, {tag: 'Map', constructor: Map}, {tag: 'Set', constructor: Set}, // Custom types, not Interpreter-specific. {tag: 'IterableWeakMap', constructor: IterableWeakMap, prune: ['refs_', 'finalisers_']}, {tag: 'IterableWeakSet', constructor: IterableWeakSet, prune: ['refs_', 'map_', 'finalisers_']}, {tag: 'Registry', constructor: Registry}, // Interpreter-specific types. {tag: 'Interpreter', constructor: Interpreter, prune: [ 'hrStartTime_', 'previousTime_', 'runner_', 'Object', 'Function', 'UserFunction', 'BoundFunction', 'NativeFunction', 'OldNativeFunction', 'Array', 'Date', 'RegExp', 'Error', 'Arguments', 'WeakMap', 'Thread', 'Box', 'Server', ]}, {tag: 'Scope', constructor: Interpreter.Scope}, {tag: 'State', constructor: Interpreter.State}, {tag: 'Thread', constructor: Interpreter.Thread}, {tag: 'PropertyIterator', constructor: Interpreter.PropertyIterator}, {tag: 'Source', constructor: Interpreter.Source}, {tag: 'PseudoObject', constructor: intrp.Object, prune: ['socket']}, {tag: 'PseudoFunction', constructor: intrp.Function}, {tag: 'PseudoUserFunction', constructor: intrp.UserFunction}, {tag: 'PseudoBoundFunction', constructor: intrp.BoundFunction}, {tag: 'PseudoNativeFunction', constructor: intrp.NativeFunction}, {tag: 'PseudoOldNativeFunction', constructor: intrp.OldNativeFunction}, {tag: 'PseudoArray', constructor: intrp.Array}, {tag: 'PseudoDate', constructor: intrp.Date}, {tag: 'PseudoRegExp', constructor: intrp.RegExp}, {tag: 'PseudoError', constructor: intrp.Error}, {tag: 'PseudoArguments', constructor: intrp.Arguments}, {tag: 'PseudoWeakMap', constructor: intrp.WeakMap}, {tag: 'PseudoThread', constructor: intrp.Thread}, {tag: 'Box', constructor: intrp.Box}, {tag: 'Server', constructor: intrp.Server, prune: ['server_']}, {tag: 'Node', constructor: Node}, ]; var /** !Object */ byTag = Object.create(null); var /** !Map */ byProto = new Map(); for (var type, i = 0; type = types[i]; i++) { byTag[type.tag] = type; byProto.set(type.constructor.prototype, type); } return {types: types, byTag: byTag, byProto: byProto}; }; /** * Deserialize the provided JSON-compatible object into an interpreter. * @param {!Object} JSON-compatible object. * @param {!Interpreter} intrp JS-Interpreter instance. */ Serializer.deserialize = function(json, intrp) { function decodeValue(value) { if (value && typeof value === 'object') { var data; if ((data = value['#'])) { // Object reference: {'#': 42} value = objectList[data]; if (!value) { throw new ReferenceError('Object reference not found: ' + data); } return value; } if ((data = value['Number'])) { // Special number: {'Number': 'Infinity'} return Number(data); } if ((data = value['Value'])) { // Special value: {'Value': 'undefined'} if (value['Value'] === 'undefined') { return undefined; } } } return value; } // Get configuration. var config = Serializer.getConfig_(intrp); if (!Array.isArray(json)) { throw new TypeError('Top-level JSON is not a list.'); } // Require native functions to be present. Can't just create fresh // new interpreter instance because client code may want to add // custom builtins. if (!intrp.global) { throw new Error( 'Interpreter must be initialized prior to deserialization.'); } // Find all native functions to get id => func mappings. var functionHash = Object.create(null); // Builtins. var builtins = Array.from(intrp.builtins.values()); var implProps = ['impl', 'call', 'construct']; for (var i = 0; i < builtins.length; i++) { var builtin = builtins[i]; for (var j = 0; j < implProps.length; j++) { var func = builtin[implProps[j]]; if (func) functionHash[func.id] = func; } } // Step functions. for (var stepName in intrp.stepFuncs) { var stepFunc = intrp.stepFuncs[stepName]; functionHash[stepFunc.id] = stepFunc; } // First pass: Create object stubs for every object. We don't need // to (re)create object #0, because that's the interpreter proper. var objectList = [intrp]; for (var i = 1; i < json.length; i++) { var jsonObj = json[i]; var obj; var tag = jsonObj['type']; // Default case handles most types; sepcial cases handle only // those that can't be correctly created by an unparameterized // construction "new Constructor()". switch (tag) { case 'Function': obj = functionHash[jsonObj['id']]; if (!obj) { throw new RangeError('Function ID not found: ' + jsonObj['id']); } break; case 'Date': obj = new Date(jsonObj['data']); if (isNaN(obj)) { throw new TypeError('Invalid date: ' + jsonObj['data']); } break; case 'RegExp': obj = RegExp(jsonObj['source'], jsonObj['flags']); break; case 'State': // TODO(cpcallen): this is just a little performance kludge so // that the State constructor doesn't need a conditional in it. // Find a more general solution to constructors requiring args. obj = new Interpreter.State(/** @type {?} */({}), /** @type {?} */(undefined)); break; default: if (config.byTag[tag]) { obj = new config.byTag[tag].constructor(); } else { throw new TypeError('Unknown type tag "' + tag + '"'); } } objectList[i] = obj; } // Second pass: Populate properties for every object. for (var i = 0; i < json.length; i++) { var jsonObj = json[i]; var tag = jsonObj['type']; var typeInfo = config.byTag[tag]; var obj = objectList[i]; // Set prototype, if specified. if (jsonObj['proto']) { Object.setPrototypeOf(obj, decodeValue(jsonObj['proto'])); } // Repopulate properties. var prune = (typeInfo && typeInfo.prune) || []; var props = jsonObj['props']; if (props) { var nonConfigurable = jsonObj['nonConfigurable'] || []; var nonEnumerable = jsonObj['nonEnumerable'] || []; var nonWritable = jsonObj['nonWritable'] || []; var keys = Object.getOwnPropertyNames(props); for (var j = 0; j < keys.length; j++) { var key = keys[j]; if (prune.includes(key)) continue; Object.defineProperty(obj, key, {configurable: !nonConfigurable.includes(key), enumerable: !nonEnumerable.includes(key), writable: !nonWritable.includes(key), value: decodeValue(props[key])}); } } // Repopulate sets. if (obj instanceof Set || obj instanceof IterableWeakSet) { var data = jsonObj['data']; if (data) { for (var j = 0; j < data.length; j++) { obj.add(decodeValue(data[j])); } } } // Repopulate maps. if (obj instanceof Map || obj instanceof IterableWeakMap) { var entries = jsonObj['entries']; if (entries) { for (var j = 0; j < entries.length; j++) { var key = decodeValue(entries[j][0]); var value = decodeValue(entries[j][1]); obj.set(key, value); } } } if (jsonObj['isExtensible'] === false) { // N.B. normally omitted if true. Object.preventExtensions(obj); } } // Finally: fixup interpreter state, post-deserialization. intrp.postDeserialize(); }; /** * Serialize the provided interpreter. * @param {!Interpreter} intrp JS-Interpreter instance. * @return {!Object} JSON-compatible object. */ Serializer.serialize = function(intrp) { // First: prepare interpreter for serialization. intrp.preSerialize(); function encodeValue(value) { if (value && (typeof value === 'object' || typeof value === 'function')) { var ref = objectRefs.get(value); if (ref === undefined) { throw new RangeError('object not found in table'); } return {'#': ref}; } if (value === undefined) { return {'Value': 'undefined'}; } if (typeof value === 'number') { if (value === Infinity) { return {'Number': 'Infinity'}; } else if (value === -Infinity) { return {'Number': '-Infinity'}; } else if (Number.isNaN(value)) { return {'Number': 'NaN'}; } else if (Object.is(value, -0)) { return {'Number': '-0'}; } } return value; } // Get configuration. var config = Serializer.getConfig_(intrp); // Find all objects. var objectList = Serializer.getObjectList_(intrp, config); // Build reverse-lookup cache. var /** !Map */ objectRefs = new Map(); for (var i = 0; i < objectList.length; i++) { objectRefs.set(objectList[i], i); } // Serialize every object. var json = []; for (var i = 0; i < objectList.length; i++) { var jsonObj = Object.create(null); json.push(jsonObj); var obj = objectList[i]; // TODO: Add a flag on the '#' prop. On for debugging, off for production. if (true) { jsonObj['#'] = i; } var proto = Object.getPrototypeOf(obj); var typeInfo = config.byProto.get(proto); // Default case handles most types; sepcial cases handle only // those that have extra intenal slots. switch (proto) { case Function.prototype: jsonObj['type'] = 'Function'; jsonObj['id'] = obj.id; if (!obj.id) { throw new Error('Native function has no ID: ' + obj); } continue; // No need to index properties. case Date.prototype: jsonObj['type'] = 'Date'; jsonObj['data'] = obj.toJSON(); continue; // No need to index properties. case RegExp.prototype: jsonObj['type'] = 'RegExp'; jsonObj['source'] = obj.source; jsonObj['flags'] = obj.flags; continue; // No need to index properties. case Map.prototype: jsonObj['type'] = 'Map'; if (obj.size) { jsonObj['entries'] = Array.from(/** @type {?} */(obj),function(entry) { var key = encodeValue(entry[0]); var value = encodeValue(entry[1]); return [key, value]; }); } break; case Set.prototype: jsonObj['type'] = 'Set'; if (obj.size) { jsonObj['data'] = Array.from(obj.values(), encodeValue); } break; case IterableWeakMap.prototype: jsonObj['type'] = 'IterableWeakMap'; if (obj.size) { jsonObj['entries'] = Array.from(/** @type {?} */(obj), function(entry) { var key = encodeValue(entry[0]); var value = encodeValue(entry[1]); return [key, value]; }); } continue; // Mustn't index internal properties for IterableWeakMap case IterableWeakSet.prototype: jsonObj['type'] = 'IterableWeakSet'; if (obj.size) { jsonObj['data'] = Array.from(obj.values(), encodeValue); } continue; // Mustn't index internal properties for IterableWeakSet case Registry.prototype: jsonObj['type'] = 'Registry'; break; default: if (typeInfo) { jsonObj['type'] = typeInfo.tag; } else { jsonObj['type'] = Array.isArray(obj) ? 'Array' : 'Object'; jsonObj['proto'] = encodeValue(proto); } } var props = Object.create(null); var nonConfigurable = []; var nonEnumerable = []; var nonWritable = []; var prune = (typeInfo && typeInfo.prune) || []; var keys = Object.getOwnPropertyNames(obj); for (var j = 0; j < keys.length; j++) { var key = keys[j]; if (prune.includes(key)) continue; // Skip [[Socket]] slot on connected objects. // TODO(cpcallen): this is pretty kludgy. Try to find a better way. if (obj instanceof intrp.Object && key === 'socket') continue; props[key] = encodeValue(obj[key]); var descriptor = Object.getOwnPropertyDescriptor(obj, key); if (!descriptor.configurable) { nonConfigurable.push(key); } if (!descriptor.enumerable) { nonEnumerable.push(key); } if (!descriptor.writable) { nonWritable.push(key); } } if (Object.getOwnPropertyNames(keys).length) { jsonObj['props'] = props; } if (nonConfigurable.length) { jsonObj['nonConfigurable'] = nonConfigurable; } if (nonEnumerable.length) { jsonObj['nonEnumerable'] = nonEnumerable; } if (nonWritable.length) { jsonObj['nonWritable'] = nonWritable; } if (!Object.isExtensible(obj)) { jsonObj['isExtensible'] = false; } } return json; }; /** * Recursively search node to find all non-primitives. * * TODO(cpcallen): use a Registry instead of Array for objectList; * this would allow more readable references by using paths * instead of numerical indices. * @param {*} node JavaScript value to search. * @param {!Config} config Configuation object. * @return {!Array} objectList Array of all objects found via node. */ Serializer.getObjectList_ = function(node, config) { var seen = new Set(); Serializer.objectHunt_(node, config, seen); return Array.from(seen.keys()); }; /** * Recursively search node find all non-primitives. * * @param {*} node JavaScript value to search. * @param {!Config} config Configuation object. * @param {!Set} seen Set of objects found so far. */ Serializer.objectHunt_ = function(node, config, seen) { if (!node || (typeof node !== 'object' && typeof node !== 'function')) { // node is primitive. Nothing to do. return; } var obj = /** @type {!Object} */(node); if (seen.has(obj)) return; var proto = Object.getPrototypeOf(obj); seen.add(obj); if (typeof obj === 'object') { // Recurse. var typeInfo = config.byProto.get(proto); var prune = (typeInfo && typeInfo.prune) || []; // Properties. var keys = Object.getOwnPropertyNames(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (prune.includes(key)) continue; Serializer.objectHunt_(obj[key], config, seen); } // Set members. if (obj instanceof Set || obj instanceof IterableWeakSet) { obj.forEach(function(value) { Serializer.objectHunt_(value, config, seen); }); } // Map entries. if (obj instanceof Map || obj instanceof IterableWeakMap) { obj.forEach(function(value, key) { Serializer.objectHunt_(key, config, seen); Serializer.objectHunt_(value, config, seen); }); } } }; module.exports = Serializer; ================================================ FILE: server/startup/cc.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Initialisation code to expose CC-specific extensions * not exposed by server/startup/esx.js for testing. * @author cpcallen@google.com (Christopher Allen) */ /////////////////////////////////////////////////////////////////////////////// // Namespace for CodeCity-specific extensions. // var CC = {}; /////////////////////////////////////////////////////////////////////////////// // Permissions API. // CC.root = new 'CC.root'; var perms = new 'perms'; var setPerms = new 'setPerms'; /////////////////////////////////////////////////////////////////////////////// // Networking API. // CC.connectionListen = new 'CC.connectionListen'; CC.connectionUnlisten = new 'CC.connectionUnlisten'; CC.connectionWrite = new 'CC.connectionWrite'; CC.connectionClose = new 'CC.connectionClose'; CC.xhr = new 'CC.xhr'; ================================================ FILE: server/startup/es5.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Polyfills to bring the server's partial JavaScript * implementation up to ECMAScript 5.1 (or close to it). * @author fraser@google.com (Neil Fraser) */ // Global functions. var parseInt = new 'parseInt'; var parseFloat = new 'parseFloat'; var isNaN = new 'isNaN'; var isFinite = new 'isFinite'; var escape = new 'escape'; var unescape = new 'unescape'; var decodeURI = new 'decodeURI'; var decodeURIComponent = new 'decodeURIComponent'; var encodeURI = new 'encodeURI'; var encodeURIComponent = new 'encodeURIComponent'; // As a special case, eval is not included in this list: it must be // set in the global scope by the interpreter because binding eval in // strict mode is illegal. // Global objects. var Object = new 'Object'; var Function = new 'Function'; var Array = new 'Array'; var String = new 'String'; var Boolean = new 'Boolean'; var Number = new 'Number'; var Date = new 'Date'; var RegExp = new 'RegExp'; var Error = new 'Error'; var EvalError = new 'EvalError'; var RangeError = new 'RangeError'; var ReferenceError = new 'ReferenceError'; var SyntaxError = new 'SyntaxError'; var TypeError = new 'TypeError'; var URIError = new 'URIError'; var Math = {}; var JSON = {}; // Bootstrap the defineProperty function in two steps. Object.defineProperty = new 'Object.defineProperty'; Object.defineProperty(Object, 'defineProperty', {enumerable: false}); (function() { // Hack to work around restriction that the 'new hack' only works on // literal strings. Note name must not contain any double quotes or // backslashes, because we have no easy way to escape them yet! var builtin = function(name) { return eval('new "' + name + '"'); }; var classes = ['Object', 'Function', 'Array', 'String', 'Boolean', 'Number', 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError']; // Prototypes of global constructors. for (var i = 0; i < classes.length; i++) { var constructor = builtin(classes[i]); Object.defineProperty(constructor, 'prototype', { configurable: false, enumerable: false, writable: false, value: builtin(classes[i] + '.prototype') }); Object.defineProperty(constructor.prototype, 'constructor', { configurable: true, enumerable: false, writable: true, value: constructor }); } // Configure Error and its subclasses. var errors = ['Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError']; for (var i = 0; i < errors.length; i++) { var constructor = builtin(errors[i]); Object.defineProperty(constructor.prototype, 'name', { configurable: true, enumerable: false, writable: true, value: errors[i] }); } Object.defineProperty(Error.prototype, 'message', { configurable: true, enumerable: false, writable: true, value: '' }); // Struct is a list of tuples: // [Object, 'Object', [static methods], [instance methods]] var struct = [ [Object, 'Object', ['getOwnPropertyNames', 'keys', 'getOwnPropertyDescriptor', 'getPrototypeOf', 'isExtensible', 'preventExtensions'], ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'propertyIsEnumerable', 'isPrototypeOf']], [Function, 'Function', [], ['apply', 'bind', 'call', 'toString']], [Array, 'Array', ['isArray'], ['toString', 'pop', 'push', 'shift', 'unshift', 'reverse', 'splice', 'slice', 'concat', 'indexOf', 'lastIndexOf']], [String, 'String', ['fromCharCode'], ['trim', 'toLowerCase', 'toUpperCase', 'toLocaleLowerCase', 'toLocaleUpperCase', 'charAt', 'charCodeAt', 'substring', 'slice', 'substr', 'indexOf', 'lastIndexOf', 'concat', 'localeCompare', 'split', 'match', 'search', 'replace', 'toString', 'valueOf']], [Boolean, 'Boolean', [], ['toString', 'valueOf']], [Number, 'Number', [], ['toExponential', 'toFixed', 'toLocaleString', 'toPrecision', 'toString', 'valueOf']], [Date, 'Date', ['now', 'parse', 'UTC'], ['toString', 'getDate', 'getDay', 'getFullYear', 'getHours', 'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime', 'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear', 'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth', 'getUTCSeconds', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toISOString', 'toJSON', 'toGMTString', 'toTimeString', 'toUTCString', 'toLocaleDateString', 'toLocaleString', 'toLocaleTimeString']], [RegExp, 'RegExp', [], ['toString', 'test', 'exec']], [Error, 'Error', [], ['toString']], [Math, 'Math', ['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'random', 'round', 'sin', 'sqrt', 'tan'], []], [JSON, 'JSON', ['parse', 'stringify'], []] ]; for (var i = 0; i < struct.length; i++) { var obj = struct[i][0]; var objName = struct[i][1]; var staticMethods = struct[i][2]; var instanceMethods = struct[i][3]; for (var j = 0; j < staticMethods.length; j++) { var member = staticMethods[j]; Object.defineProperty(obj, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.' + member)}); } for (var j = 0; j < instanceMethods.length; j++) { var member = instanceMethods[j]; Object.defineProperty(obj.prototype, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.prototype.' + member)}); } } })(); Object.defineProperty(Number, 'MAX_VALUE', { configurable: false, enumerable: false, writable: false, value: 1.7976931348623157e+308 }); Object.defineProperty(Number, 'MIN_VALUE', { configurable: false, enumerable: false, writable: false, value: 5e-324 }); Object.defineProperty(Number, 'NaN', { configurable: false, enumerable: false, writable: false, value: NaN }); Object.defineProperty(Number, 'NEGATIVE_INFINITY', { configurable: false, enumerable: false, writable: false, value: -Infinity }); Object.defineProperty(Number, 'POSITIVE_INFINITY', { configurable: false, enumerable: false, writable: false, value: Infinity }); Object.defineProperty(Math, 'E', { configurable: false, enumerable: false, writable: false, value: 2.718281828459045 }); Object.defineProperty(Math, 'LN2', { configurable: false, enumerable: false, writable: false, value: 0.6931471805599453 }); Object.defineProperty(Math, 'LN10', { configurable: false, enumerable: false, writable: false, value: 2.302585092994046 }); Object.defineProperty(Math, 'LOG2E', { configurable: false, enumerable: false, writable: false, value: 1.4426950408889634 }); Object.defineProperty(Math, 'LOG10E', { configurable: false, enumerable: false, writable: false, value: 0.4342944819032518 }); Object.defineProperty(Math, 'PI', { configurable: false, enumerable: false, writable: false, value: 3.141592653589793 }); Object.defineProperty(Math, 'SQRT1_2', { configurable: false, enumerable: false, writable: false, value: 0.7071067811865476 }); Object.defineProperty(Math, 'SQRT2', { configurable: false, enumerable: false, writable: false, value: 1.4142135623730951 }); Object.defineProperty(RegExp.prototype, 'global', { configurable: false, enumerable: false, writable: false, value: undefined }); Object.defineProperty(RegExp.prototype, 'ignoreCase', { configurable: false, enumerable: false, writable: false, value: undefined }); Object.defineProperty(RegExp.prototype, 'multiline', { configurable: false, enumerable: false, writable: false, value: undefined }); Object.defineProperty(RegExp.prototype, 'source', { configurable: false, enumerable: false, writable: false, value: '(?:)' }); /////////////////////////////////////////////////////////////////////////////// // Object polyfills /////////////////////////////////////////////////////////////////////////////// // Add a polyfill to handle create's second argument. Object.create = function create(proto, props) { var obj = (new 'Object.create')(proto); props && Object.defineProperties(obj, props); return obj; }; Object.defineProperty(Object, 'create', {enumerable: false}); Object.defineProperties = function defineProperties(obj, props) { if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { throw new TypeError('Object.defineProperties called on type ' + typeof obj + ', not type object or function'); } var keys = Object.keys(props); for (var i = 0; i < keys.length; i++) { Object.defineProperty(obj, keys[i], props[keys[i]]); } return obj; }; Object.defineProperty(Object, 'defineProperties', {enumerable: false}); Object.isFrozen = function isFrozen(obj) { // TODO: replace this with builtin version. // Per ES5.1, §15.2.3.12 if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) { throw new TypeError('Primitive is already immutable'); } var keys = Object.getOwnPropertyNames(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var pd = Object.getOwnPropertyDescriptor(obj, key); // Assume no accessor properties. if (pd.configurable || pd.writable) return false; } if (Object.isExtensible) return false; return true; }; Object.defineProperty(Object, 'isFrozen', {enumerable: false}); Object.isSealed = function isSealed(obj) { // TODO: replace this with builtin version. // Per ES5.1, §15.2.3.12 if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) { throw new TypeError('Primitive is already immutable'); } var keys = Object.getOwnPropertyNames(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var pd = Object.getOwnPropertyDescriptor(obj, key); if (pd.configurable) return false; } if (Object.isExtensible) return false; return true; }; Object.defineProperty(Object, 'isSealed', {enumerable: false}); Object.freeze = function freeze(obj) { // TODO: replace this with builtin version. // Per ES5.1, §15.2.3.9 if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) { throw new TypeError('Primitive is already immutable'); } var keys = Object.getOwnPropertyNames(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; // Assume no accessor properties. Object.defineProperty(obj, key, {writable: false, configurable: false}); } Object.preventExtensions(obj); }; Object.defineProperty(Object, 'freeze', {enumerable: false}); Object.seal = function seal(obj) { // TODO: replace this with builtin version. // Per ES5.1, §15.2.3.8 if (obj === null || !(typeof obj === 'object' || typeof obj === 'function')) { throw new TypeError('Primitive is already immutable'); } var keys = Object.getOwnPropertyNames(obj); for (var i = 0; i < keys.length; i++) { var key = keys[i]; // Assume no accessor properties. Object.defineProperty(obj, key, {configurable: false}); } Object.preventExtensions(obj); }; Object.defineProperty(Object, 'seal', {enumerable: false}); /////////////////////////////////////////////////////////////////////////////// // Array.prototype polyfills /////////////////////////////////////////////////////////////////////////////// Array.prototype.every = function every(callback/*, thisArg*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/ever if (this === null || this === undefined) { throw new TypeError('Array.prototype.every called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var thisArg = arguments[1]; for (var k = 0; k < len; k++) { if (k in o && !callback.call(thisArg, o[k], k, o)) return false; } return true; }; Object.defineProperty(Array.prototype, 'every', {enumerable: false}); Array.prototype.filter = function filter(callback/*, thisArg*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/filter if (this === null || this === undefined) { throw new TypeError('Array.prototype.filter called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var res = []; var thisArg = arguments[1]; for (var i = 0; i < len; i++) { if (i in o) { var val = o[i]; if (callback.call(thisArg, val, i, o)) res.push(val); } } return res; }; Object.defineProperty(Array.prototype, 'filter', {enumerable: false}); Array.prototype.forEach = function forEach(callback/*, thisArg*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach if (this === null || this === undefined) { throw new TypeError('Array.prototype.forEach called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var thisArg = arguments[1]; for (var k = 0; k < len; k++) { if (k in o) callback.call(thisArg, o[k], k, o); } }; Object.defineProperty(Array.prototype, 'forEach', {enumerable: false}); (function() { // For cycle detection in array to string and error conversion; see // spec bug github.com/tc39/ecma262/issues/289. var visited = []; Array.prototype.join = function join(separator) { // This implements Array.prototype.join from ES5 §15.4.4.5, with // the addition of cycle detection as discussed in // https://github.com/tc39/ecma262/issues/289. // // Variable names reflect those in the spec. // // N.B. This function is defined in a closure! var isObj = (typeof this === 'object' || typeof this === 'function') && this !== null; if (isObj) { if (visited.indexOf(this) !== -1) { return ''; } visited.push(this); } try { // TODO(cpcallen): setPerms(callerPerms()); var len = this.length >>> 0; var sep = (separator === undefined) ? ',' : String(separator); if (!len) { return ''; } var r = ''; for (var k = 0; k < len; k++) { if (k > 0) r += sep; var element = this[k]; if (element !== undefined && element !== null) { r += String(element); } } return r; } finally { if (isObj) visited.pop(); } }; })(); Object.defineProperty(Array.prototype, 'join', {enumerable: false}); Array.prototype.map = function map(callback/*, thisArg*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map if (this === null || this === undefined) { throw new TypeError('Array.prototype.map called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var A = new Array(len); var thisArg = arguments[1]; for (var k = 0; k < len; k++) { if (k in o) A[k] = callback.call(thisArg, o[k], k, o); } return A; }; Object.defineProperty(Array.prototype, 'map', {enumerable: false}); Array.prototype.reduce = function reduce(callback /*, initialValue*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce if (this === null || this === undefined) { throw new TypeError('Array.prototype.reduce called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var k = 0; var value; if (arguments.length > 1) { value = arguments[1]; } else { while (k < len && !(k in o)) k++; if (k >= len) { throw new TypeError('Reduce of empty array with no initial value'); } value = o[k++]; } for (; k < len; k++) { if (k in o) value = callback(value, o[k], k, o); } return value; }; Object.defineProperty(Array.prototype, 'reduce', {enumerable: false}); Array.prototype.reduceRight = function reduceRight(callback /*, initialValue*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/ReduceRight if (this === null || this === undefined) { throw new TypeError('Array.prototype.reduceRight called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var k = len - 1; var value; if (arguments.length > 1) { value = arguments[1]; } else { while (k >= 0 && !(k in o)) k--; if (k < 0) { throw new TypeError('Reduce of empty array with no initial value'); } value = o[k--]; } for (; k >= 0; k--) { if (k in o) value = callback(value, o[k], k, o); } return value; }; Object.defineProperty(Array.prototype, 'reduceRight', {enumerable: false}); Array.prototype.some = function some(callback/*, thisArg*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/some if (this === null || this === undefined) { throw new TypeError('Array.prototype.some called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var thisArg = arguments[1]; for (var i = 0; i < len; i++) { if (i in o && callback.call(thisArg, o[i], i, o)) { return true; } } return false; }; Object.defineProperty(Array.prototype, 'some', {enumerable: false}); Array.prototype.sort = function sort(comparefn) { // Polylfill adapted from: // https://github.com/v8/v8/blob/8e43b9c01d60ddb5e58ec8de9d34616ea1bb905f/src/js/array.js // TODO(cpcallen): as of ES2020, Array.prototype.sort must be stable. var obj = this; // Let obj = ToObject(this) if (typeof(obj) !== 'object' && typeof(obj) !== 'function' || obj === null) { throw new TypeError("Can't convert " + obj + ' to Object'); } // Let len = ToLength(obj.length) var len = Number(obj.length); if (isNaN(len) || len < 0) len = 0; if (len !== 0 && isFinite(len)) len = Math.trunc(len); len = Math.min(len, Number.MAX_SAFE_INTEGER); // Make sure comparefn is usable. if (comparefn === undefined) { comparefn = function (x, y) { x = String(x); y = String(y); if (x === y) return 0; else return x < y ? -1 : 1; }; } else if(typeof(comparefn) !== 'function') { throw new TypeError( 'The comparison function must be either a function or undefined'); } if (len < 2) return obj; // The ES spec says that the sort order is implementation-defined if // the array (or array-like) being sorted is sparse and prototype // properties can be seen through the holes. // // Previously V8 (for compatibility with JSC) also sorted properties // inherited from the prototype chain on non-Array objects. It did // this by copying them to this object and sorting only own // properties. Newer versions of V8 don't seem to do this any more, // so for simplicity we sort only own properties. // // We do this by first moving all non-undefined properties to the // front of the array and move the undefineds after that. This // moves holes to the end. // // TODO(cpcallen): this is slow. Do it (as V8 did, before moving to // a torque-based implementation) using a native function. var undefCount = 0; for (var i = 0, j = 0; j < len; j++) { if (Object.prototype.hasOwnProperty.call(obj, j)) { if (obj[j] === undefined) { undefCount++; } else { obj[i++] = obj[j]; } } } var definedCount = i; for (; undefCount; undefCount--) { obj[i++] = undefined; } for (; i < len; i++) { delete obj[i]; } Array.prototype.sort.quicksort_(obj, 0, definedCount, comparefn); return obj; }; Object.defineProperty(Array.prototype, 'sort', {enumerable: false}); // Helper functions. Array.prototype.sort.insertionSort_ = function insertionSort_( a, from, to, comparefn) { // For short (length <= 10) arrays, insertion sort is used for efficiency. for (var i = from + 1; i < to; i++) { var element = a[i]; for (var j = i - 1; j >= from; j--) { var tmp = a[j]; var order = comparefn(tmp, element); if (order > 0) { a[j + 1] = tmp; } else { break; } } a[j + 1] = element; } }; Object.defineProperty(Array.prototype.sort, 'insertionSort_', {enumerable: false}); Array.prototype.sort.getThirdIndex_ = function getThirdIndex_( a, from, to, comparefn) { var t_array = []; // Use both 'from' and 'to' to determine the pivot candidates. var increment = 200 + ((to - from) & 15); var j = 0; from += 1; to -= 1; for (var i = from; i < to; i += increment) { t_array[j] = [i, a[i]]; j++; } t_array.sort(function(a, b) { return comparefn(a[1], b[1]); }); var third_index = t_array[t_array.length >> 1][0]; return third_index; }; Object.defineProperty(Array.prototype.sort, 'getThirdIndex_', {enumerable: false}); Array.prototype.sort.quicksort_ = function quicksort_(a, from, to, comparefn) { /* In-place QuickSort algorithm. */ var third_index = 0; while (true) { // Insertion sort is faster for short arrays. if (to - from <= 10) { Array.prototype.sort.insertionSort_(a, from, to, comparefn); return; } if (to - from > 1000) { third_index = Array.prototype.sort.getThirdIndex_(a, from, to, comparefn); } else { third_index = from + ((to - from) >> 1); } // Find a pivot as the median of first, last and middle element. var v0 = a[from]; var v1 = a[to - 1]; var v2 = a[third_index]; var c01 = comparefn(v0, v1); if (c01 > 0) { // v1 < v0, so swap them. var tmp = v0; v0 = v1; v1 = tmp; } // v0 <= v1. var c02 = comparefn(v0, v2); if (c02 >= 0) { // v2 <= v0 <= v1. var tmp = v0; v0 = v2; v2 = v1; v1 = tmp; } else { // v0 <= v1 && v0 < v2 var c12 = comparefn(v1, v2); if (c12 > 0) { // v0 <= v2 < v1 var tmp = v1; v1 = v2; v2 = tmp; } } // v0 <= v1 <= v2 a[from] = v0; a[to - 1] = v2; var pivot = v1; var low_end = from + 1; // Upper bound of elements lower than pivot. var high_start = to - 1; // Lower bound of elements greater than pivot. a[third_index] = a[low_end]; a[low_end] = pivot; // From low_end to i are elements equal to pivot. // From i to high_start are elements that haven't been compared yet. partition: for (var i = low_end + 1; i < high_start; i++) { var element = a[i]; var order = comparefn(element, pivot); if (order < 0) { a[i] = a[low_end]; a[low_end] = element; low_end++; } else if (order > 0) { do { high_start--; if (high_start == i) break partition; var top_elem = a[high_start]; order = comparefn(top_elem, pivot); } while (order > 0); a[i] = a[high_start]; a[high_start] = element; if (order < 0) { element = a[i]; a[i] = a[low_end]; a[low_end] = element; low_end++; } } } if (to - high_start < low_end - from) { quicksort_(a, high_start, to, comparefn); to = low_end; } else { quicksort_(a, from, low_end, comparefn); from = high_start; } } }; Object.defineProperty(Array.prototype.sort, 'quicksort_', {enumerable: false}); Array.prototype.toLocaleString = function toLocaleString() { var out = []; for (var i = 0; i < this.length; i++) { out[i] = (this[i] === null || this[i] === undefined) ? '' : this[i].toLocaleString(); } return out.join(','); }; Object.defineProperty(Array.prototype, 'toLocaleString', {enumerable: false}); /////////////////////////////////////////////////////////////////////////////// // String.prototype polyfills /////////////////////////////////////////////////////////////////////////////// // String.prototype.length is always 0. Object.defineProperty(String.prototype, 'length', {value: 0}); String.prototype.replace = function replace(substr, newSubstr) { // Polyfill to handle String.prototype.replace's second argument being // a function. if (typeof newSubstr !== 'function') { // string.replace(string|regexp, string) return (new 'String.prototype.replace').call(this, substr, newSubstr); } var str = this; if (substr instanceof RegExp) { // string.replace(regexp, function) var subs = []; var m = substr.exec(str); while (m) { m.push(m.index, str); var inject = newSubstr.apply(undefined, m); subs.push([m.index, m[0].length, inject]); m = substr.global ? substr.exec(str) : null; } for (var i = subs.length - 1; i >= 0; i--) { str = str.substring(0, subs[i][0]) + subs[i][2] + str.substring(subs[i][0] + subs[i][1]); } } else { // string.replace(string, function) var i = str.indexOf(substr); if (i !== -1) { var inject = newSubstr(str.substr(i, substr.length), i, str); str = str.substring(0, i) + inject + str.substring(i + substr.length); } } return str; }; Object.defineProperty(String.prototype, 'replace', {enumerable: false}); ================================================ FILE: server/startup/es6.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Polyfills to bring the server's partial JavaScript * implementation to include some features of ECMAScript 2015 (ES6). * @author fraser@google.com (Neil Fraser) */ // Global objects. var WeakMap = new 'WeakMap'; (function() { // Hack to work around restriction that the 'new hack' only works on // literal strings. Note name must not contain any double quotes or // backslashes, because we have no easy way to escape them yet! var builtin = function(name) { return eval('new "' + name + '"'); }; var classes = ['WeakMap']; // Prototypes of global constructors. for (var i = 0; i < classes.length; i++) { var constructor = builtin(classes[i]); Object.defineProperty(constructor, 'prototype', { configurable: false, enumerable: false, writable: false, value: builtin(classes[i] + '.prototype') }); Object.defineProperty(constructor.prototype, 'constructor', { configurable: true, enumerable: false, writable: true, value: constructor }); } // Struct is a list of tuples: // [Object, 'Object', [static methods], [instance methods]] var struct = [ [Object, 'Object', ['is', 'setPrototypeOf'], []], [String, 'String', [], ['endsWith', 'includes', 'repeat', 'startsWith']], [Number, 'Number', ['isFinite', 'isInteger', 'isNaN', 'isSafeInteger'], []], [Math, 'Math', ['acosh', 'asinh', 'atanh', 'cbrt', 'clz32', 'cosh', 'expm1', 'fround', 'hypot', 'imul', 'log10', 'log1p', 'log2', 'sign', 'sinh', 'tanh', 'trunc'], []], [WeakMap, 'WeakMap', [], ['delete', 'get', 'has', 'set']], ]; for (var i = 0; i < struct.length; i++) { var obj = struct[i][0]; var objName = struct[i][1]; var staticMethods = struct[i][2]; var instanceMethods = struct[i][3]; for (var j = 0; j < staticMethods.length; j++) { var member = staticMethods[j]; Object.defineProperty(obj, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.' + member)}); } for (var j = 0; j < instanceMethods.length; j++) { var member = instanceMethods[j]; Object.defineProperty(obj.prototype, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.prototype.' + member)}); } } })(); /////////////////////////////////////////////////////////////////////////////// // Object constructor polyfills /////////////////////////////////////////////////////////////////////////////// Object.assign = function assign(target, varArgs) { // The length property of the assign method is 2. if (target === null || target === undefined) { throw new TypeError('Cannot convert undefined or null to object'); } target = Object(target); for (var i = 1; i < arguments.length; i++) { var src = arguments[i]; if (src !== null && src !== undefined) { var keys = Object.keys(src); for (var j = 0; j < keys.length; j++) { var key = keys[j]; target[key] = src[key]; } } } return target; }; Object.defineProperty(Array, 'assign', {enumerable: false}); /////////////////////////////////////////////////////////////////////////////// // Array constructor polyfills /////////////////////////////////////////////////////////////////////////////// Array.from = function(arrayLike/*, mapFn, thisArg */) { // Polyfill adapted from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from // The length property of the from method is 1. var isCallable = function (fn) { return typeof fn === 'function' || Object.prototype.toString.call(fn) === '[object Function]'; }; var toInteger = function (value) { var number = Number(value); if (isNaN(number)) { return 0; } if (number === 0 || !isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }; var toLength = function (value) { var len = toInteger(value); return Math.min(Math.max(len, 0), Number.MAX_SAFE_INTEGER); }; // 1. Let C be the this value. var C = this; // 2. Let items be ToObject(arrayLike). var items = Object(arrayLike); // 3. ReturnIfAbrupt(items). if (arrayLike == null) { throw new TypeError('Array.from requires an array-like object - not null or undefined'); } // 4. If mapfn is undefined, then let mapping be false. var mapFn = arguments.length > 1 ? arguments[1] : void undefined; var T; if (typeof mapFn !== 'undefined') { // 5. else // 5. a If IsCallable(mapfn) is false, throw a TypeError exception. if (!isCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined. if (arguments.length > 2) { T = arguments[2]; } } // 10. Let lenValue be Get(items, "length"). // 11. Let len be ToLength(lenValue). var len = toLength(items.length); // 13. If IsConstructor(C) is true, then // 13. a. Let A be the result of calling the [[Construct]] internal method // of C with an argument list containing the single item len. // 14. a. Else, Let A be ArrayCreate(len). var A = isCallable(C) ? Object(new C(len)) : new Array(len); // 16. Let k be 0. var k = 0; // 17. Repeat, while k < len… (also steps a - h) var kValue; while (k < len) { kValue = items[k]; if (mapFn) { A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k); } else { A[k] = kValue; } k += 1; } // 18. Let putStatus be Put(A, "length", len, true). A.length = len; // 20. Return A. return A; }; Object.defineProperty(Array, 'from', {enumerable: false}); /////////////////////////////////////////////////////////////////////////////// // Array.prototype polyfills /////////////////////////////////////////////////////////////////////////////// Array.prototype.find = function find(callback/*, thisArg*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/find if (this === null || this === undefined) { throw new TypeError('Array.prototype.find called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var thisArg = arguments[1]; for (var k = 0; k < len; k++) { var kValue = o[k]; if (callback.call(thisArg, kValue, k, o)) { return kValue; } } return undefined; }; Object.defineProperty(Array.prototype, 'find', {enumerable: false}); Array.prototype.findIndex = function findIndex(callback/*, thisArg*/) { // Polyfill copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex if (this === null || this === undefined) { throw new TypeError('Array.prototype.findIndex called on ' + this); } else if (typeof callback !== 'function') { throw new TypeError('callback is type ' + typeof callback + ', not type function'); } var o = Object(this); var len = o.length >>> 0; var thisArg = arguments[1]; for (var k = 0; k < len; k++) { var kValue = o[k]; if (callback.call(thisArg, kValue, k, o)) { return k; } } return -1; }; Object.defineProperty(Array.prototype, 'findIndex', {enumerable: false}); (function() { function toInteger(value) { var number = Number(value); if (isNaN(number)) { return 0; } else if (number === 0 || !isFinite(number)) { return number; } return Math.trunc(number); } function toLength(value) { var len = toInteger(value); if (len <= 0) { return 0; } return Math.min(len, Number.MAX_SAFE_INTEGER); // Handles len === Infinity. } // For cycle detection in array to string and error conversion; see // spec bug github.com/tc39/ecma262/issues/289. var visited = []; Array.prototype.join = function join(separator) { // This implements Array.prototype.join from ES6 §22.1.3.12, with // the addition of cycle detection as discussed in // https://github.com/tc39/ecma262/issues/289. // // The only difference from the ES5 version of the spec is that // .length is normalised using the specification function // ToLength rather than ToUint32. // // Variable names reflect those in the spec. // // N.B. This function is defined in a closure! var isObj = (typeof this === 'object' || typeof this === 'function') && this !== null; if (isObj) { if (visited.indexOf(this) !== -1) { return ''; } visited.push(this); } try { // TODO(cpcallen): setPerms(callerPerms()); var len = toLength(this.length); var sep = (separator === undefined) ? ',' : String(separator); if (!len) { return ''; } var r = ''; for (var k = 0; k < len; k++) { if (k > 0) { r += sep; } var element = this[k]; if (element !== undefined && element !== null) { r += String(element); } } return r; } finally { if (isObj) { visited.pop(); } } }; })(); Object.defineProperty(Array.prototype, 'join', {enumerable: false}); /////////////////////////////////////////////////////////////////////////////// // Number polyfills /////////////////////////////////////////////////////////////////////////////// Object.defineProperty(Number, 'EPSILON', {configurable: false, enumerable: false, writable: false, value: Math.pow(2, -52)}); Object.defineProperty(Number, 'MAX_SAFE_INTEGER', {configurable: false, enumerable: false, writable: false, // Fortunately 2**53 is also safe as long as you don't increment it!: value: Math.pow(2, 53) - 1 }); Object.defineProperty(Number, 'MIN_SAFE_INTEGER', {configurable: false, enumerable: false, writable: false, value: -Number.MAX_SAFE_INTEGER}); ================================================ FILE: server/startup/es7.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Polyfills to bring the server's partial JavaScript * implementation to include some features of ECMAScript 2016 (ES7). * @author fraser@google.com (Neil Fraser) */ /////////////////////////////////////////////////////////////////////////////// // Array.prototype methods /////////////////////////////////////////////////////////////////////////////// Array.prototype.includes = new 'Array.prototype.includes'; Object.defineProperty(Array.prototype, 'includes', {enumerable: false}); ================================================ FILE: server/startup/es8.js ================================================ /** * @license * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Polyfills to bring the server's partial JavaScript * implementation to include some features of ECMAScript 2017 (ES8). * @author cpcallen@google.com (Christopher Allen) */ /////////////////////////////////////////////////////////////////////////////// // Object constructor polyfills /////////////////////////////////////////////////////////////////////////////// Object.getOwnPropertyDescriptors = function getOwnPropertyDescriptors(obj) { var ownKeys = Object.getOwnPropertyNames(obj); var descriptors = {}; for (var i = 0; i < ownKeys.length; i++) { var key = ownKeys[i]; var descriptor = Object.getOwnPropertyDescriptor(obj, key); if (descriptor !== undefined) { descriptors[key] = descriptor; } } return descriptors; }; Object.defineProperty(Object, 'getOwnPropertyDescriptors', {enumerable: false}); ================================================ FILE: server/startup/esx.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Initialisation code to set up CodeCity JavaScript * extensions. * @author cpcallen@google.com (Christopher Allen) */ // Global objects. var Thread = new 'Thread'; var PermissionError = new 'PermissionError'; (function() { // Hack to work around restriction that the 'new hack' only works on // literal strings. Note name must not contain any double quotes or // backslashes, because we have no easy way to escape them yet! var builtin = function(name) { return eval('new "' + name + '"'); }; var classes = ['PermissionError', 'Thread']; // Prototypes of global constructors. for (var i = 0; i < classes.length; i++) { var constructor = builtin(classes[i]); Object.defineProperty(constructor, 'prototype', { configurable: false, enumerable: false, writable: false, value: builtin(classes[i] + '.prototype') }); Object.defineProperty(constructor.prototype, 'constructor', { configurable: true, enumerable: false, writable: true, value: constructor }); } // Configure Error subclasses. var errors = ['PermissionError']; for (var i = 0; i < errors.length; i++) { var constructor = builtin(errors[i]); Object.defineProperty(constructor.prototype, 'name', { configurable: true, enumerable: false, writable: true, value: errors[i] }); } // Struct is a list of tuples: // [Object, 'Object', [static methods], [instance methods]] var struct = [ [Object, 'Object', ['getOwnerOf', 'setOwnerOf'], []], [Thread, 'Thread', ['current', 'kill', 'suspend', 'callers'], ['getTimeLimit', 'setTimeLimit']], ]; for (var i = 0; i < struct.length; i++) { var obj = struct[i][0]; var objName = struct[i][1]; var staticMethods = struct[i][2]; var instanceMethods = struct[i][3]; for (var j = 0; j < staticMethods.length; j++) { var member = staticMethods[j]; Object.defineProperty(obj, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.' + member)}); } for (var j = 0; j < instanceMethods.length; j++) { var member = instanceMethods[j]; Object.defineProperty(obj.prototype, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.prototype.' + member)}); } } })(); /////////////////////////////////////////////////////////////////////////////// // Array.prototype polyfills /////////////////////////////////////////////////////////////////////////////// (function() { function toInteger(value) { var number = Number(value); if (isNaN(number)) { return 0; } else if (number === 0 || !isFinite(number)) { return number; } return Math.trunc(number); } function toLength(value) { var len = toInteger(value); if (len <= 0) return 0; return Math.min(len, Number.MAX_SAFE_INTEGER); // Handles len === Infinity. }; // For cycle detection in array to string and error conversion; see // spec bug github.com/tc39/ecma262/issues/289. var visitedByThread = new WeakMap; Array.prototype.join = function join(separator) { // This implements Array.prototype.join from ES6 §22.1.3.12, // with the addition of cycle detection as discussed in // https://github.com/tc39/ecma262/issues/289. // // The only difference from the ES6 version is that the cycle // detection mechanism is thread-aware, so multiple parallel // invocations of .join will not interfere with each other. // // Variable names reflect those in the spec. // // N.B. This function is defined in a closure! var isObj = (typeof this === 'object' || typeof this === 'function') && this !== null; if (isObj) { if (visitedByThread.has(Thread.current())) { var visited = visitedByThread.get(Thread.current()); } else { visited = []; visitedByThread.set(Thread.current(), visited); } if (visited.includes(this)) { return ''; } visited.push(this); } try { // TODO(cpcallen): setPerms(callerPerms()); var len = toLength(this.length); var sep = (separator === undefined) ? ',' : String(separator); if (!len) { return ''; } var r = ''; for (var k = 0; k < len; k++) { if (k > 0) r += sep; var element = this[k]; if (element !== undefined && element !== null) { r += String(element); } } return r; } finally { if (isObj) visited.pop(); if (!visited.length) { visitedByThread.delete(Thread.current()); } } }; })(); Object.defineProperty(Array.prototype, 'join', {enumerable: false}); /////////////////////////////////////////////////////////////////////////////// // Threads API; parts are roughly conformant with HTML Living // Standard, plus our local extensions. // var suspend = new 'Thread.suspend'; var setTimeout = function setTimeout(func, delay) { /* setTimeout(func, delay[, ...args]) -> thread * * Arguments: * func : A function to call when the timer elapses. * delay : Time to wait (in ms) before calling the callback. * ...args : Optional arguments to pass to func. * * Returns: * , which may be passed to clearTimeout() to cancel. */ // TODO(cpcallen:perms): setPerms(callerPerms()); var args = Array.prototype.slice.call(arguments, 2); args = [undefined, func, delay, undefined].concat(args); return new (Thread.bind.apply(Thread, args)); // The parens around Thread.bind.apply(...) are mandatory: we want to // "new" the function returned by bind, not apply (which is not a // constructor). return new (Thread.bind.apply(Thread, args))(); }; var clearTimeout = function clearTimeout(thread) { /* clearTimeout(thread) * * Arguments: * thread : The Thread object whose execution to be cancelled. * * Note that attempts to cancel the current thread (or any non-Thread * value) is silently ignored. */ // TODO(cpcallen:perms): setPerms(callerPerms()); if (!(thread instanceof Thread) || thread === Thread.current()) { return; } Thread.kill(thread); }; ================================================ FILE: server/tests/code_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Tests for utilities for manipulating JavaScript code. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const {quote, parseString, testOnly} = require('../code'); const {T} = require('./testing'); const util = require('util'); // Unpack test-only exports: const {count} = testOnly; /** * Unit tests for the count function. * @param {!T} t The test runner object. */ exports.testCount = function(t) { t.expect("count('bobob', 'b')", count('bobob', 'b'), 3); t.expect("count('bobob', 'bo')", count('bobob', 'bo'), 2); t.expect("count('bobob', 'bob')", count('bobob', 'bob'), 1); t.expect("count('bobobob', 'bob')", count('bobobob', 'bob'), 2); }; /** * Unit tests for the quote function. * @param {!T} t The test runner object. */ exports.testQuote = function(t) { const cases = [ ['foo', "'foo'"], ['"Hi", he said.', "'\"Hi\", he said.'"], ["Don't.", '"Don\'t."'], ['\'"', "'\\'\"'"], ['\0\/\b\n\r\t\v\\\x05\u2028\u2029', "'\\0/\\b\\n\\r\\t\\v\\\\\\x05\\u2028\\u2029'"], ]; for (const tc of cases) { const r = quote(tc[0]); t.expect(util.format('quote(%o)', tc[0]), r, tc[1]); t.expect(util.format('eval(quote(%o))', tc[0]), eval(r), tc[0]); } }; /** * Unit tests for the parseString function. * @param {!T} t The test runner object. */ exports.testParseString = function(t) { const cases = [ `'foo'`, `'"Hi", he said.'`, `"\\"Hi\\", he said."`, `'Don\\'t.'`, `"Don't."`, `'\\0 \\' \\" \\/ \\b \\n \\r \\t \\v \\\\ \\x00 \\xfF \\u09aF'`, ]; for (const tc of cases) { const r = parseString(tc); t.expect(util.format('parseString(%o)', tc), r, eval(tc)); } const badCases = [ `'foo`, `""Hi", he said."`, `'Don't.'`, `'\\j'`, `'\\x0'`, `'\\u123'`, `'\\x1g'`, `'\\x1G'`, `'\\u1g00'`, `'\\u1G00'`, `'\r'`, `'\n'`, `'\u2028'`, `'\u2029'`, // Pathological cases that previously caused exponential // backtracking. `'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`, `"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx`, ]; for (const tc of badCases) { try { const r = parseString(tc); t.fail(util.format('parseString(%o)', tc), "Didn't throw."); } catch (e) { t.pass(util.format('parseString(%o)', tc)); } } }; ================================================ FILE: server/tests/db/core_01_$.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Initialize the $ object in the database. * @author fraser@google.com (Neil Fraser) */ var $ = {}; ================================================ FILE: server/tests/db/core_01_$.system.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Initialize the system object in the database. * @author fraser@google.com (Neil Fraser) */ $.system = {}; $.system.log = new 'CC.log'; $.system.checkpoint = new 'CC.checkpoint'; $.system.shutdown = new 'CC.shutdown'; ================================================ FILE: server/tests/db/test.cfg ================================================ { "databaseDirectory": "./", "checkpointInterval": 0, "checkpointAtShutdown": true } ================================================ FILE: server/tests/db/test_00_start.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Mock up a basic console. * @author fraser@google.com (Neil Fraser) */ var console = {}; console.log = $.system.log; console.assert = function(value, message) { if (value) { console.goodCount++; } else { $.system.log('FAIL:\t%s', message); console.badCount++; } }; // Counters for unit test results. console.goodCount = 0; console.badCount = 0; var tests = {}; ================================================ FILE: server/tests/db/test_01_es5.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test the ES5 functions of the server. * @author fraser@google.com (Neil Fraser) */ // Run some tests of the various constructors and their associated // literals and prototype objects. tests.builtinClasses = function() { var classes = [ { constructor: Object, literal: {}, prototypeProto: null, classStr: '[object Object]', }, { constructor: Function, literal: function(){}, prototypeType: 'function', classStr: '[object Function]', }, { constructor: Array, literal: [], classStr: '[object Array]', }, { constructor: RegExp, literal: /foo/, classStr: '[object RegExp]', prototypeClass: '[object Object]' // Was 'RegExp' in ES5.1. }, { constructor: Date, classStr: '[object Date]', prototypeClass: '[object Object]', // Was 'RegExp' in ES5.1. functionNotConstructor: true // Date() doesn't construct. }, { constructor: Error, classStr: '[object Error]', }, { constructor: EvalError, prototypeProto: Error.prototype, classStr: '[object Error]', }, { constructor: RangeError, prototypeProto: Error.prototype, classStr: '[object Error]', }, { constructor: ReferenceError, prototypeProto: Error.prototype, classStr: '[object Error]', }, { constructor: SyntaxError, prototypeProto: Error.prototype, classStr: '[object Error]', }, { constructor: TypeError, prototypeProto: Error.prototype, classStr: '[object Error]', }, { constructor: URIError, prototypeProto: Error.prototype, classStr: '[object Error]', }, { constructor: Boolean, literal: true, literalType: 'boolean', noInstance: true, classStr: '[object Boolean]', }, { constructor: Number, literal: 42, literalType: 'number', noInstance: true, classStr: '[object Number]', }, { constructor: String, literal: "hello", literalType: 'string', noInstance: true, classStr: '[object String]', } ]; for (var i = 0, tc; (tc = classes[i]); i++) { var c = tc.constructor; var prototypeType = (tc.prototypeType || 'object'); // Check constructor is a function: console.assert(typeof c === 'function', c + ' isFunction'); // Check constructor's proto is Function.prototype console.assert(Object.getPrototypeOf(c) === Function.prototype, c + ' protoIsFunctionPrototype'); // Check prototype is of correct type: console.assert(typeof c.prototype === prototypeType, c + ' prototypeIs'); // Check prototype has correct class: console.assert( Object.prototype.toString.apply(c.prototype) === tc.prototypeClass || tc.classStr, c + ' prototypeClassIs'); // Check prototype has correct proto: console.assert( Object.getPrototypeOf(c.prototype) === (tc.prototypeProto === undefined ? Object.prototype : tc.prototypeProto), c + ' prototypeProtoIs'); // Check prototype's .constructor is constructor: console.assert(c.prototype.constructor === c, c + ' prototypeConstructorIs'); if (!tc.noInstance) { // Check instance's type: console.assert(typeof new c === prototypeType, c + ' instanceIs'); // Check instance's proto: console.assert(Object.getPrototypeOf(new c) === c.prototype, c + ' instancePrototypeIs'); // Check instance's class: console.assert(Object.prototype.toString.apply(new c) === tc.classStr, c + ' instanceClassIs'); // Check instance is instanceof its contructor: console.assert((new c) instanceof c, c + ' instanceIsInstanceof'); if (!tc.functionNotConstructor) { // Recheck instances when constructor called as function: // Recheck instance's type: console.assert(typeof c() === prototypeType, c + ' returnIs'); // Recheck instance's proto: console.assert(Object.getPrototypeOf(c()) === c.prototype, c + ' returnPrototypeIs'); // Recheck instance's class: console.assert(Object.prototype.toString.apply(c()) === tc.classStr, c + ' returnClassIs'); // Recheck instance is instanceof its contructor: console.assert(c() instanceof c, c + ' returnIsInstanceof'); } } if (tc.literal) { var literalType = (tc.literalType || prototypeType); // Check literal's type: console.assert(typeof tc.literal === literalType, c + ' literalIs'); // Check literal's proto: console.assert(Object.getPrototypeOf(tc.literal) === c.prototype, c + ' literalPrototypeIs'); // Check literal's class: console.assert( Object.prototype.toString.apply(tc.literal) === tc.classStr, c + ' literalClassIs'); // Primitives can never be instances. if (literalType === 'object' || literalType === 'function') { // Check literal is instanceof its constructor. console.assert(tc.literal instanceof c, c + ' literalIsInstanceof'); } } } }; // Run some tests of switch statements with fallthrough. tests.switchFallthrough = function() { var expected = [28, 31, 30, 12, 8]; for (var i = 0; i < expected.length; i++) { var x = 0; switch (i) { case 1: x += 1; // fall through case 2: x += 2; // fall through default: x += 16; // fall through case 3: x += 4; // fall through case 4: x += 8; // fall through } console.assert(x === expected[i], 'switch fallthrough ' + i); } }; // Run some tests of switch statements. tests.switchBreak = function() { var expected = [30, 20, 20, 30, 40]; for (var i = 0; i < expected.length; i++) { var x; foo: { switch (i) { case 1: x = 10; // fall through case 2: x = 20; break; default: x = 50; // fall through case 3: x = 30; break foo; case 4: x = 40; } } console.assert(x === expected[i], 'switch ' + i); } }; // Run some tests of evaluation of binary expressions, as defined in // §11.5--11.11 of the ES5.1 spec. tests.binary = function() { var cases = [ // Addition / concatenation: ["1 + 1", 2], ["'1' + 1", '11'], ["1 + '1'", '11'], // Subtraction: ["'1' - 1", 0], // Multiplication: ["'5' * '5'", 25], ["-5 * 0", -0], ["-5 * -0", 0], ["1 * NaN", NaN], ["Infinity * NaN", NaN], ["-Infinity * NaN", NaN], ["Infinity * Infinity", Infinity], ["Infinity * -Infinity", -Infinity], ["-Infinity * -Infinity", Infinity], ["-Infinity * Infinity", -Infinity], // FIXME: add overflow/underflow cases // Division: ["35 / '7'", 5], ["1 / 1", 1], ["1 / -1", -1], ["-1 / -1", 1], ["-1 / 1", -1], ["1 / NaN", NaN], ["NaN / NaN", NaN], ["NaN / 1", NaN], ["Infinity / Infinity", NaN], ["Infinity / -Infinity", NaN], ["-Infinity / -Infinity", NaN], ["-Infinity / Infinity", NaN], ["Infinity / 0", Infinity], ["Infinity / -0", -Infinity], ["-Infinity / -0", Infinity], ["-Infinity / 0", -Infinity], ["Infinity / 1", Infinity], ["Infinity / -1", -Infinity], ["-Infinity / -1", Infinity], ["-Infinity / 1", -Infinity], ["1 / Infinity", 0], ["1 / -Infinity", -0], ["-1 / -Infinity", 0], ["-1 / Infinity", -0], ["0 / 0", NaN], ["0 / -0", NaN], ["-0 / -0", NaN], ["-0 / 0", NaN], ["1 / 0", Infinity], ["1 / -0", -Infinity], ["-1 / -0", Infinity], ["-1 / 0", -Infinity], // FIXME: add overflow/underflow cases // Remainder: ["20 % 5.5", 3.5], ["20 % -5.5", 3.5], ["-20 % -5.5", -3.5], ["-20 % 5.5", -3.5], ["1 % NaN", NaN], ["NaN % NaN", NaN], ["NaN % 1", NaN], ["Infinity % 1", NaN], ["-Infinity % 1", NaN], ["1 % 0", NaN], ["1 % -0", NaN], ["Infinity % 0", NaN], ["Infinity % -0", NaN], ["-Infinity % -0", NaN], ["-Infinity % 0", NaN], ["0 % 1", 0], ["-0 % 1", -0], // FIXME: add overflow/underflow cases // Left shift: ["10 << 2", 40], ["10 << 28", -1610612736], ["10 << 33", 20], ["10 << 34", 40], // Signed right shift: ["10 >> 4", 0], ["10 >> 33", 5], ["10 >> 34", 2], ["-11 >> 1", -6], ["-11 >> 2", -3], // Signed right shift: ["10 >>> 4", 0], ["10 >>> 33", 5], ["10 >>> 34", 2], ["-11 >>> 0", 0xfffffff5], ["-11 >>> 1", 0x7ffffffa], ["-11 >>> 2", 0x3ffffffd], ["4294967338 >>> 0", 42], // Bitwise: ["0x3 | 0x5", 0x7], ["0x3 ^ 0x5", 0x6], ["0x3 & 0x5", 0x1], ["NaN | 0", 0], ["-0 | 0", 0], ["Infinity | 0", 0], ["-Infinity | 0", 0], // Comparisons: // // (This is mainly about making sure that the binary operators are // hooked up to the abstract relational comparison algorithm // correctly; that algorithm is tested separately to make sure // details of comparisons are correct.) ["1 < 2", true], ["2 < 2", false], ["3 < 2", false], ["1 <= 2", true], ["2 <= 2", true], ["3 <= 2", false], ["1 > 2", false], ["2 > 2", false], ["3 > 2", true], ["1 >= 2", false], ["2 >= 2", true], ["3 >= 2", true], // (Ditto for abstract equality comparison algorithm.) ["1 == 1", true], ["2 == 1", false], ["2 == 2", true], ["1 == 2", false], ["1 == '1'", true], ["1 != 1", false], ["2 != 1", true], ["2 != 2", false], ["1 != 2", true], ["1 != '1'", false], // (Ditto for abstract strict equality comparison algorithm.) ["1 === 1", true], ["2 === 1", false], ["2 === 2", true], ["1 === 2", false], ["1 === '1'", false], ["1 !== 1", false], ["2 !== 1", true], ["2 !== 2", false], ["1 !== 2", true], ["1 !== '1'", true], ]; // Object.is is part of ES6, not ES5, so provide a helper function. // Copied from: // developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/is function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } for (var i = 0, tc; (tc = cases[i]); i++) { var actual = eval(tc[0]); var expected = tc[1]; console.assert(is(actual, expected), tc[0] + ' Actual: ' + actual + ' Expected: ' + expected); } }; // Run some tests of the Abstract Relational Comparison Algorithm, as defined // in §11.8.5 of the ES5.1 spec and as embodied by the '<' operator. tests.arca = function() { var cases = [ ['0, NaN', undefined], ['NaN, NaN', undefined], ['NaN, 0', undefined], ['1, 1', false], ['0, -0', false], ['-0, 0', false], ['Infinity, Number.MAX_VALUE', false], ['Number.MAX_VALUE, Infinity', true], ['-Infinity, -Number.MAX_VALUE', true], ['-Number.MAX_VALUE, -Infinity', false], ['1, 2', true], ['2, 1', false], // String comparisons: ['"", ""', false], ['"", " "', true], ['" ", ""', false], ['" ", " "', false], ['"foo", "foobar"', true], ['"foo", "bar"', false], ['"foobar", "foo"', false], ['"10", "9"', true], ['"10", 9', false], // \ufb00 vs. \U0001f019: this test fails if we do simple // lexicographic comparison of UTF-8 or UTF-32. The latter // character is a larger code point and sorts later in UTF8, // but in UTF16 it gets replaced by two surrogates, both of // which are smaller than \uf000. ['"ff", "🀙"', false], // Mixed: ['11, "2"', false], // Numeric ['2, "11"', true], // Numeric ['"11", "2"', true], // String ]; function arca(a, b) { return ((a < b) || (a >= b)) ? (a < b) : undefined; } for (var i = 0, tc; (tc = cases[i]); i++) { console.assert(tc[1] === eval('arca(' + tc[0] + ')'), 'ARCA: ' + tc[0]); } }; // Run some tests of the Abstract Equality Comparison Algorithm and // the Abstract Strict Equality Comparison Algorithm, as defined in // §11.9.3 and §11.9.6 respectively of the ES5.1 spec and as embodied // by the '==' and '===' operators. tests.aeca_aseca = function() { var cases = [ ['false, false', true, true], // Numeric ['false, true', false, false], // Numeric ['true, true', true, true], // Numeric ['true, false', false, false], // Numeric // Numeric comparisons: ['0, NaN', false, false], ['NaN, NaN', false, false], ['NaN, 0', false, false], ['1, 1', true, true], ['0, -0', true, true], ['-0, 0', true, true], ['Infinity, Number.MAX_VALUE', false, false], ['Number.MAX_VALUE, Infinity', false, false], ['Infinity, -Number.MAX_VALUE', false, false], ['-Number.MAX_VALUE, -Infinity', false, false], ['1, 2', false, false], ['2, 1', false, false], // String comparisons: ['"", ""', true, true], ['"", " "', false, false], ['" ", ""', false, false], ['" ", " "', true, true], ['"foo", "foobar"', false, false], ['"foo", "bar"', false, false], ['"foobar", "foo"', false, false], ['"10", "9"', false, false], // Null / undefined: ['undefined, undefined', true, true], ['undefined, null', true, false], ['null, null', true, true], ['null, undefined', true, false], // Objects: ['Object.prototype, Object.prototype', true, true], ['{}, {}', false, false], // Mixed: ['"10", 10', true, false], // Numeric ['10, "10"', true, false], // Numeric ['"10", 9', false, false], // Numeric ['"10", "9"', false, false], // String ['"10", "10"', true, true], // String ['false, 0', true, false], // Numeric ['false, 1', false, false], // Numeric ['true, 1', true, false], // Numeric ['true, 0', false, false], // Numeric ['0, false', true, false], // Numeric ['1, false', false, false], // Numeric ['1, true', true, false], // Numeric ['0, true', false, false], // Numeric ['null, false', false, false], ['null, 0', false, false], ['null, ""', false, false], ['false, null', false, false], ['0, null', false, false], ['"", null', false, false], ['{}, false', false, false], ['{}, 0', false, false], ['{}, ""', false, false], ['{}, null', false, false], ['{}, undefined', false, false], ]; function aeca(a, b) { return a == b; } function aseca(a, b) { return a === b; } for (var i = 0, tc; (tc = cases[i]); i++) { console.assert(tc[1] === eval('aeca(' + tc[0] + ')'), 'AECA: ' + tc[0]); console.assert(tc[2] === eval('aseca(' + tc[0] + ')'), 'ASECA: ' + tc[0]); } }; tests.isFinite = function() { console.assert(!isFinite(Infinity), 'isFinite Infinity'); console.assert(!isFinite(NaN), 'isFinite NaN'); console.assert(!isFinite(-Infinity), 'isFinite -Infinity'); console.assert(isFinite(0), 'isFinite 0'); console.assert(isFinite(2e64), 'isFinite 2e64'); console.assert(isFinite('0'), 'isFinite "0"'); console.assert(isFinite(null), 'isFinite null'); }; tests.isNaN = function() { console.assert(isNaN(NaN), 'isNaN NaN'); console.assert(isNaN(0 / 0), 'isNaN 0 / 0'); console.assert(isNaN('NaN'), 'isNaN "NaN"'); console.assert(isNaN(undefined), 'isNaN undefined'); console.assert(isNaN({}), 'isNaN {}'); console.assert(isNaN('blabla'), 'isNaN "blabla"'); console.assert(!isNaN(true), 'isNaN true'); console.assert(!isNaN(null), 'isNaN null'); console.assert(!isNaN(37), 'isNaN 37'); console.assert(!isNaN('37'), 'isNaN "37"'); console.assert(!isNaN('37.37'), 'isNaN "37.37"'); console.assert(!isNaN(''), 'isNaN ""'); console.assert(!isNaN(' '), 'isNaN " "'); }; tests.basicMath = function() { console.assert(1 + 1 === 2, 'onePlusOne'); console.assert(2 + 2 === 4,'twoPlusTwo'); console.assert(6 * 7 === 42, 'sixTimesSeven'); console.assert((3 + 12 / 4) * (10 - 3) === 42, 'simpleFourFunction'); }; tests.basicVariables = function() { var x = 43; console.assert(x === 43, 'variableDecl'); x = 44; console.assert(x === 44, 'simpleAssignment'); }; tests.ternary = function() { console.assert((true ? 'then' : 'else') === 'then', 'condTrue'); console.assert((false ? 'then' : 'else') === 'else', 'condFalse'); }; tests.ifElse = function() { var ifTrue; if (true) { ifTrue = 'then'; } else { ifTrue = 'else'; } console.assert(ifTrue === 'then', 'ifTrue'); var ifFalse; if (false) { ifFalse = 'then'; } else { ifFalse = 'else'; } console.assert(ifFalse === 'else', 'ifFalse'); }; tests.propertyAssignment = function() { var o = {}; o.foo = 45; console.assert(o.foo == 45, 'propertyAssignment'); }; tests.propertyOnPrimitive = function() { console.assert('foo'.length === 3, 'propertyOnPrimitiveGet'); try { 'foo'.bar = 42; console.assert('foo'.length === 3, 'propertyOnPrimitiveSet'); } catch (e) { console.assert(e.name === 'TypeError', 'propertyOnPrimitiveSetError'); } }; tests.increment = function() { var postincrement = 45; postincrement++; console.assert(postincrement++ === 46, 'postincrement'); var preincrement = 45; ++preincrement; console.assert(++preincrement === 47, 'preincrement'); }; tests.concat = function() { console.assert('foo' + 'bar' === 'foobar', 'concat'); }; tests.plusEquals = function() { var plusequalsLeft = 40; var plusequalsRight = 8; plusequalsLeft += plusequalsRight; console.assert(plusequalsLeft === 48, 'plusequalsLeft'); console.assert(plusequalsRight === 8, 'plusequalsRight'); }; tests.simpleFunctionExpression = function() { var value; var f = function() { value = 49; }; f(); console.assert(value === 49, 'simpleFunctionExpression'); }; tests.funExpWithParameter = function() { var value; var f = function(x) { value = x; }; f(50); console.assert(value === 50, 'fExpWithParameter'); }; tests.functionReturn = function() { console.assert('functionWithReturn', (function(x) { return x; })(51), 51); console.assert('functionWithoutReturn', (function() {})(), undefined); var multipleReturn = function() { try { return true; } finally { return false; } }; console.assert(multipleReturn() === false, 'multipleReturn'); }; tests.throwCatch = function() { var f = function() { throw 26; }; var result; try { f(); } catch (e) { result = e * 2; } console.assert(result === 52, 'throwCatch'); }; tests.throwCatchFalsey = function() { var result; try { throw null; } catch (e) { result = 'caught ' + String(e); } console.assert(result === 'caught null', 'throwCatchFalsey'); }; tests.seqExpr = function() { console.assert((51, 52, 53) === 53, 'seqExpr'); }; tests.labeledStatement = function() { foo: var x = 54; console.assert(x === 54, 'labeledStatement'); }; tests.whileLoop = function() { var a = 0; while (a < 55) { a++; } console.assert(a === 55, 'whileLoop'); }; tests.whileFalse = function() { var a = 56; while (false) { a++; } console.assert(a === 56, 'whileFalse'); }; tests.doWhileFalse = function() { var a = 56; do { a++; } while (false); console.assert(a === 57, 'doWhileFalse'); }; tests.breakDoWhile = function() { var a = 57; do { a++; break; a++; } while (false); console.assert(a === 58, 'breakDoWhile'); }; tests.selfBreak = function() { console.assert(eval('foo: break foo;') === undefined, 'selfBreak'); }; tests.breakWithFinally = function() { var a = 6; foo: { try { a *= 10; break foo; } finally { a--; } } console.assert(a === 59, 'breakWithFinally'); }; tests.continueWithFinally = function() { var a = 59; do { try { continue; } finally { a++; } } while (false); console.assert(a === 60, 'continueWithFinally'); }; tests.breakWithFinallyContinue = function() { var a = 0; while (a++ < 60) { try { break; } finally { continue; } } console.assert(a === 61, 'breakWithFinallyContinue'); }; tests.returnWithFinallyContinue = function() { var f = function() { var i = 0; while (i++ < 61) { try { return 42; } finally { continue; } } return i; }; console.assert(f() === 62, 'returnWithFinallyContinue'); }; tests.or = function() { console.assert((63 || 'foo') === 63, 'orTrue'); console.assert((false || 64) === 64, 'orFalse'); var r = 0; true || (r++); console.assert(r === 0, 'orShortcircuit'); }; tests.and = function() { console.assert((({}) && 65) === 65, 'andTrue'); console.assert((0 && 65) === 0, 'andFalse'); var r = 0; false && (r++); console.assert(r === 0, 'andShortcircuit'); }; tests.forTriangular = function() { var t = 0; for (var i = 0; i < 12; i++) { t += i; } console.assert(t === 66, 'forTriangular'); }; tests.forIn = function() { var x = 0, a = {a: 60, b:3, c:4}; for (var i in a) { x += a[i]; } console.assert(x === 67, 'forIn'); }; tests.forInMemberExp = function() { var x = 1, o = {foo: 'bar'}, a = {a:2, b:2, c:17}; for (o.foo in a) { x *= a[o.foo]; } console.assert(x === 68, 'forInMemberExp'); }; tests.forInMembFunc = function() { var x = 0, o = {}; var f = function() { x += 20; return o; }; var a = {a:2, b:3, c:4}; for (f().foo in a) { x += a[o.foo]; } console.assert(x === 69, 'forInMembFunc'); }; tests.forInNullUndefined = function() { var x = 0, o = {}; var f = function() { x++; return o; }; for (f().foo in null) { x++; } for (f().foo in undefined) { x++; } console.assert(x === 0, 'forInNullUndefined'); }; tests.switchDefaultFirst = function() { var r; switch ('not found') { default: r = 'OK'; break; case 'decoy': r = 'fail'; }; console.assert(r === 'OK', 'switchDefaultFirst'); } tests.switchDefaultOnly = function() { var r; switch ('not found') { default: r = 'OK'; break; }; console.assert(r === 'OK', 'switchDefaultOnly'); } tests.switchEmptyToEnd = function() { switch ('foo') { default: console.assert(false, 'switchEmptyToEnd'); case 'foo': case 'bar': } }; tests.thisInMethod = function() { var o = { f: function() { return this.foo; }, foo: 70 }; console.assert(o.f() === 70, 'thisInMethod'); }; tests.thisInFormerMethod = function() { var o = { f: function() { return this; }}; var g = o.f; console.assert(g() === undefined, 'thisInFormerMethod'); }; tests.testThis = function() { console.assert(this === tests, 'testThis'); console.assert(eval('this') === tests, 'evalThis'); console.assert(tests.testThis.globalThis === undefined, 'globalThis'); }; tests.testThis.globalThis = this; tests.strictBoxedThis = function() { // Run a test to ensure that 'this' is a primitive in methods invoked on // primitives. (This also tests that interpreter is running in strict mode; // in sloppy mode this will be boxed.) try { Object.prototype.foo = function() { return typeof this; }; console.assert('foo'.foo() === 'string', 'strictBoxedThis'); } finally { console.assert(delete Object.prototype.foo, 'strictBoxedThisDelete'); } }; tests.emptyArrayLength = function() { console.assert([].length === 0, 'emptyArrayLength'); }; tests.arrayElidedLength = function() { console.assert([1,,3,,].length === 4, 'arrayElidedLength'); }; tests.arrayElidedNotDefinedNotUndefined = function() { var a = [,undefined,null,0,false]; console.assert(!(0 in a) && (1 in a) && (2 in a) && (3 in a) && (4 in a), 'arrayElidedNotDefinedNotUndefined'); }; tests.arrayLengthPropertyDescriptor = function() { var a = [1, 2, 3]; var pd = Object.getOwnPropertyDescriptor(a, 'length'); console.assert((pd.value === 3), 'arrayLengthPropertyDescriptorValue'); console.assert(pd.writable && !pd.enumerable && !pd.configurable, 'arrayLengthPropertyDescriptor'); }; tests.arrayLength = function() { var a; function checkLen(exp, desc) { if (a.length !== exp) { var msg = 'a.length === ' + a.length + ' (expected: ' + exp + ')'; console.assert(false, desc ? msg + ' ' + desc : msg); } } // Empty array has length == 0 a = []; checkLen(0, 'on empty array'); // Adding non-numeric properties does not increase length: a['zero'] = 0; checkLen(0, 'after setting non-index property on []'); // Adding numeric properties >= length does increase length: for (var i = 0; i < 5; i++) { a[i] = i; checkLen(i + 1, 'after setting a[' + i + ']'); } // .length works propery even for large, sparse arrays, and even // if values are undefined: for (i = 3; i <= 31; i++) { var idx = (1 << i) >>> 0; // >>> 0 converts int32 to uint32 a[idx] = undefined; checkLen(idx + 1, 'after setting a[' + idx + ']'); } // Adding numeric properties < length does not increase length: a[idx - 1] = 'not the largest'; checkLen(idx + 1, 'after setting non-largest element'); // Verify behaviour around largest possible index: a[0xfffffffd] = null; checkLen(0xfffffffe); a[0xfffffffe] = null; checkLen(0xffffffff); a[0xffffffff] = null; // Not an index. checkLen(0xffffffff); // Unchanged. a[0x100000000] = null; // Not an index. checkLen(0xffffffff); // Unchanged. function checkIdx(idx, exp, desc) { var r = a.hasOwnProperty(idx); var msg = 'a.hasOwnProperty(' + idx + ') === ' + r; console.assert(r === exp, desc ? msg + ' ' + desc : msg); } // Setting length to existing value should have no effect: a.length = 0xffffffff; checkIdx(0xfffffffd, true); checkIdx(0xfffffffe, true); checkIdx(0xffffffff, true); checkIdx(0x100000000, true); // Setting length one less than maximum should remove largest // index, but leave properties with keys too large to be indexes: a.length = 0xfffffffe; checkIdx(0xfffffffd, true); checkIdx(0xfffffffe, false); checkIdx(0xffffffff, true); checkIdx(0x100000000, true); // Setting length to zero should remove all index properties: a.length = 0; for (var key in a) { if (!a.hasOwnProperty(key)) { continue; } console.assert(String(key >>> 0) !== key || (key >>> 0) === 0xffffffff, 'Setting a.length = 0 failed to remove property ' + key); } // Make sure we didn't wipe everything! console.assert(Object.getOwnPropertyNames(a).length === 4, 'Setting .length = 0 removed some non-index properties'); }; tests.arrayLengthWithNonWritableProps = function() { var a = []; Object.defineProperty(a, 0, {value: 'hi', writable: false, configurable: true}); a.length = 0; console.assert(a[0] === undefined && a.length === 0, 'arrayLengthWithNonWritableProps'); }; tests.arrayLengthWithNonConfigurableProps = function() { var a = []; Object.defineProperty(a, 0, {value: 'hi', writable: false, configurable: false}); try { a.length = 0; console.assert(false, 'arrayLengthWithNonConfigurableProps'); } catch (e) { console.assert(e.name === 'TypeError', 'arrayLengthWithNonConfigurableProps'); } }; tests.compValEmptyBlock = function() { console.assert(eval('{}') === undefined, 'compValEmptyBlock'); }; tests.unaryVoid = function() { var x = 70; console.assert((undefined === void x++) && x === 71, 'unaryVoid'); }; tests.unaryPlusMinus = function() { console.assert(+'72' === 72, 'unaryPlus'); console.assert(-73 === -73, 'unaryPlus'); }; tests.unaryComplement = function() { console.assert(~0xffffffb5 === 74, 'unaryComplement'); }; tests.unaryNot = function() { console.assert(!false && (!true === false), 'unaryNot'); }; tests.unaryTypeof = function() { console.assert(typeof undefined === 'undefined', 'unaryTypeofUndefined'); console.assert(typeof null === 'object', 'unaryTypeofNull'); console.assert(typeof false === 'boolean', 'unaryTypeofBoolean'); console.assert(typeof 0 === 'number', 'unaryTypeofNumber'); console.assert(typeof '' === 'string', 'unaryTypeofString'); console.assert(typeof {} === 'object', 'unaryTypeofObject'); console.assert(typeof [] === 'object', 'unaryTypeofArray'); console.assert(typeof function() {} === 'function', 'unaryTypeofFunction'); console.assert(typeof undeclaredVar === 'undefined', 'unaryTypeofUndeclared'); }; tests.binaryIn = function() { var o = {foo: 'bar'}; console.assert('foo' in o && !('bar' in o), 'binaryIn'); }; tests.binaryInParent = function() { var p = {foo: 'bar'}; var o = Object.create(p); console.assert('foo' in o && !('bar' in o), 'binaryInParent'); }; tests.binaryInArrayLength = function() { console.assert('length' in [], 'binaryInArrayLength'); }; tests.binaryInStringLength = function() { try { 'length' in ''; console.assert(false, 'binaryInStringLength'); } catch (e) { console.assert(e.name === 'TypeError', 'binaryInStringLengthError'); } }; tests.instanceofBasics = function() { function F(){} var f = new F; console.assert(f instanceof F, 'instanceofBasics1'); console.assert(f instanceof Object, 'instanceofBasics2'); console.assert(!(f.prototype instanceof F), 'instanceofBasics3'); }; tests.instanceofNonObjectLHS = function() { function F() {} F.prototype = null; console.assert(!(42 instanceof F), 'instanceofNonObjectLHS'); }; tests.instanceofNonFunctionRHS = function() { try { ({}) instanceof 0; console.assert(false, 'instanceofNonFunctionRHS'); } catch (e) { console.assert(e.name === 'TypeError', 'instanceofNonFunctionRHSError'); } }; tests.instanceofNonObjectPrototype = function() { function F() {}; F.prototype = 'hello'; try { ({}) instanceof F; console.assert(false, 'instanceofNonObjectPrototype'); } catch (e) { console.assert(e.name === 'TypeError', 'instanceofNonObjectPrototypeError'); } }; tests.nullUndefinedProps = function() { try { undefined.foo; console.assert(false, "undefined.foo didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'undefined.foo wrong error'); } try { var c = 0; undefined.foo = c++; console.assert(false, "undefined.foo = ... didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'undefined.foo = ... wrong error'); console.assert(c === 0, 'undefined.foo = ... evaluated RHS'); } try { null.foo; console.assert(false, "null.foo didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'null.foo wrong error'); } try { c = 0; null.foo = c++; console.assert(false, "null.foo = ... didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'null.foo = ... wrong error'); console.assert(c === 0, 'null.foo = ... evaluated RHS'); } }; tests.deleteProp = function() { var o = {foo: 'bar'}; console.assert(delete o.quux, 'deleteProp1'); console.assert('foo' in o, 'deleteProp2'); console.assert(delete o.foo, 'deleteProp3'); console.assert(!('foo' in o), 'deleteProp4'); console.assert(delete o.foo, 'deleteProp5'); }; tests.deleteNonexistentFromPrimitive = function() { console.assert(delete false.nonexistent, 'deleteNonexistentFromPrimitive'); console.assert(delete (42).toString, 'deleteInheritedFromPrimitive'); }; // This "actually" tries to delete the non-configurable own .length // property from the auto-boxed String instance created by step 4a of // algorithm in §11.4.1 of the ES 5.1 spec. We have to use a string // here, because only String instances have own properties (and yes: // they are all non-configurable, so delete *always* fails). tests.deleteOwnFromPrimitive = function() { try { delete 'hello'.length; console.assert(false, 'deleteOwnFromPrimitive'); } catch (e) { console.assert(e.name === 'TypeError', 'deleteOwnFromPrimitive'); } }; tests.funcDecl = function() { var v; function f() { v = 75; } f(); console.assert(v === 75, 'funcDecl'); }; tests.namedFunctionExpression = function() { var f = function half(x) { if (x < 100) { return x; } return half(x / 2); }; console.assert(f(152) === 76, 'namedFunctionExpression'); f = function foo() {return foo;}; console.assert(f() === f, 'namedFunExpNameBinding'); f = function foo() {}; console.assert(typeof foo === 'undefined', 'namedFunExpBindingNoLeak'); try { (function foo() {foo = null;})(); console.assert(false, "namedFunExpNameBindingImmutable didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'namedFunExpNameBindingImmutable wrong error'); } f = function foo(foo) { foo += 0.1; // Verify mutability. return foo; }; console.assert(f(76) === 76.1, 'nameFunExpNameBindingShadowedByParam'); f = function foo() { var foo; foo = 76.2; // Verify mutability. return foo; }; console.assert(f(76) === 76.2, 'nameFunExpNameBindingShadowedByVar'); }; tests.closureIndependence = function() { function makeAdder(x) { return function(y) { return x + y; }; } var plus3 = makeAdder(3); var plus4 = makeAdder(4); console.assert(plus3(plus4(70)) === 77, 'closureIndependence'); }; tests.internalObjectToString = function() { var o = {}; o[{}] = null; for(var key in o) { } console.assert(key === '[object Object]', 'internalObjectToString'); }; tests.internalFunctionToString = function() { var o = {}, s, f = function(){}; o[f] = null; for(var key in o) { s = key; } console.assert(/^function.*\(.*\).*{[^]*}$/.test(s), 'internalFunctionToString'); }; tests.internalNativeFuncToString = function() { var o = {}, s, f = Object.create; o[f] = null; for(var key in o) { s = key; } console.assert(/^function.*\(.*\).*{[^]*}$/.test(s), 'internalNativeFuncToString'); }; tests.internalArrayToString = function() { var o = {}; o[[1, 2, 3]] = null; for(var key in o) { } console.assert(key === '1,2,3', 'internalArrayToString'); }; tests.internalDateToString = function() { var o = {}; o[new Date(0)] = null; for(var key in o) { } console.assert(key === (new Date(0)).toString(), 'internalDateToString'); }; tests.internalRegExpToString = function() { var o = {}; o[/foo/g] = null; for(var key in o) { } console.assert(key === '/foo/g', 'internalRegExpToString'); }; tests.internalErrorToString = function() { var o = {}; o[Error('oops')] = null; for(var key in o) { } console.assert(key === 'Error: oops', 'internalErrorToString'); }; tests.internalArgumentsToString = function() { var o = {}; (function() { o[arguments] = null; })(); for(var key in o) { } console.assert(key === '[object Arguments]', 'internalArgumentsToString'); }; tests.debugger = function() { console.assert(eval('debugger') === undefined, 'debugger'); }; tests.newExpression = function() { function T(x, y) { this.sum += x + y; }; T.prototype = { sum: 70 }; var t = new T(7, 0.7); console.assert(t.sum === 77.7, 'newExpression'); }; tests.newExpressionReturnObj = function() { function T() { return {}; }; T.prototype = { p: 'the prototype' }; console.assert((new T).p === undefined, 'newExpressionReturnObj'); }; tests.newExpressionReturnObj = function() { function T() { return 0; }; T.prototype = { p: 'the prototype' }; console.assert((new T).p === 'the prototype', 'newExpressionReturnObj'); }; tests.regexpSimple = function() { console.assert(/foo/.test('foobar'), 'regexpSimple'); }; tests.evalSeeEnclosing = function() { var n = 77.77; console.assert(eval('n') === 77.77, 'evalSeeEnclosing'); }; tests.evalIndirectNoSeeEnclosing = function() { var n = 77.77, gEval = eval; try { gEval('n'); console.assert(false, 'evalIndirectNoSeeEnclosing'); } catch (e) { console.assert(e.name === 'ReferenceError', 'evalIndirectNoSeeEnclosing'); } try { (function() { return eval; })()('n'); console.assert(false, 'evalIndirectNoSeeEnclosing2'); } catch (e) { console.assert(e.name === 'ReferenceError', 'evalIndirectNoSeeEnclosing2'); } }; tests.evalIndirectSeeGlobal = function() { var gEval = eval; console.assert(gEval('typeof Array') === 'function', 'evalIndirectSeeGlobal'); }; tests.evalModifyEnclosing = function() { var n = 77.77; eval('n = 77.88'); console.assert(n === 77.88, 'evalModifyEnclosing'); }; tests.evalNoLeakingDecls = function() { eval('var n = 88.88'); console.assert(typeof n === 'undefined', 'evalNoLeakingDecls'); }; tests.evalEmptyBlock = function() { // A bug in eval would cause it to return the value of the // previously-evaluated ExpressionStatement if the eval program did // not contain any ExpressionStatements. 'fail'; console.assert(eval('{}') === undefined, 'evalEmptyBlock'); }; tests.callEvalOrder = function() { var r = ""; function log(x) { r += x; return function () {}; }; (log('f'))(log('a'), log('b'), log('c')); console.assert(r === 'fabc', 'callEvalOrder'); }; tests.callEvalArgsBeforeCallability = function() { try { var invalid = undefined; function t() { throw {name: 'args'}; }; invalid(t()); console.assert(false, 'callEvalArgsBeforeCallability'); } catch(e) { console.assert(e.name === 'args', 'callEvalArgsBeforeCallability'); } }; tests.callNonCallable = function() { function check(v) { try { v(); console.assert(false, 'callNonCallable' + v); } catch(e) { console.assert(e.name === 'TypeError', 'callNonCallable' + v); } } check(undefined); check(null); check(false); check(42); check('hello'); check(Object.create(Function.prototype)); }; /////////////////////////////////////////////////////////////////////////////// // Object and Object.prototype tests.ObjectDefinePropertyNoArgs = function() { try { Object.defineProperty(); console.assert(false, "Object.defineProperty() didn't throw"); } catch (e) { console.assert( e.name === 'TypeError', 'Object.defineProperty() wrong error'); } }; tests.ObjectDefinePropertyNonObject = function() { try { Object.defineProperty('not an object', 'foo', {}); console.assert(false, "Object.defineProperty non-object didn't throw"); } catch (e) { console.assert( e.name === 'TypeError', 'Object.defineProperty non-object wrong error'); } }; tests.ObjectDefinePropertyBadDescriptor = function() { var o = {}; try { Object.defineProperty(o, 'foo', 'not an object'); console.assert(false, "Object.defineProperty bad descriptor didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.defineProperty bad descriptor wrong error'); } }; tests.ObjectDefineProperty = function() { // This also tests iteration over (non-)enumerable properties. var o = { foo: 70 }, r = 0; Object.defineProperty(o, 'bar', { writable: true, enumerable: true, configurable: true, value: 8 }); Object.defineProperty(o, 'baz', { value: 13 }); for (var k in o) { r += o[k]; } console.assert(r === 78, 'Object.defineProperty'); }; tests.ObjectGetPrototypeOfNullUndefined = function() { try { Object.getPrototypeOf(null); console.assert(false, "Object.getPrototypeOf null didn't throw"); } catch (e) { console.assert( e.name === 'TypeError', 'Object.getPrototypeOf null wrong error'); } try { Object.getPrototypeOf(undefined); console.assert(false, "Object.getPrototypeOf undefined didn't throw"); } catch (e) { console.assert( e.name === 'TypeError', 'Object.getPrototypeOf undefined wrong error'); } }; tests.ObjectGetPrototypeOfPrimitives = function() { // This tests for ES6 behaviour. console.assert(Object.getPrototypeOf(true) === Boolean.prototype, 'Object.getPrototypeOf boolean'); console.assert(Object.getPrototypeOf(1337) === Number.prototype, 'Object.getPrototypeOf number'); console.assert(Object.getPrototypeOf('hi') === String.prototype, 'Object.getPrototypeOf string'); }; tests.ObjectCreateNoArgs = function() { try { Object.create(); console.assert(false, "Object.create() didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.create() wrong error'); } }; tests.ObjectCreateNonObject = function() { try { Object.create(42); console.assert(false, "Object.create non-object didn't throw"); } catch (e) { console.assert( e.name === 'TypeError', 'Object.create non-object wrong error'); } }; tests.ObjectCreateNull = function() { var o = Object.create(null); console.assert(Object.getPrototypeOf(o) === null, 'Object.create null'); }; tests.ObjectCreate = function() { var o = Object.create({foo: 79}); delete o.foo; console.assert(o.foo === 79, 'Object.create'); }; tests.ObjectGetOwnPropertyDescriptorNoArgs = function() { try { Object.getOwnPropertyDescriptor(); console.assert(false, "Object.getOwnPropertyDescriptor() didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.getOwnPropertyDescriptor() wrong error'); } }; tests.ObjectGetOwnPropertyDescriptorNonObject = function() { try { Object.getOwnPropertyDescriptor('not an object', 'foo'); console.assert( false, "Object.getOwnPropertyDescriptor non-object didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.getOwnPropertyDescriptor non-object wrong error'); } }; tests.ObjectGetOwnPropertyDescriptorBadKey = function() { var o = {}; console.assert(Object.getOwnPropertyDescriptor(o, 'foo') === undefined, 'Object.getOwnPropertyDescriptor bad key'); }; tests.ObjectGetOwnPropertyDescriptor = function() { var o = {}, r = 0; Object.defineProperty(o, 'foo', { value: 'bar' }); var desc = Object.getOwnPropertyDescriptor(o, 'foo'); console.assert(desc.value === o.foo, 'Object.getOwnPropertyDescriptor value'); console.assert(!desc.writable, 'Object.getOwnPropertyDescriptor writable'); console.assert( !desc.enumerable, 'Object.getOwnPropertyDescriptor enumerable'); console.assert( !desc.configurable, 'Object.getOwnPropertyDescriptor configurable'); }; tests.ObjectGetOwnPropertyNamesNoArgs = function() { try { Object.getOwnPropertyNames(); console.assert(false, "Object.getOwnPropertyNames() didn't throw"); } catch (e) { console.assert( e.name === 'TypeError', 'Object.getOwnPropertyNames() wrong error'); } }; tests.ObjectGetOwnPropertyNamesString = function() { var i, r = 0, names = Object.getOwnPropertyNames('foo'); for (i = 0; i < names.length; i++) { if (names[i] === 'length') { r += 10; } else { r += Number(names[i]) + 1; } } console.assert(r === 16, 'Object.getOwnPropertyNames(string)'); }; tests.ObjectGetOwnPropertyNamesNumber = function() { console.assert( Object.getOwnPropertyNames(42).length === 0, 'Object.getOwnPropertyNames(number)'); }; tests.ObjectGetOwnPropertyNamesBoolean = function() { console.assert(Object.getOwnPropertyNames(true).length === 0, 'Object.getOwnPropertyNames(boolean)'); }; tests.ObjectGetOwnPropertyNamesNull = function() { try { Object.getOwnPropertyNames(null); console.assert(false, "Object.getOwnPropertyNames(null) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.getOwnPropertyNames(null) wrong error'); } }; tests.ObjectGetOwnPropertyNamesUndefined = function() { try { Object.getOwnPropertyNames(undefined); console.assert(false, "Object.getOwnPropertyNames(undefined) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.getOwnPropertyNames(undefined) wrong error'); } }; tests.ObjectGetOwnPropertyNames = function() { var o = Object.create({baz: 999}); o.foo = 42; Object.defineProperty(o, 'bar', { value: 38 }); var keys = Object.getOwnPropertyNames(o); var r = 0; for (var i = 0; i < keys.length; i++) { r += o[keys[i]]; } console.assert(r === 80, 'Object.getOwnPropertyNames'); }; tests.ObjectDefinePropertiesNoArgs = function() { try { Object.defineProperties(); console.assert(false, "Object.defineProperties() didn't throw"); } catch (e) { console.assert( e.name === 'TypeError', 'Object.defineProperties() wrong error'); } }; tests.ObjectDefinePropertiesNonObject = function() { try { Object.defineProperties('not an object', {}); console.assert(false, "Object.defineProperties non-object didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.defineProperties non-object wrong error'); } }; tests.ObjectDefinePropertiesNonObjectProps = function() { try { Object.defineProperties({}, undefined); console.assert( false, "Object.defineProperties non-object props didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.defineProperties non-object props wrong error'); } }; tests.ObjectDefinePropertiesBadDescriptor = function() { var o = {}; try { Object.defineProperties(o, { foo: 'not an object' }); console.assert( false, "Object.defineProperties bad descriptor didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.defineProperties bad descriptor wrong error'); } }; tests.ObjectDefineProperty = function() { var o = { foo: 50 }, r = 0; Object.defineProperty(o, 'bar', { writable: true, enumerable: true, configurable: true, value: 0 }); o.bar = 20; console.assert(o.bar === 20, 'Object.defineProperty +WEC'); Object.defineProperty(o, 'baz', { writable: true, enumerable: true, configurable: false }); console.assert(o.baz === undefined, 'Object.defineProperty +WE-C 1'); Object.defineProperty(o, 'baz', { value: 8 }); console.assert(o.baz === 8, 'Object.defineProperty +WE-C 2'); Object.defineProperty(o, 'quux', { enumerable: false, value: 13 }); console.assert(o.baz === 8, 'Object.defineProperty -WEC'); for (var k in o) { r += o[k]; } console.assert(r === 78, 'Object.defineProperty enumerability'); console.assert(Object.getOwnPropertyNames(o).length === 4, 'Object.defineProperty result .length wrong'); }; tests.ObjectCreateWithProperties = function() { var o = Object.create({ foo: 70 }, { bar: { writable: true, enumerable: true, configurable: true, value: 10 }, baz: { value: 999 }}); var r = 0; for (var k in o) { r += o[k]; } r += Object.getOwnPropertyNames(o).length; console.assert(r === 82, 'Object.create(..., properties)'); }; tests.ObjectPrototypeToString = function() { console.assert(({}).toString() === '[object Object]', 'Object.prototype.toString'); }; tests.ObjectPrototypeHasOwnProperty = function() { var o = Object.create({baz: 999}); o.foo = 42; Object.defineProperty(o, 'bar', { value: 41, enumerable: true }); var r = 0; for (var key in o) { if (!o.hasOwnProperty(key)) continue; r += o[key]; } console.assert(r === 83, 'Object.prototype.hasOwnProperty'); }; tests.ObjectPrototypeIsPrototypeOf = function() { var pfx = 'Object.prototype.isPrototypeOf'; console.assert(!Boolean.prototype.isPrototypeOf(false), 'Boolean.prototype.isPrototypeOf(false)'); console.assert(!Number.prototype.isPrototypeOf(0), 'Number.prototype.isPrototypeOf(0)'); console.assert(!String.prototype.isPrototypeOf(''), "String.prototype.isPrototypeOf('')"); console.assert(!Object.prototype.isPrototypeOf.call(false, false), pfx + '.call(false, false)'); console.assert(!Object.prototype.isPrototypeOf.call(0, 0), pfx + '.call(0, 0)'); console.assert(!Object.prototype.isPrototypeOf.call('', ''), pfx + ".call('', '')"); console.assert(!Object.prototype.isPrototypeOf.call(null, null), pfx + '.call(null, null)'); console.assert(!Object.prototype.isPrototypeOf.call(undefined, undefined), pfx + '.call(undefined, undefined)'); try { Object.prototype.isPrototypeOf.call(null, Object.create(null)); console.assert(false, pfx + ".call(null, ...) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', pfx + '.call(null, ...) wrong error'); } try { Object.prototype.isPrototypeOf.call(undefined, Object.create(undefined)); console.assert(false, pfx + ".call(undefined, ...) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', pfx + '.call(undefined, ...) wrong error'); } var g = {}; var p = Object.create(g); var o = Object.create(p); console.assert(!o.isPrototypeOf(o), pfx + ' self'); console.assert(!Object.prototype.isPrototypeOf(Object.create(null)), pfx + ' unrelated'); console.assert(!o.isPrototypeOf({}), pfx + ' siblings'); console.assert(g.isPrototypeOf(o), pfx + ' grandchild'); console.assert(p.isPrototypeOf(o), pfx + ' child'); console.assert(!o.isPrototypeOf(p), pfx + ' parent'); console.assert(!o.isPrototypeOf(g), pfx + ' grandparent'); }; tests.ObjectPrototypePropertyIsEnumerable = function() { try { Object.prototype.propertyIsEnumerable.call(null, ''); console.assert( false, "Object.prototype.propertyIsEnumerable(null) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.prototype.propertyIsEnumerable(null) wrong error'); } try { Object.prototype.propertyIsEnumerable.call(undefined, ''); console.assert( false, "Object.prototype.propertyIsEnumerable(undefined) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.prototype.propertyIsEnumerable(undefined) wrong error'); } var OppIE = Object.prototype.propertyIsEnumerable; console.assert(OppIE.call('foo', '0'), 'Object.prototype.propertyIsEnumerable primitive true'); console.assert(!OppIE.call('foo', 'length'), 'Object.prototype.propertyIsEnumerable primitive false'); var o = {foo: 'foo'}; Object.defineProperty(o, 'bar', {value: 'bar', enumerable: false}); console.assert(o.propertyIsEnumerable('foo'), 'Object.prototype.propertyIsEnumerable true'); console.assert(!o.propertyIsEnumerable('bar'), 'Object.prototype.propertyIsEnumerable false 1'); console.assert(!o.propertyIsEnumerable('baz'), 'Object.prototype.propertyIsEnumerable false 2'); }; /////////////////////////////////////////////////////////////////////////////// // Function and Function.prototype tests.FunctionConstructor = function() { var f = new Function; console.assert(f() === undefined, 'new Function() returns callable'); console.assert(f.length === 0, 'new Function() .length'); var actual = String(f); var expected = 'function anonymous(\n) {\n\n}'; console.assert(actual === expected, 'new Function() .toString() ' + 'Actual: "' + actual + '" Expected: "' + expected + '"'); f = new Function('return 42;'); console.assert(f() === 42, 'new Function simple returns callable'); console.assert(f.length === 0, 'new Function simple .length'); actual = String(f); expected = 'function anonymous(\n) {\nreturn 42;\n}'; console.assert(actual === expected, 'new Function simple .toString() ' + 'Actual: "' + actual + '" Expected: "' + expected + '"'); f = new Function('a, b', 'c', 'return a + b * c;'); console.assert(f(2, 3, 10) === 32, 'new Function with args returns callable'); console.assert(f.length === 3, 'new Function with args .length'); actual = String(f); expected = 'function anonymous(a, b,c\n) {\nreturn a + b * c;\n}'; console.assert(actual === expected, 'new Function with args .toString() ' + 'Actual: "' + actual + '" Expected: "' + expected + '"'); }; tests.FunctionPrototypeHasNoPrototype = function() { console.assert(Function.prototype.hasOwnProperty('prototype') === false, 'Function.prototype has no .prototype'); }; tests.FunctionPrototypeToStringApplyNonFunctionThrows = function() { try { Function.prototype.toString.apply({}); console.assert( false, "Function.prototype.toString.apply non-function didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Function.prototype.toString().apply non-function wrong error'); } }; tests.FunctionPrototypeApplyNonFuncThrows = function() { try { var o = {}; o.apply = Function.prototype.apply; o.apply(); console.assert(false, "Function.prototype.apply non-function didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Function.prototype.apply non-function wrong error'); } }; tests.FunctionPrototypeApplyThis = function() { var o = {}; function f() { return this; } console.assert(f.apply(o, []) === o, 'Function.prototype.apply this'); }; tests.FunctionPrototypeApplyArgsUndefinedOrNull = function() { var n = 0; function f() { n += arguments.length; } f.apply(undefined, undefined); f.apply(undefined, null); console.assert(n === 0, 'Function.prototype.apply(undefined) or null'); }; tests.FunctionPrototypeApplyArgsNonObject = function() { try { (function() {}).apply(undefined, 'not an object'); console.assert( false, "Function.prototype.apply(..., non-object) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Function.prototype.apply(...., non-object) wrong error'); } }; tests.FunctionPrototypeApplyArgsSparse = function() { var f = function(a, b, c) { if (!(1 in arguments)) { throw Error("Argument 1 missing"); } return a + c; }; console.assert(f.apply(undefined, [1, , 3]) === 4, 'Function.prototype.apply(..., sparse)'); }; tests.FunctionPrototypeApplyArgsArraylike = function() { var n = (function(a, b, c) { return a + b + c; }).apply(undefined, {0: 1, 1: 2, 2: 3, length: 3}); console.assert(n === 6, 'Function.prototype.apply(..., array-like)'); }; tests.FunctionPrototypeApplyArgsNonArraylike = function() { console.assert(isNaN((function(a, b, c) { return a + b + c; }).apply(undefined, {0: 1, 1: 2, 2: 4})), 'Function.prototype.apply(..., non-array-like)'); }; tests.FunctionPrototypeCallNonFuncThrows = function() { try { var o = {}; o.call = Function.prototype.call; o.call(); console.assert(false, "Function.prototype.call non-func didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Function.prototype.call non-func wrong error'); } }; tests.FunctionPrototypeCallThis = function() { var o = {}; function f() { return this; } console.assert(f.call(o) === o, 'Function.prototype.call this'); }; tests.FunctionPrototypeCallNoArgs = function() { function f() { return arguments.length; } console.assert(f.call(undefined) === 0, 'Function.prototype.call no args'); }; tests.FunctionPrototypeCall = function() { var f = function(a, b, c) { if (!(1 in arguments)) { throw Error("Argument 1 missing"); } return a + c; }; console.assert(f.call(undefined, 1, 2, 3) === 4, 'Function.prototype.call'); }; tests.FunctionPrototypeBindNonFuncThrows = function() { try { var o = {}; o.bind = Function.prototype.bind; o.bind(); console.assert(false, "Function.prototype.bind non-func didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Function.prototype.bind non-func wrong error'); } }; tests.FunctionPrototypeBindThis = function() { var o = {}; function f() { return this; } console.assert(f.bind(o)() === o, 'Function.prototype.bind this'); }; tests.FunctionPrototypeBindNoArgs = function() { function f() { return arguments.length; } console.assert(f.bind(undefined)() === 0, 'Function.prototype.bind no args'); }; tests.FunctionPrototypeBind = function() { var d = 4; var f = function(a, b, c) { return a + b + c + d; }; console.assert(f.bind(undefined, 1).bind(undefined, 2)(3) === 10, 'Function.prototype.bind'); }; tests.FunctionPrototypeBindCallBF = function() { var constructed; function Foo() {constructed = (this instanceof Foo)} var f = Foo.bind(); f(); console.assert(constructed === false, 'Function.prototype.bind: calling bound function calls target'); }; tests.FunctionPrototypeBindConstructBF = function() { var constructed; function Foo() {constructed = (this instanceof Foo)} var f = Foo.bind(); new f; console.assert(constructed === true, 'Function.prototype.bind: constructing bound function constructs target'); }; tests.FunctionPrototypeCallBindConstructBF = function() { var invoked; function Foo() {invoked = true;} var f = Foo.call.bind(Foo); try { new f; console.assert(false, "Calling bound call function didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Calling bound call function threw wrong error'); } console.assert(!invoked, 'Calling bound call function invoked call target'); }; /////////////////////////////////////////////////////////////////////////////// // Array and Array.prototype tests.ArrayNoArgs = function() { var a = new Array; console.assert(Array.isArray(a), 'new Array() returns array'); console.assert(a.length === 0, '(new Array().length'); }; tests.ArrayNumericArg = function() { var a = new Array(42); console.assert(Array.isArray(a), 'new Array(number) returns array'); console.assert(!(0 in a), 'new Array(number) has no first item'); console.assert(!(41 in a), 'new Array(number) has no last item'); console.assert(a.length === 42, 'new Array(number).length'); }; tests.ArrayNonNumericArg = function() { var a = new Array('foo'); console.assert(Array.isArray(a), 'new Array(non-number) returns array'); console.assert(a.length === 1, 'new Array(non-number).length'); console.assert(a[0] ==='foo', 'new Array(non-number)[0]'); }; tests.ArrayMultipleArgs = function() { var a = new Array(1, 2, 3); console.assert(Array.isArray(a), 'new Array(multiple...) return array'); console.assert(a.length === 3, 'new Array(multiple...).ength'); console.assert(String(a) ==='1,2,3', 'new Array(multiple...).toString()'); }; tests.ArrayIsArrayArrayPrototype = function() { console.assert( Array.isArray(Array.prototype), 'Array.isArray Array.prototype'); }; tests.ArrayIsArrayArrayInstance = function() { console.assert(Array.isArray(new Array), 'Array.isArray Array instance'); }; tests.ArrayIsArrayArrayLiteral = function() { console.assert(Array.isArray([]), 'Array.isArray Array literal'); }; tests.ArrayIsArrayArrayLike = function() { console.assert(!Array.isArray({0: 'foo', 1: 'bar', length: 2}), 'Array.isArray(array-like)'); }; tests.ArrayPrototypeConcat = function() { var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var c = a.concat(); console.assert(a.length === 6 && c.length === 6 && c !== a && String(c) === String(a), 'Array.prototype.concat()'); var o = {0: 'quux', 1: 'quuux', length: 2}; c = [].concat(['foo', 'bar'], 'baz', undefined, o); console.assert(c.length === 5 && '3' in c && c[3] === undefined && String(c) === 'foo,bar,baz,,[object Object]', 'Array.prototype.concat(...)'); o = {0: 'foo', 1: 'bar', length: 2}; c = Array.prototype.concat.call(o, 'baz', [, 'quux', 'quuux']); console.assert(c.length === 5 && String(c) === '[object Object],baz,,quux,quuux', 'Array.prototype.concat.call(object, ...)'); }; tests.ArrayPrototypeIndexOf = function() { console.assert([1, 2, 3, 2, 1].indexOf(2) === 1, 'Array.prototype.indexOf'); console.assert([1, 2, 3, 2, 1].indexOf(4) === -1, 'Array.prototype.indexOf not found'); console.assert([1, 2, 3, 2, 1].indexOf(2, 2) === 3, 'Array.prototype.indexOf(..., +)'); console.assert([1, 2, 3, 2, 1].indexOf(1, -3) === 4, 'Array.prototype.indexOf(..., -)'); console.assert(['x', NaN, 'y'].indexOf(NaN) === -1, 'Array.prototype.indexOf NaN'); var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5}; console.assert(Array.prototype.indexOf.call(o, 2) === 1, 'Array.prototype.indexOf.call(array-like, ...)'); }; tests.ArrayPrototypeJoin = function() { console.assert([1, 2, 3].join('-') === '1-2-3', 'Array.prototype.join'); }; tests.ArrayPrototypeLastIndexOf = function() { console.assert([1, 2, 3, 2, 1].lastIndexOf(2) === 3, 'Array.prototype.lastIndexOf'); console.assert([1, 2, 3, 2, 1].lastIndexOf(4) === -1, 'Array.prototype.lastIndexOf not found'); console.assert([1, 2, 3, 2, 1].lastIndexOf(2, 2) === 1, 'Array.prototype.lastIndexOf(..., +)'); console.assert([1, 2, 3, 2, 1].lastIndexOf(1, -3) === 0, 'Array.prototype.lastIndexOf(..., -)'); var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5}; console.assert(Array.prototype.lastIndexOf.call(o, 2) === 3, 'Array.prototype.lastIndexOf.call(array-like, ...)'); }; tests.ArrayPrototypeJoinCycleDetection = function() { var a = [1, , 3]; a[1] = a; a.join('-'); // Didn't crash! console.assert(true, 'Array.prototype.join cycle detection'); }; tests.ArrayPrototypePop = function() { var a = ['foo', 'bar', 'baz']; var r = a.pop(); console.assert(a.length === 2 && r === 'baz', 'Array.prototype.pop'); a = []; r = a.pop(); console.assert( a.length === 0 && r === undefined, 'Array.prototype.pop empty array'); var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3}; r = Array.prototype.pop.apply(o); console.assert( o.length === 2 && r === 'baz', 'Array.prototype.pop.apply(array-like)'); o = {length: 0}; r = Array.prototype.pop.apply(o); console.assert(o.length === 0 && r === undefined, 'Array.prototype.pop.apply(empty array-like)'); o = {5000000000000000: 'foo', 5000000000000001: 'quux', length: 5000000000000002}; r = Array.prototype.pop.apply(o); console.assert(o.length === 5000000000000001 && o[5000000000000000] === 'foo', 'Array.prototype.pop.apply(huge array-like)'); }; tests.ArrayPrototypePush = function() { var a = []; console.assert(a.push('foo') === 1 && a.push('bar') === 2 && a.length === 2 && a[0] === 'foo' && a[1] === 'bar', 'Array.prototype.push'); var o = {length: 0}; console.assert(Array.prototype.push.call(o, 'foo') === 1 && Array.prototype.push.call(o, 'bar') === 2 && o.length === 2 && o[0] === 'foo' && o[1] === 'bar', 'Array.prototype.push.call(array-like, ...)'); var o = {length: 5000000000000000}; console.assert(Array.prototype.push.call(o, 'foo') === 5000000000000001 && Array.prototype.push.call(o, 'bar') === 5000000000000002 && o[5000000000000000] === 'foo' && o[5000000000000001] === 'bar' && o.length === 5000000000000002, 'Array.prototype.push.call(huge array-like, ...)'); }; tests.ArrayPrototypeReverse = function () { var a = [1, 2, 3]; console.assert(a.reverse() === a && a.length === 3 && String(a) === '3,2,1', 'Array.prototype.reverse odd-length'); a = [1, 2, , 4]; console.assert(a.reverse() === a && a.length === 4 && String(a) === '4,,2,1', 'Array.prototype.reverse even-length'); a = []; console.assert(a.reverse() === a && a.length === 0, 'Array.prototype.reverse empty'); var o = {0: 1, 1: 2, 2: 3, length: 3}; console.assert(Array.prototype.reverse.call(o) === o && o.length === 3 && Array.prototype.slice.apply(o).toString() === '3,2,1', 'Array.prototype.reverse.call(odd-length array-like)'); o = {0: 1, 1: 2, 3: 4, length: 4}; console.assert(Array.prototype.reverse.call(o) === o && o.length === 4 && Array.prototype.slice.apply(o).toString() === '4,,2,1', 'Array.prototype.reverse.call(even-length array-like)'); o = {length: 0}; console.assert(Array.prototype.reverse.call(o) === o && o.length === 0, 'Array.prototype.reverse.call(empty array-like)'); }; tests.ArrayPrototypeShift = function() { var a = ['foo', 'bar', 'baz']; var r = a.shift(); console.assert(a.length === 2 && a[0] === 'bar' && a[1] === 'baz' && r === 'foo', 'Array.prototype.shift'); a = []; r = a.shift(); console.assert( a.length === 0 && r === undefined, 'Array.prototype.shift empty array'); var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3}; r = Array.prototype.shift.apply(o); console.assert(o.length === 2 && o[0] === 'bar' && o[1] === 'baz' && r === 'foo', 'Array.prototype.shift.apply(array-like)'); o = {length: 0}; r = Array.prototype.shift.apply(o); console.assert(o.length === 0 && r === undefined, 'Array.prototype.shift.apply(empty array-like)'); // SKIP until more efficient shift implementation available. console.log('SKIP:\tArray.prototype.shift.apply(huge array-like)'); // o = {5000000000000000: 'foo', // 5000000000000001: 'quux', // length: 5000000000000002}; // r = Array.prototype.shift.apply(o); // console.assert(o.length === 5000000000000001 && o[5000000000000000] === 'quux', // 'Array.prototype.shift.apply(huge array-like)'); }; tests.ArrayPrototypeSlice = function() { var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.slice(); console.assert(a.length === 6 && s.length === 6 && String(s) === String(a), 'Array.prototype.slice()'); s = a.slice(-2); console.assert(a.length === 6 && s.length === 2 && String(s) === 'quux,quuux', 'Array.prototype.slice(-)'); s = a.slice(1, 4); console.assert(a.length === 6 && s.length === 3 && !('2' in s) && String(s) === 'bar,baz,', 'Array.prototype.slice(+, +)'); s = a.slice(1, -2); console.assert(a.length === 6 && s.length === 3 && !('2' in s) && String(s) === 'bar,baz,', 'Array.prototype.slice(+, +)'); var o = {0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6}; s = Array.prototype.slice.call(o, 1, -2); console.assert(o.length === 6 && s.length === 3 && !('2' in s) && String(s) === 'bar,baz,', 'Array.prototype.slice.call(array-like, -, +)'); o = { 5000000000000000: 'foo', 5000000000000001: 'bar', 5000000000000002: 'baz', 5000000000000004: 'quux', 5000000000000005: 'quuux', length: 5000000000000006 }; s = Array.prototype.slice.call(o, -5, -2); console.assert(o.length === 5000000000000006 && s.length === 3 && !('2' in s) && String(s) === 'bar,baz,', 'Array.prototype.slice.call(huge array-like, -, -)'); }; tests.ArrayPrototypeSort = function() { console.assert([5, 2, 3, 1, 4].sort().join() === '1,2,3,4,5', 'Array.prototype.sort()'); // TODO(cpcallen): console.assert(['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1].sort() .map(String).join() === '1,10,5,NaN,a,aa,null,z,undefined,,', 'Array.prototype.sort() compaction'); console.assert([99, 9, 10, 11, 1, 0, 5].sort(function(a, b) {return a - b;}) .join() === '0,1,5,9,10,11,99', 'Array.prototype.sort(comparefn)'); // TODO(cpcallen): console.assert(['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1].sort( function(a, b) { // Try to put undefineds first - should not succeed. if (a === undefined) return b === undefined ? 0 : -1; if (b === undefined) return 1; // Reverse order of ususal sort. a = String(a); b = String(b); if (a > b) return -1; if (b > a) return 1; return 0; }).map(String).join() === 'z,null,aa,a,NaN,5,10,1,undefined,,', 'Array.prototype.sort(comparefn) compaction'); }; tests.ArrayPrototypeSplice = function() { var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.splice(); console.assert(a.length === 6 && String(a) === 'foo,bar,baz,,quux,quuux' && s.length === 0 && String(s) === '', 'Array.prototype.splice()'); a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; s = a.splice(-2); console.assert(a.length === 4 && String(a) === 'foo,bar,baz,' && s.length === 2 && String(s) === 'quux,quuux', 'Array.prototype.splice(-)'); a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; s = a.splice(1, 3, 'bletch'); console.assert(a.length === 4 && String(a) === 'foo,bletch,quux,quuux' && s.length === 3 && String(s) === 'bar,baz,', 'Array.prototype.splice(+, +, ...)'); var o = {0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6}; s = Array.prototype.splice.call(o, 0, 100, 'bletch'); console.assert(!Array.isArray(o) && o.length === 1 && Object.keys(o).length === 2 && o[0] === 'bletch' && s.length === 6 && !('3' in s) && String(s) === 'foo,bar,baz,,quux,quuux', 'Array.prototype.splice.call(array-like, 0, large, ...)'); o = { 5000000000000000: 'foo', 5000000000000001: 'bar', 5000000000000002: 'baz', 5000000000000004: 'quux', 5000000000000005: 'quuux', length: 5000000000000006 }; s = Array.prototype.splice.call(o, -2, -999, 'bletch', 'qux'); console.assert(!Array.isArray(o) && o.length === 5000000000000008 && o[5000000000000004] === 'bletch' && o[5000000000000005] === 'qux' && o[5000000000000006] === 'quux' && o[5000000000000007] === 'quuux' && Array.isArray(s) && s.length === 0, 'Array.prototype.splice.call(huge array-like, -, -)'); }; tests.ArrayPrototypeToStringCycleDetection = function() { var a = [1, , 3]; a[1] = a; a.toString(); // Didn't crash! console.assert(true, 'Array.prototype.toString cycle detection'); }; tests.ArrayPrototypeUnshift = function() { var a = []; console.assert(a.unshift('foo') === 1 && a.unshift('bar') === 2 && a.length === 2 && a[0] === 'bar' && a[1] === 'foo', 'Array.prototype.unshift'); var o = {length: 0}; console.assert(Array.prototype.unshift.call(o, 'foo') === 1 && Array.prototype.unshift.call(o, 'bar') === 2 && o.length === 2 && o[0] === 'bar' && o[1] === 'foo', 'Array.prototype.unshift.call(array-like, ...)'); // SKIP until more efficient unshift implementation available. console.log('SKIP:\tArray.prototype.unshift.apply(huge array-like, ...)'); // var o = {length: 5000000000000000}; // console.assert(Array.prototype.unshift.call(o, 'foo') === 5000000000000001 && // Array.prototype.unshift.call(o, 'bar') === 5000000000000002 && // o[5000000000000000] === 'foo' && o[5000000000000001] === 'bar' && // o.length === 5000000000000002, // 'Array.prototype.unshift.call(huge array-like, ...)'); }; tests.ArrayLegalIndexLength = function() { var cases = [ // [value, asIndex, asLength] [false, 0, 0], [true, 0, 1], [0, 1, 0], [1, 2, 1], [0xfffffffe, 0xffffffff, 0xfffffffe], [0xffffffff, 0, 0xffffffff], [0x100000000, 0, NaN], [4.5, 0, NaN], [-1, 0, NaN], ['0', 1, 0], ['1', 2, 1], ['0xfffffffe', 0, 0xfffffffe], ['0xffffffff', 0, 0xffffffff], ['0x100000000', 0, NaN], ['4294967294', 4294967295, 0xfffffffe], ['4294967295', 0, 0xffffffff], ['4294967296', 0, NaN], ['4.5', 0, NaN], ['-1', 0, NaN], ['hello', 0, NaN], [null, 0, 0], // wat [undefined, 0, NaN], [[], 0, 0], // wat! [{}, 0, NaN], ]; for (var i = 0, tc; (tc = cases[i]); i++) { var a = []; a[tc[0]] = true; console.assert(a.length === tc[1], 'Array legal index ' + JSON.stringify(tc[0])); var a = []; try { a.length = tc[0]; if (isNaN(tc[2])) { console.assert(false, "Array illegal .length didn't throw " + JSON.stringify(tc[0])); } } catch (e) { console.assert(e.name === 'RangeError', 'Array illegal .length wrong error ' + JSON.stringify(tc[0])); } } }; /////////////////////////////////////////////////////////////////////////////// // Boolean and Boolean.prototype tests.Boolean = function() { console.assert(Boolean(undefined) === false, 'Boolean undefined'); console.assert(Boolean(null) === false, 'Boolean null'); console.assert(Boolean(false) === false, 'Boolean false'); console.assert(Boolean(true) === true, 'Boolean true'); console.assert(Boolean(NaN) === false, 'Boolean NaN'); console.assert(Boolean(0) === false, 'Boolean 0'); console.assert(Boolean(1) === true, 'Boolean 1'); console.assert(Boolean('') === false, 'Boolean empty string'); console.assert(Boolean('foo') === true, 'Boolean non-empty string'); console.assert(Boolean({}) === true, 'Boolean object'); console.assert(Boolean([]) === true, 'Boolean array'); console.assert(Boolean(function() {}) === true, 'Boolean function'); }; tests.BooleanPrototypeToString = function () { console.assert(Boolean.prototype.toString() === 'false', 'Boolean.prototype.toString()'); console.assert(Boolean.prototype.toString.call(true) === 'true', 'Boolean.prototype.toString.call(true)'); console.assert(Boolean.prototype.toString.call(false) === 'false', 'Boolean.prototype.toString.call(false)'); try { Boolean.prototype.toString.call({}); console.assert(false, "Boolean.prototype.toString.call({}) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Boolean.prototype.toString.call({}) wrong error'); } }; tests.BooleanPrototypeValueOf = function () { console.assert(Boolean.prototype.valueOf() === false, 'Boolean.prototype.valueOf()'); console.assert(Boolean.prototype.valueOf.call(true) === true, 'Boolean.prototype.valueOf.call(true)'); console.assert(Boolean.prototype.valueOf.call(false) === false, 'Boolean.prototype.valueOf.call(false)'); try { Boolean.prototype.valueOf.call({}); console.assert(false, "Boolean.prototype.valueOf.call({}) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Boolean.prototype.valueOf.call({}) wrong error'); } }; /////////////////////////////////////////////////////////////////////////////// // Number and Number.prototype tests.Number = function() { console.assert(Number() === 0, 'Number()'); console.assert(isNaN(Number(undefined)), 'Number undefined'); console.assert(Number(null) === 0, 'Number null'); console.assert(Number(true) === 1, 'Number true'); console.assert(Number(false) === 0, 'Number false'); console.assert(Number('42') === 42, "Number '42'"); console.assert(isNaN(Number('Hello')), 'Number non-empty string'); console.assert(Number('') === 0, 'Number empty string'); console.assert(Number(3.1) === 3.1, 'Number number'); console.assert(isNaN(Number({})), 'Number object'); console.assert(Number([]) === 0, 'Number []'); console.assert(Number([42]) === 42, 'Number [42]'); console.assert(isNaN(Number([1,2,3])), 'Number [1,2,3]'); console.assert(isNaN(Number(function() {})), 'Number function'); console.assert(isNaN(Number.NaN), 'Number NaN'); console.assert(!isFinite(Number.POSITIVE_INFINITY), 'Number +Infinity'); console.assert(!isFinite(Number.NEGATIVE_INFINITY), 'Number -Infinity'); console.assert(Number.POSITIVE_INFINITY === -Number.NEGATIVE_INFINITY, 'Number infinities'); }; tests.NumberPrototypeToString = function () { console.assert(Number.prototype.toString() === '0', 'Number.prototype.toString()'); console.assert(Number.prototype.toString.call(84) === '84', 'Number.prototype.toString.call(85)'); try { Number.prototype.toString.call({}); console.assert(false, "Number.prototype.toString.call({}) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Number.prototype.toString.call({}) wrong error'); } }; // Run some tests of Number.toString(radix) with various different // radix arguments. tests.NumberPrototypeToStringRadix = function() { var cases = [ [42, , '42'], [42, 16, '2a'], // Old versions of Node incorrectly reports '-132.144444'. [-42.4, 5, '-132.2'], [42, '2', '101010'], [-3.14, , '-3.14'], [999999999999999999999999999, undefined, '1e+27'], [NaN, undefined, 'NaN'], [Infinity, , 'Infinity'], [-Infinity, , '-Infinity'], ]; for (var i = 0, tc; (tc = cases[i]); i++) { console.assert(Number.prototype.toString.call(tc[0], tc[1]) === tc[2], 'Number.prototype.toString.call(' + tc[0] + ', ' + tc[1] + ')'); } }; tests.NumberPrototypeValueOf = function () { console.assert(Number.prototype.valueOf() === 0, 'Number.prototype.valueOf()'); console.assert(Number.prototype.valueOf.call(85) === 85, 'Number.prototype.valueOf.call(85)'); try { Number.prototype.valueOf.call({}); console.assert(false, "Number.prototype.valueOf.call({}) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Number.prototype.valueOf.call({}) wrong error'); } }; /////////////////////////////////////////////////////////////////////////////// // String and String.prototype tests.String = function() { console.assert(String() === '', 'String()'); console.assert(String(undefined) === 'undefined', 'String undefined'); console.assert(String(null) === 'null', 'String null'); console.assert(String(true) === 'true', 'String true'); console.assert(String(false) === 'false', 'String false'); console.assert(String(0) === '0', 'String 0'); console.assert(String(-0) === '0', 'String -0'); console.assert(String(Infinity) === 'Infinity', 'String +Infinity'); console.assert(String(-Infinity) === '-Infinity', 'String -Infinity'); console.assert(String(NaN) === 'NaN', 'String NaN'); console.assert(String({}) === '[object Object]', 'String object'); console.assert(String([1, 2, 3,,5]) === '1,2,3,,5', 'String array'); }; tests.StringPrototypeLength = function() { console.assert(String.prototype.length === 0, 'String.prototype.length'); }; tests.StringPrototypeReplaceStringString = function() { console.assert('xxxx'.replace('xx', 'y') === 'yxx', 'String.prototype.replace(string, string)'); }; tests.StringPrototypeReplaceRegExpString = function() { console.assert('xxxx'.replace(/(X)\1/ig, 'y') === 'yy', 'String.prototype.replace(regexp, string)'); }; tests.StringPrototypeReplaceStringFunction = function() { var str = 'xxxx'.replace('xx', function () { return '[' + Array.prototype.join.apply(arguments) + ']'; }); console.assert(str === '[xx,0,xxxx]xx', 'String.prototype.replace(string, function)'); }; tests.StringPrototypeReplaceRegExpFunction = function() { var str = 'xxxx'.replace(/(X)\1/ig, function () { return '[' + Array.prototype.join.apply(arguments) + ']'; }); console.assert(str === '[xx,x,0,xxxx][xx,x,2,xxxx]', 'String.prototype.replace(regexp, function)'); }; tests.StringPrototypeSearch = function() { console.assert('hello'.search('H') === -1, 'String.prototype.search(string) not found'); console.assert('hello'.search('ll') === 2, 'String.prototype.search(string) found'); console.assert('hello'.search(/H/) === -1, 'String.prototype.search(regexp) not found'); console.assert('hello'.search(/(.)\1/) === 2, 'String.prototype.search(regexp) found'); }; tests.StringPrototypeToString = function () { console.assert(String.prototype.toString() === '', 'String.prototype.toString()'); console.assert(String.prototype.toString.call('a string') === 'a string', "String.prototype.toString.call('a string')"); try { String.prototype.toString.call({}); console.assert(false, "String.prototype.toString.call({}) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'String.prototype.toString.call({}) wrong error'); } }; tests.StringPrototypeValueOf = function () { console.assert(String.prototype.valueOf() === '', 'String.prototype.valueOf()'); console.assert(String.prototype.valueOf.call('a string') === 'a string', "String.prototype.valueOf.call('a string')"); try { String.prototype.valueOf.call({}); console.assert(false, "String.prototype.valueOf.call({}) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'String.prototype.valueOf.call({}) wrong error'); } }; /////////////////////////////////////////////////////////////////////////////// // RegExp tests.RegExpPrototypeTestApplyNonRegExpThrows = function() { try { /foo/.test.apply({}, ['foo']); console.assert( false, "RegExp.prototype.test.apply(non-regexp) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'RegExp.prototype.test.apply(non-regexp) wrong error'); } }; /////////////////////////////////////////////////////////////////////////////// // JSON tests.JsonStringify = function () { var obj = {string: 'foo', number: 42, true: true, false: false, null: null, object: { obj: {}, arr: [] }, array: [{}, []] }; var str = '{"string":"foo","number":42,"true":true,"false":false,' + '"null":null,"object":{"obj":{},"arr":[]},"array":[{},[]]}'; console.assert(JSON.stringify(obj) === str, 'JSON.stringify basic'); console.assert(JSON.stringify(function(){}) === undefined, 'JSON.stringify(function(){})'); console.assert(JSON.stringify([function(){}]) === '[null]', 'JSON.stringify([function(){}])'); console.assert(JSON.stringify({f: function(){}}) === '{}', 'JSON.stringify({f: function(){}})'); str = '{"string":"foo","number":42}'; console.assert(JSON.stringify(obj, ['string', 'number']) === str, 'JSON.stringify filter'); str = '{\n "string": "foo",\n "number": 42\n}'; console.assert(JSON.stringify(obj, ['string', 'number'], 2) === str, 'JSON.stringify pretty number'); str = '{\n--"string": "foo",\n--"number": 42\n}'; console.assert(JSON.stringify(obj, ['string', 'number'], '--') === str, 'JSON.stringify pretty string'); obj = {e: 'enumerable', ne: 'nonenumerable'}; Object.defineProperty(obj, 'ne', {enumerable: false}); console.assert(JSON.stringify(obj) === '{"e":"enumerable"}', 'JSON.stringify nonenumerable'); console.assert(JSON.stringify(Object.create({foo: 'bar'})) === '{}', 'JSON.stringify inherited'); obj = {}; obj.circular = obj; try { JSON.stringify(obj); console.assert(false, "JSON.stringify didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'JSON.stringify wrong error'); } }; /////////////////////////////////////////////////////////////////////////////// // Other built-in functions tests.decodeUriThrows = function() { try { decodeURI('%xy'); console.assert(false, "decodeURI(invalid-URI) didn't throw"); } catch (e) { console.assert(e.name === 'URIError', 'decodeURI(invalid-URI) wrong error'); } }; /////////////////////////////////////////////////////////////////////////////// // Other tests tests.newHack = function() { console.assert( (new 'Array.prototype.push') === Array.prototype.push, 'new hack'); }; tests.newHackUnknown = function() { try { new 'nonexistent-builtin-name'; console.assert(false, "new hack with unknown built-in didn't throw"); } catch (e) { console.assert(e.name === 'ReferenceError', 'new hack with unknown built-in wrong error'); } }; tests.newHacknNonLiteral = function() { try { var builtin = 'Object.prototype'; new builtin; console.assert(false, "new hack with non-literal didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'new hack with non-literal wrong error'); } }; tests.es6CausesSyntaxErrors = function() { var tests = [ // Class statements & expressions 'class Foo{};', 'false && class Foo{};', // Arrow functions. 'false && [].map((item) => String(item));', // For-of statement. 'for (var x of [1, 2, 3]) {};', // Let & const. 'let x;', 'const x;', ]; for (var i = 0; i < tests.length; i++) { var src = tests[i]; try { eval(tests[i]); console.assert(false, "es5 didn't throw for: " + src); } catch (e) { console.assert(e.name === 'SyntaxError', 'es5 threw wrong error for: ' + src); } } }; tests.strictModeSyntaxErrors = function() { var tests = [ // With statement. 'var o = { foo: 42 }; var f = function() { with (o) { foo; }};', // Binding eval in global scope, or arguments in a function. 'var eval = "rebinding eval?!?";', '(function() { arguments = undefined; });', // Duplicate argument names. '(function(a, a) {});', // Octal numeric literals. '0777;', // Delete of unqualified or undeclared identifier. 'var foo; delete foo;', 'delete foo;', ]; for (var i = 0; i < tests.length; i++) { var src = tests[i]; try { eval(tests[i]); console.assert(false, "strict mode didn't throw for: " + src); } catch (e) { console.assert(e.name === 'SyntaxError', 'strict mode wrong error for: ' + src); } } }; ================================================ FILE: server/tests/db/test_01_es6.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test the ES6 functions of the server. * @author fraser@google.com (Neil Fraser) */ // Test automatic setting of function .name properties. tests.functionNameSetting = function() { var myAssignedFunc; myAssignedFunc = function() {}; console.assert(myAssignedFunc.name === 'myAssignedFunc', 'Assignment expression sets anonymous function name'); var o = {myPropFunc: function() {}}; console.assert(o.myPropFunc.name === 'myPropFunc', 'Object expression sets anonymous function name'); var myVarDeclFunc = function() {}; console.assert(myVarDeclFunc.name === 'myVarDeclFunc', 'Variable declaration sets anonymous function name'); }; // Run some tests of the various constructors and their associated // literals and prototype objects. tests.builtinClassesES6 = function() { var classes = [ { constructor: WeakMap, classStr: '[object WeakMap]', prototypeClass: '[object Object]', functionNotConstructor: true // WeakMap() can't be called without new. }, ]; for (var i = 0, tc; (tc = classes[i]); i++) { var c = tc.constructor; var prototypeType = (tc.prototypeType || 'object'); // Check constructor is a function: console.assert(typeof c === 'function', c + ' isFunction'); // Check constructor's proto is Function.prototype console.assert(Object.getPrototypeOf(c) === Function.prototype, c + ' protoIsFunctionPrototype'); // Check prototype is of correct type: console.assert(typeof c.prototype === prototypeType, c + ' prototypeIs'); // Check prototype has correct class: console.assert( Object.prototype.toString.apply(c.prototype) === tc.prototypeClass || tc.classStr, c + ' prototypeClassIs'); // Check prototype has correct proto: console.assert( Object.getPrototypeOf(c.prototype) === (tc.prototypeProto === undefined ? Object.prototype : tc.prototypeProto), c + ' prototypeProtoIs'); // Check prototype's .constructor is constructor: console.assert(c.prototype.constructor === c, c + ' prototypeConstructorIs'); if (!tc.noInstance) { // Check instance's type: console.assert(typeof new c === prototypeType, c + ' instanceIs'); // Check instance's proto: console.assert(Object.getPrototypeOf(new c) === c.prototype, c + ' instancePrototypeIs'); // Check instance's class: console.assert(Object.prototype.toString.apply(new c) === tc.classStr, c + ' instanceClassIs'); // Check instance is instanceof its contructor: console.assert((new c) instanceof c, c + ' instanceIsInstanceof'); if (!tc.functionNotConstructor) { // Recheck instances when constructor called as function: // Recheck instance's type: console.assert(typeof c() === prototypeType, c + ' returnIs'); // Recheck instance's proto: console.assert(Object.getPrototypeOf(c()) === c.prototype, c + ' returnPrototypeIs'); // Recheck instance's class: console.assert(Object.prototype.toString.apply(c()) === tc.classStr, c + ' returnClassIs'); // Recheck instance is instanceof its contructor: console.assert(c() instanceof c, c + ' returnIsInstanceof'); } } // No need to check literals. } }; /////////////////////////////////////////////////////////////////////////////// // Object and Object.prototype tests.ObjectSetPrototypeOfNullUndefined = function() { try { Object.setPrototypeOf(null, null); console.assert(false, "Object.setPrototypeOf(null, ...) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.setPrototypeOf(null, ...) wrong error'); } try { Object.setPrototypeOf(undefined, null); console.assert(false, "Object.setPrototypeOf(undefined, ...) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.setPrototypeOf(undefined, ...) wrong error'); } }; tests.ObjectSetPrototypeOfPrimitives = function() { console.assert(Object.setPrototypeOf(true, null) === true, 'Object.setPrototypeOf boolean'); console.assert(Object.setPrototypeOf(1337, null) === 1337, 'Object.setPrototypeOf number'); console.assert(Object.setPrototypeOf('hi', null) === 'hi', 'Object.setPrototypeOf string'); }; tests.ObjectSetPrototypeOf = function() { var o = {parent: 'o'}; var p = {parent: 'p'}; var q = Object.create(o); console.assert(Object.setPrototypeOf(q, p) === q, 'Object.setPrototypeOf(q, p) return value'); console.assert(Object.getPrototypeOf(q) === p, 'Object.setPrototypeOf(q, p) new parent'); console.assert(q.parent === 'p', 'Object.setPrototypeOf(q, p) inheritance'); }; tests.ObjectSetPrototypeOfToNull = function() { var o = {parent: 'o'}; var q = Object.create(o); console.assert(Object.setPrototypeOf(q, null) === q, 'Object.setPrototypeOf(q, null) return value'); console.assert(Object.getPrototypeOf(q) === null, 'Object.setPrototypeOf(q, null) new parent'); }; tests.ObjectSetPrototypeOfCircular = function() { var o = {}; var p = Object.create(o); try { Object.setPrototypeOf(o, p); console.assert(false, "Object.setPrototypeOf(o, p) didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Object.setPrototypeOf(o, p) wrong error'); } }; tests.ObjectIs = function() { console.assert(Object.is('foo', 'foo'), 'equal strings'); console.assert(Object.is(Array, Array), 'equal objects'); console.assert(!Object.is('foo', 'bar'), 'unequal strings'); console.assert(!Object.is([], []), 'unequal objects'); var test = {a: 1}; console.assert(Object.is(test, test), 'custom object'); console.assert(Object.is(null, null), 'null'); console.assert(!Object.is(0, -0), 'unequal zero'); console.assert(Object.is(-0, -0), 'negative zero'); console.assert(Object.is(NaN, 0/0), 'NaN'); }; /////////////////////////////////////////////////////////////////////////////// // Function and Function.prototype tests.FunctionPrototypeBindClassConstructor = function() { var f = WeakMap.bind(); try { f(); console.assert(false, "Calling bound class constructor didn't throw"); } catch (e) { console.assert(e.name === 'TypeError', 'Calling bound class constructor threw wrong error'); } } tests.FunctionPrototypeBindClassConstructorNew = function() { console.assert(String(new (WeakMap.bind())) === '[object WeakMap]', 'FunctionPrototypeBindClassConstructorNew'); }; /////////////////////////////////////////////////////////////////////////////// // Array and Array.prototype tests.ArrayFind = function() { var inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } console.assert([].find(isCherries) === undefined, 'Array.find 0'); console.assert(inventory.find(isCherries) === inventory[2], 'Array.find 1'); }; tests.ArrayFindIndex = function() { var inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } console.assert([].findIndex(isCherries) === -1, 'Array.findIndex 0'); console.assert(inventory.findIndex(isCherries) === 2, 'Array.findIndex 1'); }; /////////////////////////////////////////////////////////////////////////////// // String and String.prototype tests.StringBooleanSearchFunctions = function() { var str = 'To be, or not to be, that is the question.'; console.assert(str.includes('To be'), 'Includes "To be"'); console.assert(str.includes('question'), 'Includes "question"'); console.assert(!str.includes('nonexistent'), 'Includes "nonexistent"'); console.assert(!str.includes('To be', 1), 'Includes "To be" (1)'); console.assert(!str.includes('TO BE'), 'Includes "TO BE"'); console.assert(str.startsWith('To be'), 'StartsWith "To be"'); console.assert(!str.startsWith('not to be'), 'StartsWith "not to be"'); console.assert(str.startsWith('not to be', 10), 'StartsWith "not to be" (10)'); console.assert(str.endsWith('question.'), 'EndsWith "question."'); console.assert(!str.endsWith('to be'), 'EndsWith "to be"'); console.assert(str.endsWith('to be', 19), 'EndsWith "to be" (19)'); }; tests.StringRepeat = function() { try { 'abc'.repeat(-1); console.assert(false, 'Repeat Negative'); } catch (e) { console.assert(e.name === 'RangeError', 'Repeat Negative Error'); } console.assert('abc'.repeat(0) === '', 'Repeat 0'); console.assert('abc'.repeat(1) === 'abc', 'Repeat 1'); console.assert('abc'.repeat(2) === 'abcabc', 'Repeat 2'); console.assert('abc'.repeat(3.5) === 'abcabcabc', 'Repeat 3.5'); try { 'abc'.repeat(1 / 0); console.assert(false, 'RegExpPrototypeTestApplyNonRegExpThrows'); } catch (e) { console.assert(e.name === 'RangeError', 'RegExpPrototypeTestApplyNonRegExpThrowsError'); } }; /////////////////////////////////////////////////////////////////////////////// // Number tests.NumberEpsilon = function() { console.assert(Number.EPSILON > 0, 'Epsilon > zero'); console.assert(Number.EPSILON < 0.001, 'Epsilon < 0.001'); }; tests.NumberIsFinite = function() { console.assert(!Number.isFinite(Infinity), 'Number.isFinite Infinity'); console.assert(!Number.isFinite(NaN), 'Number.isFinite NaN'); console.assert(!Number.isFinite(-Infinity), 'Number.isFinite -Infinity'); console.assert(Number.isFinite(0), 'Number.isFinite 0'); console.assert(Number.isFinite(2e64), 'Number.isFinite 2e64'); console.assert(!Number.isFinite('0'), 'Number.isFinite "0"'); console.assert(!Number.isFinite(null), 'Number.isFinite null'); }; tests.NumberIsNaN = function() { console.assert(Number.isNaN(NaN), 'Number.isNaN NaN'); console.assert(Number.isNaN(Number.NaN), 'Number.isNaN Number.NaN'); console.assert(Number.isNaN(0 / 0), 'Number.isNaN 0 / 0'); console.assert(!Number.isNaN('NaN'), 'Number.isNaN "NaN"'); console.assert(!Number.isNaN(undefined), 'Number.isNaN undefined'); console.assert(!Number.isNaN({}), 'Number.isNaN {}'); console.assert(!Number.isNaN('blabla'), 'Number.isNaN "blabla"'); console.assert(!Number.isNaN(true), 'Number.isNaN true'); console.assert(!Number.isNaN(null), 'Number.isNaN null'); console.assert(!Number.isNaN(37), 'Number.isNaN 37'); console.assert(!Number.isNaN('37'), 'Number.isNaN "37"'); console.assert(!Number.isNaN('37.37'), 'Number.isNaN "37.37"'); console.assert(!Number.isNaN(''), 'Number.isNaN ""'); console.assert(!Number.isNaN(' '), 'Number.isNaN " "'); }; tests.NumberIsInteger = function() { console.assert(Number.isInteger(-17), 'Number.isInteger -17'); console.assert(Number.isInteger(Math.pow(2, 64)), 'Number.isInteger 2**64'); console.assert(Number.isInteger(-Math.pow(2, 64)), 'Number.isInteger -2**64'); console.assert(!Number.isInteger(NaN), 'Number.isInteger NaN'); console.assert(!Number.isInteger(Infinity), 'Number.isInteger Infinity'); console.assert(!Number.isInteger('3'), 'Number.isInteger "3"'); console.assert(!Number.isInteger(3.1), 'Number.isInteger 3.1'); console.assert(Number.isInteger(3.0), 'Number.isInteger 3.0'); }; tests.NumberIsSafeInteger = function() { console.assert(Number.isSafeInteger(3), 'Number.isSafeInteger 3'); console.assert(!Number.isSafeInteger(Math.pow(2, 53)), 'Number.isSafeInteger 2**53'); console.assert(Number.isSafeInteger(Math.pow(2, 53) - 1), 'Number.isSafeInteger 2**53-1'); console.assert(!Number.isSafeInteger(NaN), 'Number.isSafeInteger NaN'); console.assert(!Number.isSafeInteger(Infinity), 'Number.isSafeInteger Infinity'); console.assert(!Number.isSafeInteger('3'), 'Number.isSafeInteger "3"'); console.assert(!Number.isSafeInteger(3.1), 'Number.isSafeInteger 3.1'); console.assert(Number.isSafeInteger(3.0), 'Number.isSafeInteger 3.0'); }; tests.NumberMaxSafeInteger = function() { console.assert(Number.MAX_SAFE_INTEGER + 1 === Math.pow(2, 53), 'Number.MAX_SAFE_INTEGER'); console.assert(Number.isSafeInteger(Number.MAX_SAFE_INTEGER), 'Number.isSafeInteger(Number.MAX_SAFE_INTEGER);'); console.assert(!Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1), 'Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1);'); }; tests.NumberMinSafeInteger = function() { console.assert(Number.MIN_SAFE_INTEGER === -(Math.pow(2, 53) - 1), 'Number.MIN_SAFE_INTEGER'); console.assert(Number.isSafeInteger(Number.MIN_SAFE_INTEGER), 'Number.isSafeInteger(Number.MIN_SAFE_INTEGER);'); console.assert(!Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1), 'Number.isSafeInteger(Number.MIN_SAFE_INTEGER - 1);'); }; /////////////////////////////////////////////////////////////////////////////// // Math tests.MathAcosh = function() { console.assert(Number.isNaN(Math.acosh(-1)), 'Math.acosh -1'); console.assert(Number.isNaN(Math.acosh(0)), 'Math.acosh 0'); console.assert(Number.isNaN(Math.acosh(0.5)), 'Math.acosh 0.5'); console.assert(Math.acosh(1) === 0, 'Math.acosh 1'); console.assert(Math.acosh(2).toPrecision(10) === '1.316957897', 'Math.acosh 2'); }; tests.MathAsinh = function() { console.assert(Math.asinh(1).toPrecision(10) === '0.8813735870', 'Math.asinh 1'); console.assert(Math.asinh(0) === 0, 'Math.asinh 0'); }; tests.MathAtanh = function() { console.assert(Number.isNaN(Math.atanh(-2)), 'Math.atanh -2'); console.assert(Math.atanh(-1) === -Infinity, 'Math.atanh -1'); console.assert(Math.atanh(0) === 0, 'Math.atanh 0'); console.assert(Math.atanh(0.5).toPrecision(10) === '0.5493061443', 'Math.atanh 0.5'); console.assert(Math.atanh(1) === Infinity, 'Math.atanh 1'); console.assert(Number.isNaN(Math.atanh(2)), 'Math.atanh 2'); }; tests.MathCbrt = function() { console.assert(Number.isNaN(Math.cbrt(NaN)), 'Math.cbrt NaN'); console.assert(Math.cbrt(-1) === -1, 'Math.cbrt -1'); console.assert(Object.is(Math.cbrt(-0), -0), 'Math.cbrt -0'); console.assert(Math.cbrt(-Infinity) === -Infinity, 'Math.cbrt -Infinity'); console.assert(Object.is(Math.cbrt(0), 0), 'Math.cbrt 0'); console.assert(Math.cbrt(1) === 1, 'Math.cbrt 1'); console.assert(Math.cbrt(Infinity) === Infinity, 'Math.cbrt Infinity'); console.assert(Math.cbrt(null) === 0, 'Math.cbrt null'); console.assert(Math.cbrt(2).toPrecision(10) === '1.259921050', 'Math.cbrt 2'); }; tests.MathClz32 = function() { console.assert(Math.clz32(1) === 31, 'Math.clz32 1'); console.assert(Math.clz32(1000) === 22, 'Math.clz32 1000'); console.assert(Math.clz32() === 32, 'Math.clz32 ()'); console.assert(Math.clz32(NaN) === 32, 'Math.clz32 NaN'); console.assert(Math.clz32(Infinity) === 32, 'Math.clz32 Infinity'); console.assert(Math.clz32(-Infinity) === 32, 'Math.clz32 -Infinity'); console.assert(Math.clz32(0) === 32, 'Math.clz32 0'); console.assert(Math.clz32(-0) === 32, 'Math.clz32 -0'); console.assert(Math.clz32(null) === 32, 'Math.clz32 null'); console.assert(Math.clz32(undefined) === 32, 'Math.clz32 undefined'); console.assert(Math.clz32('foo') === 32, 'Math.clz32 "foo"'); console.assert(Math.clz32({}) === 32, 'Math.clz32 {}'); console.assert(Math.clz32([]) === 32, 'Math.clz32 []'); console.assert(Math.clz32(true) === 31, 'Math.clz32 true'); console.assert(Math.clz32(3.5) === 30, 'Math.clz32 3.5'); }; tests.MathCosh = function() { console.assert(Math.cosh(-1).toPrecision(10) === '1.543080635', 'Math.cosh -1'); console.assert(Math.cosh(0) === 1, 'Math.cosh 0'); console.assert(Math.cosh(1).toPrecision(10) === '1.543080635', 'Math.cosh 1'); }; tests.MathExpm1 = function() { console.assert(Math.expm1(-1).toPrecision(10) === '-0.6321205588', 'Math.expm1 -1'); console.assert(Math.expm1(0) === 0, 'Math.expm1 0'); console.assert(Math.expm1(1).toPrecision(10) === '1.718281828', 'Math.expm1 1'); }; tests.MathFround = function() { console.assert(Math.fround(1.5) === 1.5, 'Math.fround 1.5'); console.assert(Math.fround(1.337).toPrecision(10) === '1.337000012', 'Math.fround 1.337'); console.assert(Math.fround(Math.pow(2, 150)) === Infinity, 'Math.fround 2**150'); console.assert(Number.isNaN(Math.fround('abc')), 'Math.fround "abc"'); console.assert(Number.isNaN(Math.fround(NaN)), 'Math.fround NaN'); }; tests.MathHypot = function() { console.assert(Math.hypot(3, 4) === 5, 'Math.hypot 3, 4'); console.assert(Math.hypot(3, 4, 5).toPrecision(10) === '7.071067812', 'Math.hypot 3, 4, 5'); console.assert(Math.hypot() === 0, 'Math.hypot ()'); console.assert(Number.isNaN(Math.hypot(NaN)), 'Math.hypot NaN'); console.assert(Number.isNaN(Math.hypot(3, 4, 'foo')), 'Math.hypot 3, 4, "foo"'); console.assert(Math.hypot(3, 4, '5').toPrecision(10) === '7.071067812', 'Math.hypot 3, 4, "5"'); console.assert(Math.hypot(-3) === 3, 'Math.hypot -3'); }; tests.MathImul = function() { console.assert(Math.imul(2, 4) === 8, 'Math.imul 2, 4'); console.assert(Math.imul(-1, 8) === -8, 'Math.imul -1, 8'); console.assert(Math.imul(-2, -2) === 4, 'Math.imul -2, -2'); console.assert(Math.imul(0xffffffff, 5) === -5, 'Math.imul 0xffffffff, 5'); console.assert(Math.imul(0xfffffffe, 5) === -10, 'Math.imul 0xfffffffe, 5'); }; tests.MathLog10 = function() { console.assert(Math.log10(2).toPrecision(10) === '0.3010299957', 'Math.log10 2'); console.assert(Math.log10(1) === 0, 'Math.log10 1'); console.assert(Math.log10(0) === -Infinity, 'Math.log10 0'); console.assert(Number.isNaN(Math.log10(-2)), 'Math.log10 -2'); console.assert(Math.log10(100000) === 5, 'Math.log10 100000'); }; tests.MathLog1p = function() { console.assert(Math.log1p(1).toPrecision(10) === '0.6931471806', 'Math.log1p 1'); console.assert(Math.log1p(0) === 0, 'Math.log1p 0'); console.assert(Math.log1p(-1) === -Infinity, 'Math.log1p -1'); console.assert(Number.isNaN(Math.log1p(-2)), 'Math.log1p -2'); }; tests.MathLog2 = function() { console.assert(Math.log2(3).toPrecision(10) === '1.584962501', 'Math.log2 3'); console.assert(Math.log2(2) === 1, 'Math.log2 2'); console.assert(Math.log2(1) === 0, 'Math.log2 1'); console.assert(Math.log2(0) === -Infinity, 'Math.log2 0'); console.assert(Number.isNaN(Math.log2(-2)), 'Math.log2 -2'); console.assert(Math.log2(1024) === 10, 'Math.log2 1024'); }; tests.MathSign = function() { console.assert(Math.sign(3) === 1, 'Math.sign 3'); console.assert(Math.sign(-3) === -1, 'Math.sign -3'); console.assert(Math.sign('-3') === -1, 'Math.sign "-3"'); console.assert(Object.is(Math.sign(0), 0), 'Math.sign 0'); console.assert(Object.is(Math.sign(-0), -0), 'Math.sign -0'); console.assert(Number.isNaN(Math.sign(NaN)), 'Math.sign NaN'); console.assert(Number.isNaN(Math.sign('foo')), 'Math.sign "foo"'); console.assert(Number.isNaN(Math.sign()), 'Math.sign undefined'); }; tests.MathSinh = function() { console.assert(Math.sinh(0) === 0, 'Math.sinh 0'); console.assert(Math.sinh(1).toPrecision(10) === '1.175201194', 'Math.sinh 1'); }; tests.MathTanh = function() { console.assert(Math.tanh(0) === 0, 'Math.tanh 0'); console.assert(Math.tanh(Infinity) === 1, 'Math.tanh Infinity'); console.assert(Math.tanh(1).toPrecision(10) === '0.7615941560', 'Math.tanh 1'); }; tests.MathTrunc = function() { console.assert(Math.trunc(13.37) === 13, 'Math.trunc 13.37'); console.assert(Math.trunc(42.84) === 42, 'Math.trunc 42.84'); console.assert(Object.is(Math.trunc(0.123), 0), 'Math.trunc 0.123'); console.assert(Object.is(Math.trunc(-0.123), -0), 'Math.trunc -0.123'); console.assert(Math.trunc('-1.123') === -1, 'Math.trunc "-1.123"'); console.assert(Number.isNaN(Math.trunc(NaN)), 'Math.trunc NaN'); console.assert(Number.isNaN(Math.trunc('foo')), 'Math.trunc "foo"'); console.assert(Number.isNaN(Math.trunc()), 'Math.trunc undefined'); }; /////////////////////////////////////////////////////////////////////////////// // WeakMap and WeakMap.prototype tests.WeakMap = function() { var w = new WeakMap; var p = {}; var o = Object.create(p); console.assert(!w.has(p), 'WeakMapPrototypeHasNonKey'); console.assert(!w.delete(p), 'WeakMapPrototypeDeleteNonKey'); console.assert(w.set(o, 'o') === w, 'WeakMapPrototypeSet'); console.assert(w.get(o) === 'o', 'WeakMapPrototypeGet'); console.assert(w.get(p) === undefined, 'WeakMapPrototypeGetNonKey'); console.assert(w.has(o), 'WeakMapPrototypeHas'); console.assert(w.delete(o), 'WeakMapPrototypeDelete'); console.assert(!w.has(o), 'WeakMapPrototypeHasNonKey'); }; tests.WeakMapPrototypeMethodsRejectInvalid = function() { var w = new WeakMap; var name = 'WeakMapPrototypeMethodsReject'; function expectError(method, thisVal, args) { var label = String(thisVal === w ? args : 'ThisIs' + args); try { w[method].apply(thisVal, args); console.assert(false, name + label); } catch (e) { console.assert(e.name === 'TypeError', name + label + 'Error'); } } var methods = ['delete', 'get', 'has', 'set']; var values = [null, undefined, true, false, 0, 42, '', 'hi']; for (var i = 0; i < methods.length; i++) { var method = methods[i]; for (var j = 0; j < values.length; j++) { var value = values[j]; expectError(method, value, [{}]); expectError(method, w, [value]); } expectError(method, WeakMap.prototpye, [{}]); // Ordinary object. } }; ================================================ FILE: server/tests/db/test_01_es7.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test the ES7 functions of the server. * @author fraser@google.com (Neil Fraser) */ /////////////////////////////////////////////////////////////////////////////// // Array and Array.prototype tests.ArrayPrototypeIncludes = function() { console.assert([1, 2, 3, 2, 1].includes(2), 'Array.prototype.includes'); console.assert(![1, 2, 3, 2, 1].includes(4), 'Array.prototype.includes not found'); console.assert([1, 2, 3, 2, 1].includes(2, 2), 'Array.prototype.includes(..., +)'); console.assert([1, 2, 3, 2, 1].includes(1, -3), 'Array.prototype.includes(..., -)'); console.assert(['x', NaN, 'y'].includes(NaN), 'Array.prototype.includes NaN'); var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5}; console.assert(Array.prototype.includes.call(o, 2), 'Array.prototype.includes.call(array-like, ...)'); }; ================================================ FILE: server/tests/db/test_02_errors.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test language extensions related to errors. * @author cpcallen@google.com (Christopher Allen) */ tests.errorStack = function() { // Use eval to make parsing .stack easier. var e = eval('new Error;'); var lines = e.stack.split('\n'); console.assert(lines[0].trim() === 'at "new Error;" 1:1', 'new Error has .stack'); try { (function buggy() {1 instanceof 2;})(); console.assert(false, "thrown Error wasn't thrown??"); } catch (e) { lines = e.stack.split('\n'); console.assert(lines[0].trim() === 'at buggy 1:19', 'thrown Error has .stack'); } // Bug #241. function foo() { switch (1) { case 1: return undefined.hasNoProperties; } } try { foo(); console.assert(false, "Invalid MemberExpression didn't throw??"); } catch (e) { lines = e.stack.split('\n'); console.assert(lines[0].trim() === 'at foo 4:16', 'Invalid MemberExpression escaped blame'); } function bar() { return undefinedVariable; } try { bar(); console.assert(false, "Invalid Identifier didn't throw??"); } catch (e) { lines = e.stack.split('\n'); console.assert(lines[0].trim() === 'at bar 2:12', 'Invalid Identifier escaped blame'); } }; ================================================ FILE: server/tests/db/test_02_perms.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test the permissions system. * @author cpcallen@google.com (Christopher Allen) */ tests.perms = function() { console.assert(perms() === CC.root, 'perms() returns root'); }; tests.setPerms = function() { var bob = {}; console.assert(perms() === CC.root, 'before setPerms()'); (function() { setPerms(bob); console.assert(perms() === bob, 'after setPerms()'); // Perms revert at end of scope. })(); console.assert(perms() === CC.root, 'after scope end'); }; tests.getOwnerOf = function() { var bob = {}; var roots = {}; setPerms(bob); var bobs = {}; console.assert(Object.getOwnerOf(Object) === CC.root, 'getOwenerOfObject'); console.assert(Object.getOwnerOf(roots) === CC.root, 'getOwnerOfNew'); console.assert(Object.getOwnerOf(bobs) === bob, 'getOwnerOfBobs'); }; tests.setOwnerOf = function() { var bob = {}; var obj = {}; console.assert(Object.setOwnerOf(obj, bob) === obj, 'setOwneerOf return'); console.assert(Object.getOwnerOf(obj) === bob, 'setOwenerOf effect'); }; ================================================ FILE: server/tests/db/test_09_end.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Run the unit tests. * @author fraser@google.com (Neil Fraser) */ $.system.log('Starting tests'); for (var name in tests) { var oldBad = console.badCount; try { tests[name](); } catch (e) { console.assert(false, 'CRASH: ' + name + '\n' + e); } if (oldBad < console.badCount) { $.system.log(String(tests[name])); } } $.system.log(''); $.system.log('Completed tests'); $.system.log('Pass: %d', console.goodCount); $.system.log('Fail: %d', console.badCount); ================================================ FILE: server/tests/db/test_10_fibonacci.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Run a performance stress test. * @author fraser@google.com (Neil Fraser) */ // Define function as global so that it can be run again // after checkpoint and restart. function test_fibonacci10k() { for (var run = 1; run <= 3; run++) { var start = Date.now(); var fibonacci = function(n, output) { var a = 1, b = 1, sum; for (var i = 0; i < n; i++) { output.push(a); sum = a + b; a = b; b = sum; } } for(var i = 0; i < 10000; i++) { var result = []; fibonacci(78, result); } result; var ms = Date.now() - start; $.system.log('Run #%d fibonacci10k: %d ms', run, ms); } } $.system.log('Benchmarking fibonacci10k...'); test_fibonacci10k(); ================================================ FILE: server/tests/db/test_20_reboot.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Reboot the server, and verify restart. * @author fraser@google.com (Neil Fraser) */ $.system.shutdown(); $.system.log('Benchmarking resurrected fibonacci10k...'); test_fibonacci10k(); $.system.shutdown(); ================================================ FILE: server/tests/dump_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Tests for Saving the state of the interpreter as * eval-able JS. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const {configFromSpec, Do, dump} = require('../dump'); const fs = require('fs'); const Interpreter = require('../interpreter'); const path = require('path'); const Selector = require('../selector'); const {T} = require('./testing'); const util = require('util'); /** * Unit tests for the dump function * @param {!T} t The test runner object. */ exports.testConfigFromSpec = function(t) { const cases = [{ input: [], expected: [], }, { input: [ {filename: 'foo', header: ['// F1 BIOS', '// Copyright YEAR Foonly inc.', 'LINES'], headerSubs: {YEAR: '1978', LINES: ['// 1', '// 2']}, contents: ['a', 'b']}], expected: [ {filename: 'foo', header: '// F1 BIOS\n// Copyright YEAR Foonly inc.\nLINES', headerSubs: {YEAR: '1978', LINES: '// 1\n// 2'}, prune: [], pruneRest: [], contents: [ {selector: new Selector('a'), do: Do.RECURSE, reorder: false}, {selector: new Selector('b'), do: Do.RECURSE, reorder: false} ], rest: false }], }, { input: [{filename: 'foo', prune: ['a', 'b'], rest: true}], expected: [ {filename: 'foo', header: undefined, headerSubs: {}, prune: [new Selector('a'), new Selector('b')], pruneRest: [], contents: [], rest: true }], }, { input: [{filename: 'foo', pruneRest: ['c', 'd'], rest: true}], expected: [ {filename: 'foo', header: undefined, headerSubs: {}, prune: [], pruneRest: [new Selector('c'), new Selector('d')], contents: [], rest: true }], }, { input: [{options: {}}, {options: {treeOnly: false}}], expected: [{options: {}}, {options: {treeOnly: false}}], }]; for (const {input, expected} of cases) { const out = configFromSpec(input); t.expect(util.format('configFromSpec(%o)', input), util.format('%o', out), util.format('%o', expected)); } const invalid = [ undefined, // Not an array. 'a string', // Not an array. {object: 'not array'}, // Not an array. ['array', 'of', 'strings'], // Array but not of objects. [{}], // Neither SpecFileItem nor SpecOptionsItem. [{filename: 'foo'}], // Missing both .contents and .rest. [{filename: 'foo', contents: [], rest: 'bar'}], // .rest not bool. [{filename: 'foo', contents: [42]}], // .contents[0] not object or string. [{filename: 'foo', contents: ['foo[']}], // .contents[0] invalid selector. [{filename: 'foo', contents: [{}]}], // ... has no .path. [{filename: 'foo', contents: [{path: 'bar'}]}], // ... has no .do. [{filename: 'foo', contents: [{path: 'bar', do: 2}]}], // ... invalid .do. [{filename: 'foo', contents: [{path: 'bar', do: 'baz'}]}], // Ditto. [{filename: 'foo', // .reorder not a boolean. contents: [{path: 'bar', do: 'SET', reorder: 'qux'}]}], [{filename: 'foo', rest: 42}], // .rest not a boolean. [{filename: 'foo', rest: 'false'}], // .rest not a boolean. [{filename: 'foo', prune: 'x', rest: true}], // .prune not an array. [{filename: 'foo', prune: ['foo['], rest: true}], // .prune[0] invalid. [{filename: 'foo', pruneRest: 'x', rest: true}], // .prune not an array. [{filename: 'foo', pruneRest: ['foo['], rest: true}], // .prune[0] invalid. [{options: 'not an object'}], // .options is not an object. ]; for (const input of invalid) { const name = util.format('configFromSpec(%o)', input); try { configFromSpec(input); t.fail(util.format("%O didn't throw", input)); } catch (e) { if (!(e instanceof TypeError || e instanceof SyntaxError)) { t.fail(util.format('%O threw wrong error', input), e); } } } }; /** * Unit tests for the dump function * @param {!T} t The test runner object. */ exports.testDump = function(t) { const intrp = new Interpreter({noLog: ['net']}); // Load tinycore. const coreDir = 'tests/tinycore'; for (const file of fs.readdirSync(coreDir) || []) { if (file.match(/^(core|test).*\.js$/)) { const filename = path.join(coreDir, file); intrp.createThreadForSrc(String(fs.readFileSync(filename, 'utf8'))); intrp.run(); } } intrp.stop(); // Close any listening sockets, so node will exit. const specText = fs.readFileSync(path.join(coreDir, 'dump_spec.json')); const spec = JSON.parse(String(specText)); var config = configFromSpec(spec); dump(new Interpreter(), intrp, config, '/tmp'); }; ================================================ FILE: server/tests/dumper_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Tests for Saving the state of the interpreter as * eval-able JS. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const {Dumper, Do, testOnly, Writable} = require('../dumper'); const {getInterpreter} = require('./interpreter_common'); const Interpreter = require('../interpreter'); const path = require('path'); const Selector = require('../selector'); const {T} = require('./testing'); const util = require('util'); // Unpack test-only exports. const {Components, ObjectDumper, ScopeDumper} = testOnly; /** * A mock Writable, for testing. * @implements {Writable} */ class MockWritable { constructor() { /** @const {!Array} */ this.output = []; } /** @override */ write(chunk) { this.output.push(String(chunk)); } /** @return {string} */ toString() { return this.output.join(''); } } /** * Tests for the ObjectDumper.prototype.isWritable method. * @suppress {accessControls} */ exports.testObjectDumperPrototypeIsWritable = function(t) { const intrp = getInterpreter(); // Create some objects and properties: // - .foo writable on child but not Object.prototype. // - .bar writable on child but not parent. // - .baz writable on child and parent. intrp.createThreadForSrc(` Object.prototype.foo = undefined; // Cheeky! Object.defineProperty(Object.prototype, 'foo', {writable: false}); var parent = {bar: undefined, baz: undefined}; Object.defineProperty(parent, 'bar', {writable: false}); var child = {foo: undefined, bar: undefined, baz: undefined}; Object.setPrototypeOf(child, parent); `); intrp.run(); const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); dumper.dumpBinding(new Selector('Object'), Do.SET); dumper.dumpBinding(new Selector('Object.prototype'), Do.SET); const objectPrototypeDumper = dumper.getObjectDumper_(intrp.OBJECT); const parentDumper = dumper.getDumperFor('parent'); const childDumper = dumper.getDumperFor('child'); // Fake dumping of parent and child as if created by object // literals. (.dumpBinding would use Object.create, pre-setting // their prototypes - we don't want that for this test.) parentDumper.proto = intrp.OBJECT; parentDumper.ref = new Components(dumper.global, 'parent'); childDumper.proto = intrp.OBJECT; childDumper.ref = new Components(dumper.global, 'child'); // Now dump various bindings in a certain order, and check // writability of child.foo, .bar and .baz in each situation. objectPrototypeDumper.dumpBinding(dumper, 'foo', Do.SET); parentDumper.dumpBinding(dumper, Selector.PROTOTYPE, Do.SET); parentDumper.dumpBinding(dumper, 'bar', Do.SET); childDumper.dumpBinding(dumper, Selector.PROTOTYPE, Do.DECL); t.expect("childDumper.isWritable('foo') // 0", childDumper.isWritable(dumper, 'foo'), true); t.expect("childDumper.isWritable('bar') // 0", childDumper.isWritable(dumper, 'bar'), true); t.expect("childDumper.isWritable('baz') // 0", childDumper.isWritable(dumper, 'baz'), true); objectPrototypeDumper.dumpBinding(dumper, 'foo', Do.ATTR); parentDumper.dumpBinding(dumper, 'bar', Do.ATTR); t.expect("childDumper.isWritable('foo') // 1", childDumper.isWritable(dumper, 'foo'), false); t.expect("childDumper.isWritable('bar') // 1", childDumper.isWritable(dumper, 'bar'), true); t.expect("childDumper.isWritable('baz') // 1", childDumper.isWritable(dumper, 'baz'), true); childDumper.dumpBinding(dumper, Selector.PROTOTYPE, Do.SET); t.expect("childDumper.isWritable('foo') // 2", childDumper.isWritable(dumper, 'foo'), false); t.expect("childDumper.isWritable('bar') // 2", childDumper.isWritable(dumper, 'bar'), false); t.expect("childDumper.isWritable('baz') // 2", childDumper.isWritable(dumper, 'baz'), true); childDumper.dumpBinding(dumper, 'foo', Do.DECL); childDumper.dumpBinding(dumper, 'bar', Do.DECL); childDumper.dumpBinding(dumper, 'baz', Do.DECL); t.expect("childDumper.isWritable('foo') // 3", childDumper.isWritable(dumper, 'foo'), true); t.expect("childDumper.isWritable('bar') // 3", childDumper.isWritable(dumper, 'bar'), true); t.expect("childDumper.isWritable('baz') // 3", childDumper.isWritable(dumper, 'baz'), true); }; /** * Tests for the ObjectDumper.prototype.updateRef method. * @suppress {accessControls} */ exports.testObjectDumperUpdateRef = function(t) { const intrp = new Interpreter(); // ScopeDumper for global scope and ObjectDumpers for some arbitrary objects. const globalDumper = new ScopeDumper(intrp.global); const fooDumper = new ObjectDumper(new intrp.Object()); const barDumper = new ObjectDumper(new intrp.Object()); const reachableDumper = new ObjectDumper(new intrp.Object()); const unreachableDumper = new ObjectDumper(new intrp.Object()); // Stub Dumper. const /** !Dumper */ dumper = /** @type {?} */({ intrp2: intrp, scope: intrp.global, }); // Scenario 0: Reject self references. fooDumper.updateRef(dumper, new Components(fooDumper, '')); t.expect('fooDumper.updateRef(); fooDumper.ref', fooDumper.ref, null); // Scenario 1: Typical cases during dumping. We've dumped foo and // are dumping foo.bar, which might also have (not preferred) // references from reachable and unreachable objects or the global // scope. fooDumper.preferredRef = new Components(globalDumper, 'foo'); fooDumper.ref = fooDumper.preferredRef; // Reachable. barDumper.preferredRef = new Components(fooDumper, 'bar'); // foo.bar barDumper.ref = null; // Not yet reachable. reachableDumper.preferredRef = new Components(globalDumper, 'reachable'); reachableDumper.ref = reachableDumper.preferredRef; // Reachable. unreachableDumper.preferredRef = new Components(globalDumper, 'unreachable'); unreachableDumper.ref = null; // Not yet reachable. // Test all N*N combinations of possible (existing, proposed) refs // for bar. Cases are in order increrasing preferability: earlier // ones should be replace by later but not vice-versa. const cases = [ null, // No known reference yet. // Refs from an unreachable object are better than nothing. new Components(unreachableDumper, Selector.PROTOTYPE), new Components(unreachableDumper, '#hash'), new Components(unreachableDumper, '42'), new Components(unreachableDumper, 'aaaaaaaaaa'), new Components(unreachableDumper, 'bar'), // Refs from reachable objects are better - but other than // foo.bar, these two objects are equally good so order just comes // down to selector badness. new Components(reachableDumper, Selector.PROTOTYPE), new Components(fooDumper, Selector.PROTOTYPE), new Components(reachableDumper, '#hash'), new Components(fooDumper, '#hash'), new Components(reachableDumper, '42'), new Components(fooDumper, '42'), new Components(reachableDumper, 'aaaaaaaaaa'), new Components(fooDumper, 'aaaaaaaaaa'), new Components(reachableDumper, 'bar'), new Components(reachableDumper, 'b'), new Components(fooDumper, 'b'), // Refs from a scope are generally better. new Components(globalDumper, 'aaaaaaaaaa'), new Components(globalDumper, 'bar'), new Components(globalDumper, 'b'), // The preferred reference is best of all. new Components(fooDumper, 'bar'), ]; for (var i = 0; i < cases.length; i++) { for (var j = 1; j < cases.length; j++) { // Don't call updateRef with null. if (!reachableDumper.ref) throw new Error(); const before = cases[i]; const suggested = cases[j]; const expected = cases[Math.max(i, j)]; const name = util.format('updateRef %o to %o?', before, suggested); const message = util.format(['barDumper.ref = %s;', 'barDumper.updateRef(%s);', 'barDumper.ref;'].map(s => ' ' + s).join('\n'), before, suggested); barDumper.ref = before; barDumper.updateRef(dumper, suggested); t.expect(name, barDumper.ref, expected, message); } } // TODO(cpcallen): Scenario 2: unreachable refs (e.g. due to scoping). }; /** * Unit tests for the Dumper.prototype.isShadowed_ method. * @param {!T} t The test runner object. * @suppress {accessControls} */ exports.testDumperPrototypeIsShadowed_ = function(t) { const intrp = new Interpreter(); const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); intrp.global.createMutableBinding('foo', 'foo'); intrp.global.createMutableBinding('bar', 'bar'); const inner = new Interpreter.Scope(Interpreter.Scope.Type.FUNCTION, intrp.ROOT, intrp.global); inner.createMutableBinding('foo', 'foobar!'); dumper.scope = inner; t.expect("isShadowed_('foo')", dumper.isShadowed_('foo'), true); t.expect("isShadowed_('bar')", dumper.isShadowed_('bar'), false); }; /** * Unit tests for the Dumper.prototype.exprForPrimitive_ method. * @param {!T} t The test runner object. * @suppress {accessControls} */ exports.testDumperPrototypeExprForPrimitive_ = function(t) { const intrp = new Interpreter(); const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); function doCases(cases) { for (const tc of cases) { const r = dumper.exprForPrimitive_(tc[0]); t.expect(util.format('dumper.exprForPrimitive_(%o)', tc[0]), r, tc[1]); t.expect(util.format('eval(dumper.exprForPrimitive_(%o))', tc[0]), eval(r), tc[0]); } } doCases([ [undefined, 'undefined'], [null, 'null'], [false, 'false'], [true, 'true'], [0, '0'], [-0, '-0'], [Infinity, 'Infinity'], [-Infinity, '-Infinity'], [NaN, 'NaN'], ['foo', "'foo'"], ]); // Shadow some names and check results are still correct. const inner = new Interpreter.Scope(Interpreter.Scope.Type.FUNCTION, intrp.ROOT, intrp.global); inner.createMutableBinding('Infinity', '42'); inner.createMutableBinding('NaN', '42'); inner.createMutableBinding('undefined', '42'); dumper.scope = inner; doCases([ [undefined, '(void 0)'], [Infinity, '(1/0)'], [-Infinity, '(-1/0)'], [NaN, '(0/0)'], ]); }; /** * Tests for the Dumper.prototype.exprFor_ method. * @param {!T} t The test runner object. * @suppress {accessControls} */ exports.testDumperPrototypeExprFor_ = function(t) { // Create an Interperter with a UserFunction to dump. const intrp = new Interpreter(); intrp.createThreadForSrc('function foo(bar) {}'); intrp.run(); const func = /** @type {!Interpreter.prototype.UserFunction} */ ( intrp.global.get('foo')); const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); // Give references to needed builtins. for (const b of [ 'Date', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'TypeError', 'SyntaxError', 'URIError', 'PermissionError', 'WeakMap', ]) { dumper.getObjectDumper_(/** @type {!Interpreter.prototype.Object} */ (intrp.builtins.get(b))).ref = new Components(dumper.global, b); } // Give foo a reference too, even though it has not been created yet. dumper.getObjectDumper_(func).ref = new Components(dumper.global, 'foo'); const cases = [ [intrp.OBJECT, "new 'Object.prototype'"], [func, 'function foo(bar) {}'], [new intrp.Object(intrp.ROOT), '{}'], [new intrp.Array(intrp.ROOT), '[]'], [new intrp.Date(new Date('1975-07-27'), intrp.ROOT), "new Date('1975-07-27T00:00:00.000Z')"], [new intrp.RegExp(/foo/ig, intrp.ROOT), '/foo/gi'], [new intrp.Error(intrp.ROOT, intrp.ERROR), "new Error()"], [new intrp.Error(intrp.ROOT, intrp.ERROR, 'message'), "new Error('message')"], [new intrp.Error(intrp.ROOT, intrp.EVAL_ERROR), "new EvalError()"], [new intrp.Error(intrp.ROOT, intrp.RANGE_ERROR), "new RangeError()"], [new intrp.Error(intrp.ROOT, intrp.REFERENCE_ERROR), "new ReferenceError()"], [new intrp.Error(intrp.ROOT, intrp.SYNTAX_ERROR), "new SyntaxError()"], [new intrp.Error(intrp.ROOT, intrp.TYPE_ERROR), "new TypeError()"], [new intrp.Error(intrp.ROOT, intrp.URI_ERROR), "new URIError()"], [new intrp.Error(intrp.ROOT, intrp.PERM_ERROR), "new PermissionError()"], [new intrp.Error(intrp.ROOT, intrp.OBJECT), "new Error()"], [new intrp.Error(intrp.ROOT, null), "new Error()"], [new intrp.WeakMap(), 'new WeakMap()'], ]; // A fake reference: exprFor_ won't create an unreferenceable object. const ref = new Components(dumper.global, 'dummyVariable'); for (const [value, expected] of cases) { const r = dumper.exprFor_(value, ref); t.expect(util.format('Dumper.p.exprFor_(%s)', value), r, expected); } }; /** * Tests for Dumper.prototype.survey_, and in particular the * imlementation of Dijkstra's Algorigithm it uses to set the * .preferredRef property on ObjectDumper instances. * @param {!T} t The test runner object. * @suppress {accessControls} */ exports.testDumperPrototypeSurvey = function(t) { const intrp = getInterpreter(); // Create various variables to dump. intrp.createThreadForSrc(` var func = (function() { var unreachable = {unreachable: true}; return function foo() {return unreachable;}; })(); var arr = [{baz: {}}]; var foo = {bar: arr[0]}; Object.setPrototypeOf(foo.bar, {}); `); intrp.run(); // Create Dumper with pristine Interpreter instance to compare to; // get ScopeDumper for global scope. Dumper constructor performs // survey. const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); // Check preferredRef of various objects. The preferred selector is // assumed to be the same as the selector used to obtain the object // unless otherwise specified. const tc = [ ['func'], ['func{proto}', 'Function.prototype'], ['func{owner}', 'CC.root'], ['func.prototype'], ['func.prototype{proto}', 'Object.prototype'], ['foo'], ['foo{proto}', 'Object.prototype'], ['foo.bar{proto}'], ['foo.bar.baz{proto}', 'Object.prototype'], ['arr[0]', 'foo.bar'], ]; for (const [ss, expected] of tc) { const objDumper = dumper.getDumperFor(ss); t.expect('Dumper.p.survey_: .preferredRef of ' + ss, objDumper.getSelector(/*preferred=*/true).toString(), expected || ss); } // Can't create preferred Selector for unreachable (it's // unreachable!), so check .preferredRef manually. const func = intrp.global.get('func'); if (!(func instanceof intrp.UserFunction) || !func.scope.outerScope) { throw new TypeError('func.scope.outerScope not a Scope'); } const funcScopeDumper = dumper.getScopeDumper_(func.scope.outerScope); const unreachable = func.scope.outerScope.get('unreachable'); if (!(unreachable instanceof intrp.Object)) throw new TypeError(); const unreachableDumper = dumper.getObjectDumper_(unreachable); t.expect('Dumper.p.survey_: unreachableDumper.preferredRef.dumper', unreachableDumper.preferredRef.dumper, funcScopeDumper); t.expect('Dumper.p.survey_: unreachableDumper.preferredRef.part', unreachableDumper.preferredRef.part, 'unreachable'); }; /** * Tests for the ObjectDumper.prototype.survey and * ScopeDumper.prototype.survey methods and their recording of * information about Scopes, Arguments objects and so on. * @param {!T} t The test runner object. * @suppress {accessControls} */ exports.testSubDumperPrototypeSurvey = function(t) { const intrp = new Interpreter(); // Create various variables to dump, including creating a closure // belonging to two functions. intrp.createThreadForSrc(` var foo = (function() { var x = 42; bar = function baz() {return x;}; function quux() {return -x;}; return quux; arguments; // Never reached, but forces Arguments instantiation. })(); var bar; // N.B.: hoisted. var orphanArgs = (function() {return arguments;})(); `); intrp.run(); // Create Dumper with pristine Interpreter instance to compare to; // get ScopeDumper for global scope. Dumper constructor performs // survey. const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); // Check relationship of functions and scopes recorded by survey. const baz = /** @type {!Interpreter.prototype.UserFunction} */( intrp.global.get('bar')); // Function baz was stored in var bar. const quux = /** @type {!Interpreter.prototype.UserFunction} */( intrp.global.get('foo')); // IIFE returned quux; was stored in var foo. const globalDumper = dumper.getScopeDumper_(intrp.global); const bazDumper = dumper.getObjectDumper_(baz); const bazScopeDumper = dumper.getScopeDumper_(baz.scope); const quuxDumper = dumper.getObjectDumper_(quux); const quuxScopeDumper = dumper.getScopeDumper_(quux.scope); t.expect('bazScopeDumper.scope.type', bazScopeDumper.scope.type, 'funexp'); t.expect('quuxScopeDumper.scope.type', quuxScopeDumper.scope.type, 'function'); t.expect('globalDumper.innerFunctions.size', globalDumper.innerFunctions.size, 0); t.expect('globalDumper.innerScopes.size', globalDumper.innerScopes.size, 1); t.assert('globalDumper.innerScopes.has(/* quux.scope */)', globalDumper.innerScopes.has(quuxScopeDumper)); t.expect('quuxScopeDumper.innerFunctions.size', quuxScopeDumper.innerFunctions.size, 1); t.assert('quuxScopeDumper.innerFunctions.has(/* quux */)', quuxScopeDumper.innerFunctions.has(quuxDumper)); t.expect('quuxScopeDumper.innerScopes.size', quuxScopeDumper.innerScopes.size, 1); t.assert('quuxScopeDumper.innerScopes.has(/* baz.scope */)', quuxScopeDumper.innerScopes.has(bazScopeDumper)); t.expect('bazScopeDumper.innerFunctions.size', bazScopeDumper.innerFunctions.size, 1); t.assert('bazScopeDumper.innerFunctions.has(/* baz */)', bazScopeDumper.innerFunctions.has(bazDumper)); t.expect('bazScopeDumper.innerScopes.size', bazScopeDumper.innerScopes.size, 0); // Check relationship of Arguments objects and scopes recorded by survey. const quuxArgs = /** @type {!Interpreter.prototype.Arguments} */( quuxScopeDumper.scope.get('arguments')); const orphanArgs = /** @type {!Interpreter.prototype.Arguments} */( intrp.global.get('arguments')); t.expect('argumentsScopeDumpers.size', dumper.argumentsScopeDumpers.size, 1); t.assert('argumentsScopeDumpers.get(quuxArgs) === quuxScopeDumper', dumper.argumentsScopeDumpers.get(quuxArgs) === quuxScopeDumper); t.assert('argumentsScopeDumpers.get(orphanArgs) === quuxScopeDumper', dumper.argumentsScopeDumpers.get(orphanArgs) === undefined); }; /** * Unit tests for the Dumper.prototype.exprForSelector_ method. * @param {!T} t The test runner object. * @suppress {accessControls} */ exports.testDumperPrototypeExprForSelector_ = function(t) { const intrp = new Interpreter(); const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); // Test dumping a selector before and after dumping Object.getPrototypeOf. const s1 = new Selector('foo.bar{proto}.baz'); t.expect(util.format('Dumper.p.exprForSelector_(%s) // 0', s1), dumper.exprForSelector_(s1), "(new 'Object.getPrototypeOf')(foo.bar).baz"); // Give Object.getPrototypeOf a referrence indicating it is // available via the global variable myGetPrototypeOf. dumper.getObjectDumper_(/** @type {!Interpreter.prototype.Object} */ (intrp.builtins.get('Object.getPrototypeOf'))).ref = new Components(dumper.global, 'myGetPrototypeOf'); t.expect(util.format('Dumper.p.exprForSelector_(%s) // 1', s1), dumper.exprForSelector_(s1), 'myGetPrototypeOf(foo.bar).baz'); // Test dumping a selector before and after dumping Object.getOwnerOf. const s2 = new Selector('quux{owner}'); t.expect(util.format('Dumper.p.exprForSelector_(%s) // 0', s2), dumper.exprForSelector_(s2), "(new 'Object.getOwnerOf')(quux)"); // Give Object.getOwnerOf a referrence indicating it is // available via the global variable myGetOwnerOf. dumper.getObjectDumper_(/** @type {!Interpreter.prototype.Object} */ (intrp.builtins.get('Object.getOwnerOf'))).ref = new Components(dumper.global, 'myGetOwnerOf'); t.expect(util.format('Dumper.p.exprForSelector_(%s) // 1', s2), dumper.exprForSelector_(s2), 'myGetOwnerOf(quux)'); }; /** * Unit tests for the Dumper.prototype.exprForCall_ method. * @param {!T} t The test runner object. * @suppress {accessControls} */ exports.testDumperPrototypeExprForCall_ = function(t) { const intrp = new Interpreter(); const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); // Test dumping builtin calls with no arguments. Note that eval is // inserted in the global Scope at Interpreter construction time, // while escape is not. t.expect("Dumper.p.exprForCall_('eval')", dumper.exprForCall_('eval'), 'eval()'); // eval is inserted in global scope at creation. t.expect("Dumper.p.exprForCall_('escape')", dumper.exprForCall_('escape'), "(new 'escape')()"); // Test dumping builtin calls with primitive arguments. t.expect("Dumper.p.exprForCall_('eval', [true])", dumper.exprForCall_('eval', [true]), "eval(true)"); t.expect("Dumper.p.exprForCall_('eval', ['foo', 42])", dumper.exprForCall_('eval', ['foo', 42]), "eval('foo', 42)"); // Test dumping builtin calls with object arguments. t.expect("Dumper.p.exprForCall_('eval', [eval])", dumper.exprForCall_('eval', [intrp.builtins.get('eval')]), "eval(eval)"); // Test dumping builtin calls with Selector arguments. t.expect("Dumper.p.exprForCall_('eval', [new Selector('foo.bar.baz')])", dumper.exprForCall_('eval', [new Selector('foo.bar.baz')]), "eval(foo.bar.baz)"); }; /** * Tests for the Dumper.prototype.dumpBinding method, and by * implication most of ScopeDumper and ObjectDumper. * @param {!T} t The test runner object. */ exports.testDumperPrototypeDumpBinding = function(t) { /** @type {string} Common minimal init src for all testcases. */ const common = "var Object = new 'Object';\n" + ['defineProperty', 'create', 'preventExtensions', 'setPrototypeOf', 'setOwnerOf', 'prototype'].map( (member) => ` Object.${member} = new 'Object.${member}'; Object.defineProperty(Object, '${member}', {enumerable: false}); `).join(''); /** * @type {!Array<{src: string, * prune: (!Array<(string|number)>|undefined), * pruneRest: (!Array<(string|number)>|undefined), * skip: (!Array<(string|number)>|undefined), * set: (!Array<(string|number)>|undefined), * dump: (!Array<(string|number)>|undefined), * after: (!Array<(string|number)>|undefined)}>} */ const cases = [ { // Test basics: DECL/SET/ATTR/DONE/RECURSE for variables and properties. title: 'basics', src: ` var prune = 'not dumped'; var skip = 'skipped'; var obj = {a: {x: 1}, b: 2, c: 3, u: undefined, skip: 'skipped', prune: 'not dumped'}; Object.defineProperty(obj, 'a', {enumerable: false}); `, prune: ['prune', 'obj.prune'], skip: ['skip', 'obj.skip'], set: ['Object', 'Object.setPrototypeOf', 'Object.defineProperty'], dump: [ // [ selector, todo, expected output, expected done (default: todo) ] // Order matters. ['prune', Do.SET, '', Do.UNSTARTED], ['skip', Do.SET, "var skip = 'skipped';\n", Do.RECURSE], ['obj', Do.DECL, 'var obj;\n'], ['obj', Do.SET, 'obj = {};\n', Do.DONE], ['obj.a', Do.DECL, 'obj.a = undefined;\n'], ['obj.a', Do.SET, 'obj.a = {};\n'], ['obj.a', Do.ATTR, "Object.defineProperty(obj, 'a', {enumerable: false});\n"], ['obj.a', Do.RECURSE, 'obj.a.x = 1;\n'], ['obj.b', Do.SET, 'obj.b = 2;\n', Do.RECURSE], ['obj.u', Do.DECL, 'obj.u = undefined;\n', Do.RECURSE], ['obj', Do.RECURSE, 'obj.c = 3;\n', Do.DONE], ['obj.prune', Do.SET, '', Do.UNSTARTED], ['obj.skip', Do.SET, "obj.skip = 'skipped';\n", Do.RECURSE], ['obj', Do.RECURSE, ''], ], after: [ // [ selector, expected done ] ['obj^', Do.RECURSE], ['obj.c', Do.RECURSE], ], }, { // Test the skipBinding option. title: 'skipBinding', src: ` var obj = {a: 'a', b: 'b'}; Object.setPrototypeOf(obj, {}); `, set: ['Object', 'Object.setPrototypeOf'], dump: [ ['obj', Do.RECURSE, "var obj = {};\nobj.a = 'a';\n", Do.DONE, {skipBindings: ['b', Selector.PROTOTYPE]}], ['obj', Do.RECURSE, 'Object.setPrototypeOf(obj, {});\n' + "obj.b = 'b';\n", Do.RECURSE, {skipBindings: []}], ], }, { // Test simple recursion with pruning. title: 'recursion-simple', src: ` var obj = {a: {id: 'a'}, b: {id: 'b'}, c: {id: 'c'}}; Object.setPrototypeOf(obj.c, {id: 'd'}); `, // Mark obj.b.id to be pruned, and pruneRest of obj.c. prune: ['obj.b.id'], pruneRest: ['obj.c'], dump: [ ['obj', Do.RECURSE, 'var obj = {};\n' + "obj.a = {};\n" + "obj.a.id = 'a';\n" + 'obj.b = {};\n' + 'obj.c = {};\n' + "(new 'Object.setPrototypeOf')(obj.c, {});\n" + "(new 'Object.getPrototypeOf')(obj.c).id = 'd';\n"], ], after: [ ['obj.a', Do.RECURSE], ['obj.a.id', Do.RECURSE], ['obj.b', Do.RECURSE], ['obj.b.id', Do.UNSTARTED], ['obj.c', Do.RECURSE], ['obj.c.id', Do.UNSTARTED], ], }, { // Test recursion in face of cyclic data and incomplet(able) properties. title: 'recursion-incompletable', src: ` var obj = {a: {id: 'a'}, b: {id: 'b'}, c: {id: 'c'}}; obj.a.self = obj.a; obj.b.self = obj.b; obj.c.parent = obj; `, // Mark obj.b.id to be skipped and obj.c.id to be pruned; // attempting to dump obj recursively should be leave obj.a as // RECUSE, obj.b and obj.c as DONE, and obj.a.id still // UNSTARTED. obj.c left at DONE. prune: ['obj.c.id'], skip: ['obj.b.id'], dump: [ ['obj', Do.RECURSE, // TODO(cpcallen): really want "var obj = {a: {id: 'a'}, ...". 'var obj = {};\n' + "obj.a = {};\nobj.a.id = 'a';\nobj.a.self = obj.a;\n" + 'obj.b = {};\nobj.b.self = obj.b;\n' + "obj.c = {};\nobj.c.parent = obj;\n", Do.DONE], ], after: [ ['obj.a', Do.RECURSE], ['obj.a.self', Do.RECURSE], ['obj.a.id', Do.RECURSE], ['obj.b', Do.DONE], ['obj.b.self', Do.DONE], ['obj.b.id', Do.UNSTARTED], ['obj.c', Do.DONE], ['obj.c.id', Do.UNSTARTED], ['obj.c.parent', Do.DONE], ], }, { // Test recursion that tries to revisit starting object. title: 'recursion-revist', src: ` var obj = {v: 42}; obj.obj = obj; `, dump: [ ['obj', Do.DONE, 'var obj = {};\n'], // TODO(cpcallen): might prefer '...obj.v = 42\n'. ['obj.obj', Do.RECURSE, 'obj.obj = obj;\nobj.obj.v = 42;\n'], ['obj', Do.RECURSE, ''], ], after: [ ['obj.v', Do.RECURSE], ], }, { // Test recursion, limited by subtree. title: 'recursion-treeOnly', src: ` var outsider = {iam: 'outsider'}; var obj = { foo: [outsider, {iam: 'insider'}], bar: {iam: 'bar'}, }; obj.foo[2] = obj.bar; `, set: ['obj'], dump: [ ['obj.foo', Do.RECURSE, 'obj.foo = [];\n' + 'obj.foo[0] = {};\n' + "obj.foo[1] = {};\nobj.foo[1].iam = 'insider';\n" + 'obj.foo[2] = {};\n', Do.DONE, {treeOnly: true}], ['obj', Do.RECURSE, "obj.bar = obj.foo[2];\nobj.bar.iam = 'bar';\n", Do.DONE, {treeOnly: true}], ['obj', Do.RECURSE, "obj.foo[0].iam = 'outsider';\n", Do.RECURSE, {treeOnly: false}], ], }, { // Test dumping property attributes. title: 'attributes', src: ` var obj = {w: {}, e: {}, c: {}}; Object.defineProperty(obj, 'w', {writable: false}); Object.defineProperty(obj, 'e', {enumerable: false}); Object.defineProperty(obj, 'c', {configurable: false}); `, set: ['Object', 'obj'], dump: [ ['obj.w', Do.ATTR, "obj.w = {};\n" + "(new 'Object.defineProperty')(obj, 'w', {writable: false});\n"], ['Object.defineProperty', Do.SET, "Object.defineProperty = new 'Object.defineProperty';\n"], ['obj.e', Do.ATTR, "obj.e = {};\n" + "Object.defineProperty(obj, 'e', {enumerable: false});\n"], ['obj.c', Do.ATTR, "obj.c = {};\n" + "Object.defineProperty(obj, 'c', {configurable: false});\n"], ], }, { // Test correct dumping inherited-non-writable properties. title: 'non-writable', src: ` var parent = {foo: 0}; var child = []; for (var i = 0; i <= 4; i++) { child[i] = Object.create(parent); child[i].foo = i; } child[4].foo = undefined; // Will have DECL do SET implicitly. // Make it impossible to set child[i].foo by assignment. Object.defineProperty(parent, 'foo', {writable: false}); `, // Object.create is polyfilled; dumper won't call polyfill. set: ['Object', 'Object.defineProperty', 'parent', 'child', 'child[0]', 'child[1]', 'child[2]', 'child[3]', 'child[4]'], dump: [ // Inherited non-writable property doesn't exist yet. ['child[0].foo', Do.SET, 'child[0].foo = 0;\n', Do.RECURSE], ['parent', Do.RECURSE, 'parent.foo = 0;\n' + "Object.defineProperty(parent, 'foo', {writable: false});\n"], ['child[1].foo', Do.DECL, "Object.defineProperty(child[1], 'foo', " + '{writable: true, enumerable: true, configurable: true});\n'], ['child[1].foo', Do.SET, "child[1].foo = 1;\n", Do.RECURSE], ['child[2].foo', Do.SET, "Object.defineProperty(child[2], 'foo', " + '{writable: true, enumerable: true, configurable: true,' + ' value: 2});\n', Do.RECURSE], ['child[3].foo', Do.ATTR, "Object.defineProperty(child[3], 'foo', " + '{writable: true, enumerable: true, configurable: true,' + ' value: 3});\n', Do.RECURSE], ['child[4].foo', Do.DECL, "Object.defineProperty(child[4], 'foo', " + '{writable: true, enumerable: true, configurable: true});\n', Do.RECURSE], ], after: [ ['child[0]^', Do.DONE, 'parent'], ['child[1]^', Do.DONE, 'parent'], ['child[2]^', Do.DONE, 'parent'], ['child[3]^', Do.DONE, 'parent'], ['child[4]^', Do.DONE, 'parent'], ], }, { // Test dumping {proto} bindings. title: '{proto}', src: ` var parent = {}; var child0 = Object.create(parent); var child1 = Object.create(parent); var child2 = Object.create(parent); var child3 = Object.create(parent); `, set: ['Object'], // N.B.: Object.create is polyfilled. dump: [ ['child0', Do.DONE, 'var child0 = {};\n'], ['child1', Do.DONE, 'var child1 = {};\n'], ['child2', Do.DONE, 'var child2 = {};\n'], ['parent', Do.DONE, 'var parent = {};\n'], ['child3', Do.DONE, "var child3 = (new 'Object.create')(parent);\n"], ['child1^', Do.SET, "(new 'Object.setPrototypeOf')(child1, parent);\n", Do.DONE], ['Object.setPrototypeOf', Do.SET, "Object.setPrototypeOf = new 'Object.setPrototypeOf';\n"], ['child2^', Do.SET, 'Object.setPrototypeOf(child2, parent);\n', Do.DONE], ], after: [ ['child0^', Do.DECL], ['child1^', Do.DONE, 'parent'], ['child2^', Do.DONE, 'parent'], ['child3^', Do.DONE, 'parent'], ] }, { // Test dumping {proto} bindings: null-protoype objects. title: 'null {proto}', src: ` var objs = {obj: {}, fun: function() {}, arr: []}; for (var p in objs) { Object.setPrototypeOf(objs[p], null); } `, set: ['Object', 'Object.setPrototypeOf', 'objs'], dump: [ ['objs.obj', Do.DONE, "objs.obj = (new 'Object.create')(null);\n"], ['objs.obj{proto}', Do.DONE, '', Do.RECURSE], ['objs.fun', Do.DONE, 'objs.fun = function() {};\n'], ['objs.fun{proto}', Do.SET, 'Object.setPrototypeOf(objs.fun, null);\n', Do.RECURSE], ['objs.arr', Do.DONE, 'objs.arr = [];\n'], ['objs.arr{proto}', Do.SET, 'Object.setPrototypeOf(objs.arr, null);\n', Do.RECURSE], ], }, { // Test dumping {owner} bindings. title: '{owner}', src: ` var CC = {}; CC.root = new 'CC.root'; var setPerms = new 'setPerms'; var alice = {}; alice.thing = (function() {setPerms(alice); return {};})(); var bob = {}; bob.thing = {}; Object.setOwnerOf(bob.thing, bob); var unowned = {}; Object.setOwnerOf(unowned, null); `, set: ['Object', 'CC', 'CC.root'], dump: [ ['alice', Do.DONE, 'var alice = {};\n'], ['alice.thing', Do.DONE, 'alice.thing = {};\n'], ['alice.thing{owner}', Do.SET, "(new 'Object.setOwnerOf')" + '(alice.thing, alice);\n', Do.DONE], ['Object.setOwnerOf', Do.SET, "Object.setOwnerOf = new 'Object.setOwnerOf';\n"], ['bob', Do.RECURSE, 'var bob = {};\nbob.thing = {};\n' + "Object.setOwnerOf(bob.thing, bob);\n"], ['unowned', Do.SET, 'var unowned = {};\n', Do.DONE], ['unowned{owner}', Do.SET, 'Object.setOwnerOf(unowned, null);\n', Do.RECURSE], ], after: [ ['alice', Do.DONE], ['alice{owner}', Do.DONE, 'CC.root'], ['alice.thing{owner}', Do.DONE, 'alice'], ['bob', Do.RECURSE], ['bob{owner}', Do.RECURSE, 'CC.root'], ['bob.thing{owner}', Do.RECURSE, 'bob'], ], }, { // Test dumping extensibility (with related recursion tests). title: 'extensibility', src: ` var other = {id: 'other'}; var obj1 = {id: 1}; var obj2 = {id: 2}; var obj3 = {id: 3, other: other}; Object.preventExtensions(obj1); Object.preventExtensions(obj2); Object.preventExtensions(obj3); `, set: ['Object', 'obj1', 'obj2', 'obj3'], dump: [ ['obj1.id', Do.SET, 'obj1.id = 1;\n', Do.RECURSE], ['obj1', Do.RECURSE, "(new 'Object.preventExtensions')(obj1);\n"], ['Object.preventExtensions', Do.SET, "Object.preventExtensions = new 'Object.preventExtensions';\n",], // Verify property set before extensibility prevented. ['obj2', Do.RECURSE, 'obj2.id = 2;\nObject.preventExtensions(obj2);\n'], // Verify treeOnly doesn't prevent .preventExtensions being called. ['obj3', Do.RECURSE, 'obj3.id = 3;\nobj3.other = {};\n' + 'Object.preventExtensions(obj3);\n', Do.DONE, {treeOnly: true}], // Verify we don't call .preventExtensions more than once. ['obj3', Do.RECURSE, "obj3.other.id = 'other';\n", Do.RECURSE, {treeOnly: false}], ], }, { // Test dumping null variables. // (See https://github.com/google/CodeCity/pull/371/files#r429566592) title: 'null variable', src: 'var n = null;', dump: [ ['n', Do.SET, 'var n = null;\n', Do.RECURSE], ], }, { // Test (not) dumping immutable bindings in the global scope. title: 'immutables', dump: [ ['NaN', Do.RECURSE, ''], ['Infinity', Do.RECURSE, ''], ['undefined', Do.RECURSE, ''], ['eval', Do.RECURSE, ''], ], }, { // Test dumping Function objects. title: 'Function', src: ` var Function = new 'Function'; function f1(arg) {} var f2 = function F2(arg) {}; var obj = {f3: function() {}}; var f4 = new Function('a1', 'a2,a3', 'a4, a5', ''); `, set: ['obj'], dump: [ // BUG(cpcallen): Really want 'function f1(arg) {};\n'. ['f1', Do.SET, 'var f1 = function f1(arg) {};\n', Do.DONE], // BUG(cpcallen): this causes a crash. // ['f1', Do.RECURSE, '', Do.RECURSE], ['f2', Do.SET, 'var f2 = function F2(arg) {};\n', Do.DONE], ['obj.f3', Do.SET, 'obj.f3 = function() {};\n', Do.DONE], // BUG(cpcallen): Really want '... = Function(...', due to scoping. ['f4', Do.SET, 'var f4 = function anonymous(a1,a2,a3,a4, a5\n) {\n\n};\n', Do.DONE], // TODO(ES5): verify that f4.name gets deleted. ], after: [ ['f1^', Do.DONE], ['f1.length', Do.RECURSE], ['f1.name', Do.RECURSE], ['f1.prototype', Do.DONE, 'f1.prototype'], ['f1.prototype.constructor', Do.DONE, 'f1'], ['f2^', Do.DONE], ['f2.length', Do.RECURSE], ['f2.name', Do.RECURSE], ['f2.prototype', Do.DONE, 'f2.prototype'], ['f2.prototype.constructor', Do.DONE, 'f2'], ['obj.f3^', Do.DONE], ['obj.f3.length', Do.RECURSE], ['obj.f3.name', Do.UNSTARTED], // N.B.: not implicitly set. ['obj.f3.prototype', Do.DONE, 'obj.f3.prototype'], ['obj.f3.prototype.constructor', Do.DONE, 'obj.f3'], ['f4^', Do.DONE], // TODO(ES6): verify that f4.name is implicitly set to 'anonymous'. ['f4.length', Do.RECURSE], ['f4.prototype', Do.DONE, 'f4.prototype'], ['f4.prototype.constructor', Do.DONE, 'f4'], ], }, { // Test Function objects with usable and unusable .prototype // objects. Note that we don't need to worry about the // attributes of the .prototype property, because a function // object's .prototype is always non-configurable. title: 'Function .prototype', src: ` var f1 = function() {}; var f2 = function() {}; var f3 = function() {}; var obj1 = f1.prototype; var obj2 = f2.prototype; f3.prototype = []; `, set: ['Object', 'Object.defineProperty'], dump: [ // No problem if f1 dumped before obj1. ['f1', Do.RECURSE, 'var f1 = function() {};\n'], ['obj1', Do.DONE, 'var obj1 = f1.prototype;\n'], // Surmountable difficulty if obj2 dumped before f2. ['obj2', Do.DONE, 'var obj2 = {};\n'], ['f2', Do.DONE, 'var f2 = function() {};\n'], ['f2.prototype', Do.DONE, 'f2.prototype = obj2;\n'], ['f2', Do.RECURSE, 'f2.prototype.constructor = f2;\n' + "Object.defineProperty(f2.prototype, 'constructor', " + '{enumerable: false});\n'], // Non-plain-Object .protype values require special handling too. ['f3', Do.DONE, 'var f3 = function() {};\n'], ['f3', Do.RECURSE, 'f3.prototype = [];\n'], ], after: [ ['obj1', Do.DONE, 'obj1'], // Var not RECURSEed (only object). ['f1.prototype', Do.RECURSE, 'obj1'], ['f1.prototype.constructor', Do.RECURSE, 'f1'], ['f2.prototype', Do.RECURSE, 'obj2'], ['f2.prototype.constructor', Do.RECURSE, 'f2'], ], }, { // Test dumping Function objects' .prototype.constructor property. title: 'Function .prototype.constructor', src: ` var f1 = function() {}; var f2 = function() {}; var f3 = function() {}; Object.defineProperty(f2.prototype, 'constructor', {enumerable: true}); Object.defineProperty(f3.prototype, 'constructor', {writable: false, value: 42}); `, set: ['Object', 'Object.defineProperty', 'f1', 'f2', 'f3'], dump: [ ['f3.prototype', Do.DONE, ''], ['f3.prototype.constructor', Do.SET, 'f3.prototype.constructor = 42;\n'], ['f3.prototype', Do.RECURSE, 'Object.defineProperty(f3.prototype, ' + "'constructor', {writable: false});\n"], ], after: [ ['f1.prototype.constructor', Do.DONE], ['f2.prototype.constructor', Do.SET], ], }, { // Test dumping Function objects' .name property. title: 'Function .name', src: ` var f1 = function() {}; var f2 = function() {}; Object.defineProperty(f1, 'name', {value: 'Hi!'}); delete f2.name; `, set: ['Object', 'Object.defineProperty', 'f1', 'f2'], dump: [ ['f1', Do.RECURSE, "Object.defineProperty(f1, 'name', " + "{value: 'Hi!'});\n"], ['f2', Do.RECURSE, 'delete f2.name;\n'], ], }, { // Test dumping Array objects. title: 'Array', src: ` var Array = new 'Array'; var obj = {}; var arr = [42, 69, 105, obj, {}]; var sparse = [0, , 2]; Object.setPrototypeOf(sparse, null); sparse.length = 4; `, set: ['Object', 'Object.setPrototypeOf', 'obj'], dump: [ // TODO(cpcallen): really want 'var arr = [42, 69, 105, obj, {}];\n'. ['arr', Do.RECURSE, 'var arr = [];\narr[0] = 42;\narr[1] = 69;\n' + 'arr[2] = 105;\narr[3] = obj;\narr[4] = {};\n'], // TODO(cpcallen): really want something like // 'var sparse = [0, , 2];\nsparse.length = 4;'. ['sparse', Do.RECURSE, 'var sparse = [];\n' + 'Object.setPrototypeOf(sparse, null);\n' + 'sparse[0] = 0;\nsparse[2] = 2;\nsparse.length = 4;\n'], ], after: [ ['arr^', Do.RECURSE], ['arr.length', Do.RECURSE], ['sparse^', Do.RECURSE], ['sparse.length', Do.RECURSE], ], }, { // Test dumping Date objects. title: 'Date', src: ` var Date = new 'Date'; var date1 = new Date('1975-07-27'); var date2 = new Date('1979-01-04'); `, dump: [ ['date1', Do.SET, "var date1 = new (new 'Date')('1975-07-27T00:00:00.000Z');\n", Do.DONE], ['Date', Do.SET, "var Date = new 'Date';\n", Do.DONE], ['date2', Do.SET, "var date2 = new Date('1979-01-04T00:00:00.000Z');\n", Do.DONE], ], after: [ ['date1^', Do.DONE], ['date2^', Do.DONE], ], }, { // Test dumping RegExp objects. title: 'RegExp', src: ` var RegExp = new 'RegExp'; var re0 = new RegExp(); var re1 = /foo/ig; var re2 = /bar/g; Object.setPrototypeOf(re2, re1); re2.lastIndex = 42; var re3 = /baz/m; Object.setPrototypeOf(re3, re1); `, set: ['Object', 'Object.setPrototypeOf'], dump: [ ['re0', Do.SET, 'var re0 = /(?:)/;\n', Do.DONE], ['re1', Do.SET, 'var re1 = /foo/gi;\n', Do.DONE], ['re2', Do.RECURSE, 'var re2 = /bar/g;\n' + 'Object.setPrototypeOf(re2, re1);\n' + 're2.lastIndex = 42;\n'], ['re3', Do.SET, 'var re3 = /baz/m;\n', Do.DONE], ['re3^', Do.SET, 'Object.setPrototypeOf(re3, re1);\n', Do.DONE], ], after: [ ['re1^', Do.RECURSE], ['re1.source', Do.RECURSE], ['re1.global', Do.RECURSE], ['re1.ignoreCase', Do.RECURSE], ['re1.multiline', Do.RECURSE], ['re1.lastIndex', Do.RECURSE], ['re2^', Do.RECURSE, 're1'], ['re2.source', Do.RECURSE], ['re2.global', Do.RECURSE], ['re2.ignoreCase', Do.RECURSE], ['re2.multiline', Do.RECURSE], ['re2.lastIndex', Do.RECURSE], ['re3^', Do.DONE, 're1'], ['re3.source', Do.RECURSE], ['re3.global', Do.RECURSE], ['re3.ignoreCase', Do.RECURSE], ['re3.multiline', Do.RECURSE], ['re3.lastIndex', Do.RECURSE], ], }, { // Test dumping Error objects. title: 'Error', src: ` var Error = new 'Error'; var TypeError = new 'TypeError'; var RangeError = new 'RangeError'; var error1 = new Error('message1'); error1.stack = 'stack1'; // Because it's otherwise kind of random. var error2 = new TypeError('message2'); error2.stack = 'stack2'; var error3 = new RangeError(); Object.setPrototypeOf(error3, error1); error3.message = 69; Object.defineProperty(error3, 'message', {writable: false}); delete error3.stack; `, set: ['Object', 'Object.defineProperty', 'Object.setPrototypeOf'], dump: [ ['error1', Do.SET, "var error1 = new (new 'Error')('message1');\n", Do.DONE], ['error1', Do.RECURSE, "error1.stack = 'stack1';\n"], ['Error', Do.SET, "var Error = new 'Error';\n", Do.DONE], ['TypeError', Do.SET, "var TypeError = new 'TypeError';\n", Do.DONE], ['RangeError', Do.SET, "var RangeError = new 'RangeError';\n", Do.DONE], ['error2', Do.SET, "var error2 = new TypeError('message2');\n", Do.DONE], ['error2', Do.RECURSE, "error2.stack = 'stack2';\n"], ['error3', Do.SET, 'var error3 = new Error();\n', Do.DONE], ['error3.message', Do.ATTR, 'error3.message = 69;\n' + "Object.defineProperty(error3, 'message', {writable: false});\n", Do.RECURSE], ['error3', Do.RECURSE, 'delete error3.stack;\n' + 'Object.setPrototypeOf(error3, error1);\n'], ], after: [ ['error1.message', Do.RECURSE], ['error2.message', Do.RECURSE], ], }, { // Test dumping WeakMap objects. title: 'WeakMap', src: ` var WeakMap = new 'WeakMap'; var Object = new 'Object'; Object.setPrototypeOf = new 'Object.setPrototypeOf'; var wm1 = new WeakMap(); var wm2 = new WeakMap(); Object.setPrototypeOf(wm2, null); `, set: ['Object', 'Object.setPrototypeOf'], dump: [ ['wm1', Do.SET, "var wm1 = new (new 'WeakMap')();\n", Do.DONE], ['WeakMap', Do.SET, "var WeakMap = new 'WeakMap';\n", Do.DONE], ['wm2', Do.SET, 'var wm2 = new WeakMap();\n', Do.DONE], ], after: [ ['wm1^', Do.DONE], ['wm2^', Do.DECL], ], }, { // Test dumping builtin objects. title: 'Builtins', src: '', dump: [ ['Object', Do.DONE, "var Object = new 'Object';\n"], ['Object.prototype', Do.SET, "Object.prototype = new 'Object.prototype';\n"], ], }, ]; for (const tc of cases) { const prefix = 'dumpBinding: ' + tc.title + ': '; // Create Interprerter and objects to dump. Run minimal common // init then any testcase-specific init source. const intrp = new Interpreter(); intrp.createThreadForSrc(common); if (tc.src) intrp.createThreadForSrc(tc.src); intrp.run(); // Create Dumper with pristine Interpreter instance to compare to. // Supply treeOnly: false because most tests were written before // this option was created (and made to default to true). const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp, {treeOnly: false}); // Set a few object .done flags in advance, to limit recursive // dumping of builtins in tests. for (const builtin of [intrp.OBJECT, intrp.FUNCTION, intrp.ARRAY, intrp.REGEXP, intrp.ERROR, intrp.TYPE_ERROR, intrp.RANGE_ERROR, intrp.ROOT]) { /** @suppress {accessControls} */ dumper.getObjectDumper_(builtin).done = ObjectDumper.Done.DONE_RECURSIVELY; }; // Set a few binding .done flags in advance to simulate things // already being dumped or being marked for deferred dumping. for (const ss of tc.prune || []) { dumper.prune(new Selector(ss)); } for (const ss of tc.pruneRest || []) { dumper.pruneRest(new Selector(ss)); } for (const ss of tc.skip || []) { dumper.skip(new Selector(ss)); } for (const ss of tc.set || []) { dumper.dumpBinding(new Selector(ss), Do.SET); } // Check generated output for (and post-dump status of) specific bindings. for (const [ss, todo, expected, done, options] of tc.dump || []) { const s = new Selector(ss); // Dump binding and check output code. const result = new MockWritable(); if (options) dumper.setOptions(options); dumper.setOptions({output: result}); dumper.unskip(s); dumper.dumpBinding(s, todo); t.expect(util.format('%sDumper.p.dumpBinding(<%s>, %o)', prefix, s, todo), String(result), expected); // Check work recorded. /** @suppress {accessControls} */ const {dumper: d, part} = dumper.getComponentsForSelector_(s); t.expect(util.format('%sBinding status of <%s> (after dump)', prefix, s), d.getDone(part), done === undefined ? todo : done); } // Check status of (some of the) additional bindings that will be // set implicitly as a side effect of the code generated above, and // that their values have the expected references (where // object-valued and already dumped). // // TODO(cpcallen): The value checks are NOT checking the dumped // value (or even, for .proto, the internal record of the current // value), but instead just the preferred selector for the actual // value in interp2. That's not really too useful, so maybe they // should be removed. for (const [ss, done, valueSelector] of tc.after || []) { const s = new Selector(ss); /** @suppress {accessControls} */ const {dumper: d, part} = dumper.getComponentsForSelector_(s); t.expect(util.format('%sbinding status of <%s> (implicit)', prefix, s), d.getDone(part), done); if (valueSelector) { const objDumper = dumper.getDumperFor(ss); t.expect(util.format('%sref for %s', prefix, s), objDumper.getSelector(/*preferred=*/true).toString(), valueSelector); } } } }; /** * Unit tests for Dumper.prototype.warn * @param {!T} t The test runner object. */ exports.testDumperPrototypeWarn = function(t) { const intrp = new Interpreter(); const dumper = new Dumper(intrp, intrp); const output = new MockWritable(); dumper.setOptions({output: output}); dumper.warn('1'); dumper.warn('2\n'); dumper.indent = ' '; dumper.warn('3\n4'); t.expect('Dumper.prototype.warn(...) output', String(output), '// 1\n// 2\n // 3\n // 4\n'); }; /** * Tests for the ScopeDumper.prototype.dump method. * @param {!T} t The test runner object. */ exports.testScopeDumperPrototypeDump = function(t) { const intrp = new Interpreter(); // Create various variables to dump. intrp.createThreadForSrc(` var value = 42; var obj = (new 'Object.create')(null); obj.prop = 69; `); intrp.run(); // Create Dumper with pristine Interpreter instance to compare to; // get ScopeDumper for global scope. const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); /** @suppress {accessControls} */ const globalDumper = dumper.getScopeDumper_(intrp.global); // Set a few object .done flags in advance, to limit recursive // dumping of builtins in tests. // TODO(cpcallen): this is a temporary hack while refactoring // recursion out of SubDumper.p.dumpBinding; remove once that // refactor is done. for (const builtin of [intrp.OBJECT, intrp.FUNCTION, intrp.ARRAY, intrp.REGEXP, intrp.ERROR, intrp.TYPE_ERROR, intrp.RANGE_ERROR, intrp.ROOT]) { /** @suppress {accessControls} */ dumper.getObjectDumper_(builtin).done = ObjectDumper.Done.DONE_RECURSIVELY; }; // Dump one binding and check result. let result = new MockWritable(); dumper.setOptions({output: result}); globalDumper.dumpBinding(dumper, 'obj', Do.SET); t.expect("ScopeDumper.p.dumpBinding(..., 'obj', Do.SET, ...) outputs", String(result), "var obj = (new 'Object.create')(null);\n"); // Dump the rest & check result. dumper.setOptions({output: (result = new MockWritable())}); globalDumper.dump(dumper); t.expect('ScopeDumper.p.dump(...) outputs', String(result), 'var value = 42;\nobj.prop = 69;\n'); }; /** * Unit tests for Dumper.prototype.dump. These need to be async * because connectionListen is (under the covers). * @param {!T} t The test runner object. */ exports.testDumperPrototypeDump = async function(t) { const intrp = new Interpreter({noLog: ['net']}); // Create a NativeFuction called "continue" that can be used to // resolve awaited Promises. (Don't add it to the global scope, as // doing so causes dump errors because it's not present in a // pristine Interpreter instance.) // TODO(cpcallen): consider abstracting test machinery into a // runAsyncDumpTest function? let resolve; intrp.createNativeFunction('continue', () => {resolve();}, false); // Create a variable and two listening sockets to dump. intrp.createThreadForSrc(` var listener = {onRecieve: function onRecieve(data) {}}; (new 'CC.connectionListen')(8888, listener, 100); (new 'CC.connectionListen')(8889, listener); (new 'continue')(); `); intrp.start(); await new Promise((res, rej) => {resolve = res;}); // Wait for continue(). intrp.pause(); // Create Dumper with pristine Interpreter instance to compare to. const pristine = new Interpreter(); const dumper = new Dumper(pristine, intrp); const output = new MockWritable(); dumper.setOptions({output: output}); dumper.dump(); t.expect('Dumper.p.dump(...) outputs', String(output), 'var listener = {};\n' + 'listener.onRecieve = function onRecieve(data) {};\n' + "(new 'CC.connectionListen')(8888, listener, 100);\n" + "(new 'CC.connectionListen')(8889, listener);\n"); // Clean up. intrp.createThreadForSrc(` (new "CC.connectionUnlisten")(8888); (new "CC.connectionUnlisten")(8889); (new 'continue')(); `); intrp.start(); await new Promise((res, rej) => {resolve = res;}); // Wait for continue(). intrp.stop(); }; ================================================ FILE: server/tests/interpreter_bench.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Benchmarks for JavaScript interpreter. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const util = require('util'); const Interpreter = require('../interpreter'); const getInterpreter = require('./interpreter_common').getInterpreter; const testcases = require('./testcases'); /** * Run a benchmark of the interpreter. * @param {!B} b The benchmark runner object. * @param {string} name The name of the test. * @param {string} setup Source to be evaled to set up benchmark environment. * @param {string} timed Source to be evaled and timed. */ function runBench(b, name, setup, timed) { for (let i = 0; i < 4; i++) { const interpreter = getInterpreter(); const err = undefined; try { interpreter.createThreadForSrc(setup); interpreter.run(); interpreter.createThreadForSrc(timed); b.start(name, i); interpreter.run(); b.end(name, i); } catch (err) { b.crash(name, util.format('%s\n%s\n%s', setup, timed, err.stack)); } } }; /** * Run the fibbonacci10k benchmark. * @param {!B} b The test runner object. */ exports.benchFibbonacci10k = function(b) { const name = 'fibonacci10k'; const setup = ` var fibonacci = function(n, output) { var a = 1, b = 1, sum; for (var i = 0; i < n; i++) { output.push(a); sum = a + b; a = b; b = sum; } }`; const timed = ` for(var i = 0; i < 10000; i++) { var result = []; fibonacci(78, result); } result; `; runBench(b, name, setup, timed); }; /** * Run some benchmarks of Array.prototype.sort. * @param {!B} b The test runner object. */ exports.benchSort = function(b) { for (const len of [10, 100, 1000, 10000]) { const name = 'sort ' + len; const setup = ` var arr = []; for (var i = 0; i < ${len}; i++) { arr.push(Math.floor(Math.random() * ${len})); }`; const timed = ` arr.sort(function(a, b) {return a - b;}); `; runBench(b, name, setup, timed); } }; ================================================ FILE: server/tests/interpreter_common.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Load polyfills for tests. * @author fraser@google.com (Neil Fraser) */ 'use strict'; const fs = require('fs'); const Interpreter = require('../interpreter'); exports.startupFiles = { es5: fs.readFileSync('startup/es5.js', 'utf8'), es6: fs.readFileSync('startup/es6.js', 'utf8'), es7: fs.readFileSync('startup/es7.js', 'utf8'), esx: fs.readFileSync('startup/esx.js', 'utf8'), cc: fs.readFileSync('startup/cc.js', 'utf8'), }; /** * Create an initialize an Interpreter instance. * @param {!Interpreter.Options=} options Interpreter constructor * options. (Default: see implementation.) * @param {boolean=} init Load the standard startup files? (Default: true.) * @return {!Interpreter} */ exports.getInterpreter = function(options, init) { var intrp = new Interpreter(options); if (init || init === undefined) { for (const file of Object.values(exports.startupFiles)) { intrp.createThreadForSrc(file); intrp.run(); } } return intrp; } ================================================ FILE: server/tests/interpreter_test.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Tests for JavaScript interpreter. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const http = require('http'); const net = require('net'); const util = require('util'); const Interpreter = require('../interpreter'); const {getInterpreter} = require('./interpreter_common'); const Parser = require('../parser').Parser; const {T} = require('./testing'); const testcases = require('./testcases'); /////////////////////////////////////////////////////////////////////////////// // Test helper functions. /////////////////////////////////////////////////////////////////////////////// // Prepare static interpreter instance for runSimpleTest. const interpreter = getInterpreter(); interpreter.global.createMutableBinding('src'); /** * Run a simple test of the interpreter. A single, shared Interpreter * instance is used by all tests executed by this function, but eval * is used to evaluate src in its own scope. The supplied src must * not modify objects accessible via the global scope! * @param {!T} t The test runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled. * @param {number|string|boolean|null|undefined} expected The expected * completion value. */ function runSimpleTest(t, name, src, expected) { let thread; try { interpreter.setValueToScope(interpreter.global, 'src', src); thread = interpreter.createThreadForSrc('eval(src);').thread; interpreter.run(); } catch (e) { t.crash(name, util.format('%s\n%s', src, e.stack)); return; } const r = interpreter.pseudoToNative(thread.value); t.expect(name, r, expected, src); } /** * Run a test of the interpreter using an independent Interpreter * instance, which may be created with non-default options and/or * without the standard startup files, and during which various * callbacks will be executed; see TestOptions for details. * (Simulated) time will be automatically fast-forwarded as required * to wake sleeping threads. * @param {!T} t The test runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled. * @param {number|string|boolean|null|undefined} expected The expected * completion value. * @param {!TestOptions=} options Custom test options. */ function runTest(t, name, src, expected, options) { options = options || {}; const intrp = getInterpreter(options.options, options.standardInit); if (options.onCreate) { options.onCreate(intrp); } let thread; try { thread = intrp.createThreadForSrc(src).thread; if (options.onCreateThread) { options.onCreateThread(intrp, thread); } let runResult; while ((runResult = intrp.run())) { if (runResult > 0) { // Sleeping thread(s). // Fast forward to wake-up time. Cast to defeat @private check. /** @type {?} */(intrp).previousTime_ += runResult; } else { // Blocked thread(s). if (options.onBlocked) { options.onBlocked(intrp); } } } } catch (e) { t.crash(name, util.format('%s\n%s', src, e.stack)); return; } const r = intrp.pseudoToNative(thread.value); t.expect(name, r, expected, src); } /** * Run a (truly) asynchronous test of the interpreter. A new * Interpreter instance is created for each test. Special functions * resolve() and reject() are inserted in the global scope; they will * end the test. If resolve() is called the test will end normally * and the argument supplied will be compared with the expected value; * if reject() is called the test will instead be treated as a * failure. * @param {!T} t The test runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled. * @param {number|string|boolean|null|undefined} expected The expected * completion value. * @param {!TestOptions=} options Custom test options. Note that * 'onBlocked' is ignored because the interpreter is .start()ed * instead of .run() being called directly. */ async function runAsyncTest(t, name, src, expected, options) { options = options || {}; const intrp = getInterpreter(options.options, options.standardInit); if (options.onCreate) { options.onCreate(intrp); } // Create promise to signal completion of test from within // interpreter. Awaiting p will block until resolve or reject is // called. let resolve, reject, result; const p = new Promise(function(res, rej) {resolve = res; reject = rej;}); intrp.global.createMutableBinding( 'resolve', intrp.createNativeFunction('resolve', resolve, false)); intrp.global.createMutableBinding( 'reject', intrp.createNativeFunction('reject', reject, false)); try { const thread = intrp.createThreadForSrc(src).thread; if (options.onCreateThread) { options.onCreateThread(intrp, thread); } intrp.start(); result = await p; } catch (e) { t.fail(name, util.format('%s\n%s', src, e)); return; } finally { intrp.stop(); } const r = intrp.pseudoToNative(result); t.expect(name, r, expected, src); } /** * Options for runTest and runAsyncTest. * @record */ const TestOptions = function() {}; /** * Interpreter constructor options. * @type {!Interpreter.Options|undefined} */ TestOptions.prototype.options; /** * Load the standard startup files? (Default: true.) * @type {boolean|undefined} */ TestOptions.prototype.standardInit; /** * Callback to be called after creating new interpreter instance (and * running standard starup files, if not suppressed with standardInit: * false) but before creating a thread for src. Can be used to insert * extra bindings into the global scope (e.g., to create additional * builtins). * * The first argument is the interpreter instance to be configured. * * @type {function(!Interpreter)|undefined} */ TestOptions.prototype.onCreate; /** * Callback to be called after creating a new Interpreter.Thread, but * before running it. * * The first argument is the interpreter instance. * The second argument is the thread just created. * * @type {function(!Interpreter, !Interpreter.Thread)|undefined} */ TestOptions.prototype.onCreateThread; /** * Callback to be called if .run() returns a negative value, * indicating there are blocked threads. Can be used to fake * completion of asynchronous events. * * The first argument is the interpreter instance to be configured. * * @type {function(!Interpreter)|undefined} */ TestOptions.prototype.onBlocked; /////////////////////////////////////////////////////////////////////////////// // Tests: static analysis functions /////////////////////////////////////////////////////////////////////////////// exports.testGetBoundNames = function(t) { const name = 'getBoundNames'; const {getBoundNames} = Interpreter.testOnly; const src = ` var a, b; for (var c in {}) {} function f(x) { var y, z; }; (function g() { var v; })(); `; const ast = Parser.parse(src); const boundNames = getBoundNames(ast); const keys = Object.getOwnPropertyNames(boundNames); t.expect(`${name}() keys`, keys.join(), 'a,b,c,f', src); for (let i = 0; i < 3; i++) { t.expect(`${name}()[${i}]`, boundNames[keys[i]], undefined, src); } t.expect(`${name}()[3]`, boundNames['f'], ast['body'][2], src); }; exports.testHasArgumentsOrEval = function(t) { const name = 'hasArgumentsOrEval'; const {hasArgumentsOrEval} = Interpreter.testOnly; const cases = [ // [src, expected]; will only look at first statement src. ['Arguments;', false], ['arguments;', true], ['arguments[0];', true], ['foo[arguments];', true], ['bar(arguments);', true], ['{var x; function myArgs() {return arguments;}}', false], ['{function f() {} arguments;}', true], ['Eval;', false], ['eval;', true], ['eval();', true], ['Function.prototype.call(eval);', true], ['{var x; function myEval(arg) {eval(arg);}}', false], ['{function f() {} eval();}', true], ]; for (const [src, expected] of cases) { try { const ast = Parser.parse(src); const firstStatement = ast['body'][0]; t.expect(`${name} ${src}`, hasArgumentsOrEval(firstStatement), expected, src); } catch (e) { t.crash(name, util.format('%s\n%s', src, e.stack)); } } }; /////////////////////////////////////////////////////////////////////////////// // Tests: run tests from testcases.js. /////////////////////////////////////////////////////////////////////////////// /** * Run the simple tests in testcases.js * @param {!T} t The test runner object. */ exports.testTestcases = function(t) { for (const tc of testcases) { if (!('expected' in tc)) { t.skip(tc.name); continue; } if (tc.destructive) { const testOptions = tc.options ? {options: tc.options} : {}; runTest(t, tc.name || tc.src, tc.src, tc.expected, testOptions); } else { const oldOptions = interpreter.options; if (tc.options) interpreter.options = tc.options; runSimpleTest(t, tc.name || tc.src, tc.src, tc.expected); if (tc.options) interpreter.options = oldOptions; } } }; /////////////////////////////////////////////////////////////////////////////// // Tests: interpreter internals /////////////////////////////////////////////////////////////////////////////// /** * Run some tests of switch statement with fallthrough. * @param {!T} t The test runner object. */ exports.testSwitchStatementFallthrough = function(t) { const code = ` var x = ''; switch (i) { case 1: x += '1'; // fall through case 2: x += '2'; // fall through default: x += 'D'; // fall through case 3: x += '3'; // fall through case 4: x += '4'; // fall through } x;`; const expected = ['D34', '12D34', '2D34', '34', '4']; for (let i = 0; i < expected.length; i++) { const src = 'var i = ' + i + ';\n' + code; runSimpleTest(t, 'switch fallthrough ' + i, src, expected[i]); } }; /** * Run some tests of switch statement completion values. * @param {!T} t The test runner object. */ exports.testSwitchStatementBreaks = function(t) { const code = ` foo: { switch (i) { case 1: 10; // fall through case 2: 20; break; default: 50; // fall through case 3: 30; break foo; case 4: 40; } }`; const expected = [30, 20, 20, 30, 40]; for (let i = 0; i < expected.length; i++) { const src = 'var i = ' + i + ';\n' + code; runSimpleTest(t, 'switch completion ' + i, src, expected[i]); } }; /** * Run some tests of evaluation of binary expressions, as defined in * §11.5--11.11 of the ES5.1 spec. * @param {!T} t The test runner object. */ exports.testBinaryOp = function(t) { const cases = [ // Addition / concatenation: ["1 + 1", 2], ["'1' + 1", '11'], ["1 + '1'", '11'], // Subtraction: ["'1' - 1", 0], // Multiplication: ["'5' * '5'", 25], ["-5 * 0", -0], ["-5 * -0", 0], ["1 * NaN", NaN], ["Infinity * NaN", NaN], ["-Infinity * NaN", NaN], ["Infinity * Infinity", Infinity], ["Infinity * -Infinity", -Infinity], ["-Infinity * -Infinity", Infinity], ["-Infinity * Infinity", -Infinity], // FIXME: add overflow/underflow cases // Division: ["35 / '7'", 5], ["1 / 1", 1], ["1 / -1", -1], ["-1 / -1", 1], ["-1 / 1", -1], ["1 / NaN", NaN], ["NaN / NaN", NaN], ["NaN / 1", NaN], ["Infinity / Infinity", NaN], ["Infinity / -Infinity", NaN], ["-Infinity / -Infinity", NaN], ["-Infinity / Infinity", NaN], ["Infinity / 0", Infinity], ["Infinity / -0", -Infinity], ["-Infinity / -0", Infinity], ["-Infinity / 0", -Infinity], ["Infinity / 1", Infinity], ["Infinity / -1", -Infinity], ["-Infinity / -1", Infinity], ["-Infinity / 1", -Infinity], ["1 / Infinity", 0], ["1 / -Infinity", -0], ["-1 / -Infinity", 0], ["-1 / Infinity", -0], ["0 / 0", NaN], ["0 / -0", NaN], ["-0 / -0", NaN], ["-0 / 0", NaN], ["1 / 0", Infinity], ["1 / -0", -Infinity], ["-1 / -0", Infinity], ["-1 / 0", -Infinity], // FIXME: add overflow/underflow cases // Remainder: ["20 % 5.5", 3.5], ["20 % -5.5", 3.5], ["-20 % -5.5", -3.5], ["-20 % 5.5", -3.5], ["1 % NaN", NaN], ["NaN % NaN", NaN], ["NaN % 1", NaN], ["Infinity % 1", NaN], ["-Infinity % 1", NaN], ["1 % 0", NaN], ["1 % -0", NaN], ["Infinity % 0", NaN], ["Infinity % -0", NaN], ["-Infinity % -0", NaN], ["-Infinity % 0", NaN], ["0 % 1", 0], ["-0 % 1", -0], // FIXME: add overflow/underflow cases // Left shift: ["10 << 2", 40], ["10 << 28", -1610612736], ["10 << 33", 20], ["10 << 34", 40], // Signed right shift: ["10 >> 4", 0], ["10 >> 33", 5], ["10 >> 34", 2], ["-11 >> 1", -6], ["-11 >> 2", -3], // Signed right shift: ["10 >>> 4", 0], ["10 >>> 33", 5], ["10 >>> 34", 2], ["-11 >>> 0", 0xfffffff5], ["-11 >>> 1", 0x7ffffffa], ["-11 >>> 2", 0x3ffffffd], ["4294967338 >>> 0", 42], // Bitwise: ["0x3 | 0x5", 0x7], ["0x3 ^ 0x5", 0x6], ["0x3 & 0x5", 0x1], ["NaN | 0", 0], ["-0 | 0", 0], ["Infinity | 0", 0], ["-Infinity | 0", 0], // Comparisons: // // (This is mainly about making sure that the binary operators are // hooked up to the abstract relational comparison algorithm // correctly; that algorithm is tested separately to make sure // details of comparisons are correct.) ["1 < 2", true], ["2 < 2", false], ["3 < 2", false], ["1 <= 2", true], ["2 <= 2", true], ["3 <= 2", false], ["1 > 2", false], ["2 > 2", false], ["3 > 2", true], ["1 >= 2", false], ["2 >= 2", true], ["3 >= 2", true], // (Ditto for abastract equality comparison algorithm.) ["1 == 1", true], ["2 == 1", false], ["2 == 2", true], ["1 == 2", false], ["1 == '1'", true], ["1 != 1", false], ["2 != 1", true], ["2 != 2", false], ["1 != 2", true], ["1 != '1'", false], // (Ditto for abastract strict equality comparison algorithm.) ["1 === 1", true], ["2 === 1", false], ["2 === 2", true], ["1 === 2", false], ["1 === '1'", false], ["1 !== 1", false], ["2 !== 1", true], ["2 !== 2", false], ["1 !== 2", true], ["1 !== '1'", true], ]; for (const tc of cases) { const src = tc[0] + ';'; runSimpleTest(t, 'BinaryExpression: ' + tc[0], src, tc[1]); } }; /** * Run some tests of the Abstract Relational Comparison Algorithm, as * defined in §11.8.5 of the ES5.1 spec and as embodied by the '<' * operator. * @param {!T} t The test runner object. */ exports.testArca = function(t) { const cases = [ ['0, NaN', undefined], ['NaN, NaN', undefined], ['NaN, 0', undefined], ['1, 1', false], ['0, -0', false], ['-0, 0', false], ['Infinity, Number.MAX_VALUE', false], ['Number.MAX_VALUE, Infinity', true], ['-Infinity, -Number.MAX_VALUE', true], ['-Number.MAX_VALUE, -Infinity', false], ['1, 2', true], ['2, 1', false], // String comparisons: ['"", ""', false], ['"", " "', true], ['" ", ""', false], ['" ", " "', false], ['"foo", "foobar"', true], ['"foo", "bar"', false], ['"foobar", "foo"', false], ['"10", "9"', true], ['"10", 9', false], // \ufb00 vs. \U0001f019: this test fails if we do simple // lexicographic comparison of UTF-8 or UTF-32. The latter // character is a larger code point and sorts later in UTF8, // but in UTF16 it gets replaced by two surrogates, both of // which are smaller than \uf000. ['"ff", "🀙"', false], // Mixed: ['11, "2"', false], // Numeric ['2, "11"', true], // Numeric ['"11", "2"', true], // String ]; for (const tc of cases) { const src = ` (function(a,b){ return ((a < b) || (a >= b)) ? (a < b) : undefined; })(${tc[0]});`; runSimpleTest(t, 'ARCA: ' + tc[0], src, tc[1]); } }; /** * Run some tests of the Abstract Equality Comparison Algorithm and * the Abstract Strict Equality Comparison Algorithm, as defined in * §11.9.3 and §11.9.6 respectiveyl of the ES5.1 spec and as embodied * by the '==' and '===' operators. * @param {!T} t The test runner object. */ exports.testAeca = function(t) { const cases = [ ['false, false', true, true], // Numeric ['false, true', false, false], // Numeric ['true, true', true, true], // Numeric ['true, false', false, false], // Numeric // Numeric comparisons: ['0, NaN', false, false], ['NaN, NaN', false, false], ['NaN, 0', false, false], ['1, 1', true, true], ['0, -0', true, true], ['-0, 0', true, true], ['Infinity, Number.MAX_VALUE', false, false], ['Number.MAX_VALUE, Infinity', false, false], ['Infinity, -Number.MAX_VALUE', false, false], ['-Number.MAX_VALUE, -Infinity', false, false], ['1, 2', false, false], ['2, 1', false, false], // String comparisons: ['"", ""', true, true], ['"", " "', false, false], ['" ", ""', false, false], ['" ", " "', true, true], ['"foo", "foobar"', false, false], ['"foo", "bar"', false, false], ['"foobar", "foo"', false, false], ['"10", "9"', false, false], // Null / undefined: ['undefined, undefined', true, true], ['undefined, null', true, false], ['null, null', true, true], ['null, undefined', true, false], // Objects: ['Object.prototype, Object.prototype', true, true], ['{}, {}', false, false], // Mixed: ['"10", 10', true, false], // Numeric ['10, "10"', true, false], // Numeric ['"10", 9', false, false], // Numeric ['"10", "9"', false, false], // String ['"10", "10"', true, true], // String ['false, 0', true, false], // Numeric ['false, 1', false, false], // Numeric ['true, 1', true, false], // Numeric ['true, 0', false, false], // Numeric ['0, false', true, false], // Numeric ['1, false', false, false], // Numeric ['1, true', true, false], // Numeric ['0, true', false, false], // Numeric ['null, false', false, false], ['null, 0', false, false], ['null, ""', false, false], ['false, null', false, false], ['0, null', false, false], ['"", null', false, false], ['{}, false', false, false], ['{}, 0', false, false], ['{}, ""', false, false], ['{}, null', false, false], ['{}, undefined', false, false], ]; for (const tc of cases) { let src = `(function(a,b) {return a == b})(${tc[0]});`; runSimpleTest(t, 'AECA: ' + tc[0], src, tc[1]); src = `(function(a,b) {return a === b})(${tc[0]});`; runSimpleTest(t, 'ASECA: ' + tc[0], src, tc[2]); } }; /** * Run a test of asynchronous functions: * @param {!T} t The test runner object. * @suppress {visibility} */ exports.testAsync = function(t) { // Function to install an async NativeFunction on new Interpreter // instances. The function, when called, will save its // resolve/reject callbacks and first arg in test-local variables. let resolve, reject, arg; function createAsync(intrp) { intrp.global.createMutableBinding('async', new intrp.NativeFunction({ name: 'async', length: 0, call: function(intrp, thread, state, thisVal, args) { arg = args[0]; const rr = intrp.getResolveReject(thread, state); resolve = rr.resolve; reject = rr.reject; return Interpreter.FunctionResult.Block; } })); }; // Test ordinary return. let name = 'testAsyncResolve'; let src = ` 'before'; async(); 'between'; async('af') + 'ter'; `; runTest(t, name, src, 'after', { standardInit: false, // Save time. onCreate: createAsync, onBlocked: (intrp) => {resolve(arg);}, }); // Test throwing an exception. name ='testAsyncReject'; src = ` try { 'before'; async(); 'after'; } catch (e) { e; } `; runTest(t, name, src, 'except', { standardInit: false, // Save time. onCreate: createAsync, onBlocked: (intrp) => {reject('except');}, }); // Extra check to verify async function can't resolve/reject more // than once without an asertion failure. name = 'testAsyncSafetyCheck'; let ok; src = ` async(); // Returns ok === undefined then sets ok to 'ok'. async(); // Returns ok === 'ok' then uselessly sets ok a second time. `; runTest(t, name, src, 'ok', { standardInit: false, // Save time. onCreate: createAsync, onBlocked: (intrp) => { resolve(ok); // Call reject; this is expected to blow up. try { reject('foo'); } catch (e) { ok = 'ok'; } }, }); // A test of unwind_, to make sure it unwinds and kills the correct // thread when an async function throws. name = 'testAsyncRejectUnwind'; const intrp = getInterpreter({noLog: ['unhandled']}); createAsync(intrp); // Install async function. // Create cannon-fodder thread that will usually be ready to run. const bgThread = intrp.createThreadForSrc(` // Repeatedly suspend; every 10th time suspend for a long time. for (var i = 1; true; i++) { suspend((i % 10) ? 0 : 1000); } `).thread; // Create thread to call async function. const asyncThread = intrp.createThreadForSrc('async();').thread; intrp.run(); // asyncThread has run once and blocked; bgThread has run ten times // and is now sleeping for 1s. // Create Error err to throw. It should have no stack to start with. const err = new intrp.Error(intrp.ROOT, intrp.ERROR, 'sample error'); t.assert(name + ': Error has no .stack initially', !err.has('stack', intrp.ROOT)); // Throw err. intrp.thread_ = bgThread; // Try to trick reject into killing wrong thread. reject(err); // Throw unhandled Error in asyncThread. // Verify correct thread was unwound and killed. t.assert(name + ': unwound thread stack empty', asyncThread.stateStack_.length === 0); t.expect(name + ': unwound thread status', asyncThread.status, Interpreter.Thread.Status.ZOMBIE); t.assert(name + ': background thread stack non-empty', bgThread.stateStack_.length > 0); t.expect(name + ': background thread status', bgThread.status, Interpreter.Thread.Status.SLEEPING); // Verify err has aquired a stack. t.assert(name + ': Error has .stack after being thrown', err.has('stack', intrp.ROOT)); const stack = err.get('stack', intrp.ROOT); t.assert(name + ': Error .stack mentions function that threw', stack.match(/in async/)); t.assert(name + ': Error .stack mentions call site', stack.match(/at "async\(\);" 1:1/)); }; /** * Run tests of the Thread constructor and the suspend(), setTimeout() * and clearTimeout() functions. * @param {!T} t The test runner object. */ exports.testThreading = function(t) { let src = ` 'before'; suspend(); 'after'; `; runTest(t, 'suspend()', src, 'after'); // Check that Threads have ids. src = ` var t1 = new Thread(function() {}); var t2 = new Thread(function() {}); typeof t1.id === 'number' && typeof t2.id === 'number' && t1.id !== t2.id; `; runSimpleTest(t, '(new Thread).id', src, true); src = ` var s = ''; new Thread(function() {s += this;}, 500, 2); new Thread(function(x) {s += x;}, 1500, undefined, [4]); new Thread(function() {s += '1';}) suspend(1000); s += '3'; suspend(1000); s += '5'; s; `; runTest(t, 'new Thread', src, '12345'); src = ` var current; var thread = new Thread(function() {current = Thread.current();}); suspend(); current === thread; `; runTest(t, 'Thread.current()', src, true); src = ` var result; new Thread(function() { result = 'OK'; Thread.kill(Thread.current()); result = 'The reports of my death are greatly exaggerated.'; }); suspend(); result; `; runTest(t, 'Thread.kill', src, 'OK'); src = ` 'before'; suspend(10000); 'after'; `; runTest(t, 'suspend(1000)', src, 'after'); src = ` var s = ''; setTimeout(function(x) {s += '2';}, 500); setTimeout(function(x) {s += '4';}, 1500); s += '1'; suspend(1000); s += '3'; suspend(1000); s += '5'; s; `; runTest(t, 'setTimeout', src, '12345'); src = ` // Should have no effect: clearTimeout('foo'); clearTimeout(Thread.current()); var s = ''; var tid = setTimeout(function(a, b) { s += a; suspend(); s += b; }, 0, '2', '4'); s += 1; suspend(); s += '3'; clearTimeout(tid); suspend(); s += '5'; s; `; runTest(t, 'clearTimeout', src, '1235'); }; /** * Run tests of the Thread time-limit mechanism. * @param {!T} t The test runner object. */ exports.testTimeLimit = function(t) { // Some constants used by several tests in this section. It should // be the case that a for loop executing the specified number of // iterations will take longer than the specified time limit, even // if the body of the loop is empty. // // Ideally these should be very small values to ensure the tests // run quickly, but in practice random delays (OS-level time // slicing, GC and JIT delays, etc.) make make tests very flaky if // these values are too small. const iterations = 10000; const timeLimit = 5; // in ms. // First check that a sufficiently slow loop will get timed out. // (This also verifies the requirements on the iterations and // timeLimit constants mentioned above.) let name = 'Thread hits timeLimit'; let src = ` try { for (var i = 0; i < ${iterations}; i++) { } "Thread didn't time out"; // Maybe increase iterations? } catch (e) { e.name + ': ' + e.message; // Can't call String(e): we're out of time! } `; runTest(t, name, src, 'RangeError: Thread ran too long', { onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;}, }); // Now check that calling suspend() regularly will save the thread // from timing out. name = 'Thread can use suspend to avoid timeLimit'; src = ` try { for (var i = 0; i < ${iterations}; i++) { suspend(); } "Thread didn't time out"; } catch (e) { e.name + ': ' + e.message; // Can't call String(e): we're out of time! } `; runTest(t, name, src, "Thread didn't time out", { onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;}, }); // Test we can't call anything after timing out. name = "Thread can't call after timeout"; src = ` try { try { for (var i = 0; i < ${iterations}; i++) { } "Thread didn't time out"; // Maybe increase iterations? } catch (e) { String(e); 'Still able to call'; } } catch (e) { e.name + ': ' + e.message; // Can't call String(e): we're out of time! } `; runTest(t, name, src, 'RangeError: Thread ran too long', { onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;}, }); // Test we can't call anything after timing out. name = "Thread can call suspend after timeout"; src = ` try { try { for (var i = 0; i < ${iterations}; i++) { } "Thread didn't time out"; // Maybe increase iterations? } catch (e) { suspend(); 'Still able to call suspend'; } } catch (e) { e.name + ': ' + e.message; // Can't call String(e): we're out of time! } `; runTest(t, name, src, 'Still able to call suspend', { onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;}, }); // Test timeLimit is inherited by child Threads. name = 'Threads inherit timeLimit from parent Thread'; src = ` var r; setTimeout(function() { try { for (var i = 0; i < ${iterations}; i++) { } r = "Thread didn't time out"; // Maybe increase iterations? } catch (e) { r = e.name + ': ' + e.message; // Can't call String(e). } }); suspend(1000000); // Fortunately simulated time passes really quickly. r; `; runTest(t, name, src, 'RangeError: Thread ran too long', { onCreateThread: (intrp, thread) => {thread.timeLimit = timeLimit;}, }); }; /** * Run a test of the .start() and .pause() methods on Interpreter * instances. This is an async test because we use real (albeit * small) timeouts to make sure everything works as it ought to. * @param {!T} t The test runner object. */ exports.testStartStop = async function(t) { function snooze(ms) { return new Promise(function(resolve, reject) {setTimeout(resolve, ms);}); } const intrp = getInterpreter(); let name = 'testStart'; let src = ` var x = 0; while (true) { suspend(10); x++; }; `; try { // Garbage collection occuring during test can case flakiness. gc(); intrp.start(); // .start() will create a zero-delay timeout to check for sleeping // tasks to awaken. Snooze briefly to allow it to run, after // which there should be no outstanding timeouts. This will // ensure that we verify .createThreadForSrc() frobs .start() to get // things going again. await snooze(0); intrp.createThreadForSrc(src); await snooze(29); intrp.pause(); } catch (e) { t.crash(name, util.format('%s\n%s', src, e.stack)); return; } finally { intrp.stop(); } let r = intrp.getValueFromScope(intrp.global, 'x'); const expected = 2; t.expect(name, r, 2, src + '\n(after 29ms)'); // Check that .pause() actually paused execution. name = 'testPause'; await snooze(10); r = intrp.getValueFromScope(intrp.global, 'x'); t.expect(name, r, expected, src + '\n(after 39ms)'); }; /////////////////////////////////////////////////////////////////////////////// // Tests: builtins /////////////////////////////////////////////////////////////////////////////// /** * Run some tests of the various constructors and their associated * literals and prototype objects. * @param {!T} t The test runner object. */ exports.testClasses = function(t) { const classes = { Object: { prototypeProto: 'null', literal: '{}' }, Function: { prototypeType: 'function', literal: 'function(){}' }, Array: { literal: '[]' }, RegExp: { prototypeClass: 'Object', // Was 'RegExp' in ES5.1. literal: '/foo/' }, Date: { prototypeClass: 'Object', // Was 'RegExp' in ES5.1. functionNotConstructor: true // Date() doesn't construct. }, Error: {}, EvalError: { prototypeProto: 'Error.prototype', class: 'Error' }, RangeError: { prototypeProto: 'Error.prototype', class: 'Error' }, ReferenceError: { prototypeProto: 'Error.prototype', class: 'Error' }, SyntaxError: { prototypeProto: 'Error.prototype', class: 'Error' }, TypeError: { prototypeProto: 'Error.prototype', class: 'Error' }, URIError: { prototypeProto: 'Error.prototype', class: 'Error' }, PermissionError: { prototypeProto: 'Error.prototype', class: 'Error' }, Boolean: { literal: 'false', literalType: 'boolean', noInstance: true, }, Number: { literal: '42', literalType: 'number', noInstance: true, }, String: { literal: '"hello"', literalType: 'string', noInstance: true, }, WeakMap: { prototypeClass: 'Object', functionNotConstructor: true // WeakMap() can't be called without new. }, }; for (const c in classes) { const tc = classes[c]; // Check constructor is a function: let name = c + 'IsFunction'; let src = 'typeof ' + c + ';'; runSimpleTest(t, name, src, 'function'); // Check constructor's proto is Function.prototype name = c + 'ProtoIsFunctionPrototype'; src = 'Object.getPrototypeOf(' + c + ') === Function.prototype;'; runSimpleTest(t, name, src, true); // Check prototype is of correct type: const prototypeType = (tc.prototypeType || 'object'); name = c + 'PrototypeIs' + prototypeType; src = 'typeof ' + c + '.prototype;'; runSimpleTest(t, name, src, prototypeType); // Check prototype has correct class: const prototypeClass = (tc.prototypeClass || tc.class || c); name = c + 'PrototypeClassIs' + prototypeClass; src = 'Object.prototype.toString.apply(' + c + '.prototype);'; runSimpleTest(t, name, src, '[object ' + prototypeClass + ']'); // Check prototype has correct proto: const prototypeProto = (tc.prototypeProto || 'Object.prototype'); name = c + 'PrototypeProtoIs' + prototypeProto; src = 'Object.getPrototypeOf(' + c + '.prototype) === ' + prototypeProto + ';'; runSimpleTest(t, name, src, true); // Check prototype's .constructor is constructor: name = c + 'PrototypeConstructorIs' + c; src = c + '.prototype.constructor === ' + c + ';'; runSimpleTest(t, name, src, true); const cls = tc.class || c; if (!tc.noInstance) { // Check instance's type: name = c + 'InstanceIs' + prototypeType; src = 'typeof (new ' + c + ');'; runSimpleTest(t, name, src, prototypeType); // Check instance's proto: name = c + 'InstancePrototypeIs' + c + 'Prototype'; src = 'Object.getPrototypeOf(new ' + c + ') === ' + c + '.prototype;'; runSimpleTest(t, name, src, true); // Check instance's class: name = c + 'InstanceClassIs' + cls; src = 'Object.prototype.toString.apply(new ' + c + ');'; runSimpleTest(t, name, src, '[object ' + cls + ']'); // Check instance is instanceof its contructor: name = c + 'InstanceIsInstanceof' + c; src = '(new ' + c + ') instanceof ' + c + ';'; runSimpleTest(t, name, src, true); if (!tc.functionNotConstructor) { // Recheck instances when constructor called as function: // Recheck instance's type: name = c + 'ReturnIs' + prototypeType; src = 'typeof ' + c + '();'; runSimpleTest(t, name, src, prototypeType); // Recheck instance's proto: name = c + 'ReturnPrototypeIs' + c + 'Prototype'; src = 'Object.getPrototypeOf(' + c + '()) === ' + c + '.prototype;'; runSimpleTest(t, name, src, true); // Recheck instance's class: name = c + 'ReturnClassIs' + cls; src = 'Object.prototype.toString.apply(' + c + '());'; runSimpleTest(t, name, src, '[object ' + cls + ']'); // Recheck instance is instanceof its contructor: name = c + 'ReturnIsInstanceof' + c; src = c + '() instanceof ' + c + ';'; runSimpleTest(t, name, src, true); } } if (tc.literal) { // Check literal's type: const literalType = (tc.literalType || prototypeType); name = c + 'LiteralIs' + literalType; src = 'typeof (' + tc.literal + ');'; runSimpleTest(t, name, src, literalType); // Check literal's proto: name = c + 'LiteralPrototypeIs' + c + 'Prototype'; src = 'Object.getPrototypeOf(' + tc.literal + ') === ' + c + '.prototype;'; runSimpleTest(t, name, src, true); // Check literal's class: name = c + 'LiteralClassIs' + cls; src = 'Object.prototype.toString.apply(' + tc.literal + ');'; runSimpleTest(t, name, src, '[object ' + cls + ']'); // Primitives can never be instances. if (literalType === 'object' || literalType === 'function') { // Check literal is instanceof its contructor. name = c + 'LiteralIsInstanceof' + c; src = '(' + tc.literal + ') instanceof ' + c + ';'; runSimpleTest(t, name, src, true); } } } }; /** * Run a test of multiple simultaneous calls to Array.prototype.join. * @param {!T} t The test runner object. */ exports.testArrayPrototypeJoinParallelism = function(t) { let src = ` // Make String() do a suspend(), to tend to cause multiple // simultaneous .join() calls become badly interleved with each // other. String = function(value) { suspend(); return (new 'String')(value); // Call original. }; var arr = [1, [2, [3, [4, 5]]]]; // Set up another Array.prototype.join traversing a subset of // the same objects to screw with us. new Thread(function() {arr[1].join();}); // Try to do the join anyway. arr.join() `; runTest(t, 'Array.prototype.join parallel', src, '1,2,3,4,5'); }; /** * Run some tests of Number.toString(radix) with various different * radix arguments. * @param {!T} t The test runner object. */ exports.testNumberToString = function(t) { const cases = [ ['(42).toString()', '42'], ['(42).toString(16)', '2a'], //['(-42.4).toString(5)', '-132.2'], Node incorrectly reports '-132.144444'. ['(42).toString("2")', '101010'], ['(-3.14).toString()', '-3.14'], ['(999999999999999999999999999).toString()', '1e+27'], ['(NaN).toString()', 'NaN'], ['(Infinity).toString()', 'Infinity'], ['(-Infinity).toString()', '-Infinity'], ]; for (const tc of cases) { const src = tc[0] + ';'; runSimpleTest(t, 'testNumberToString: ' + tc[0], src, tc[1]); } }; /** * Run tests of the server side of the networking subsystem * (connectionListen et al.) * @param {!T} t The test runner object. */ exports.testServing = async function(t) { // Run a test of connectionListen() and connectionUnlisten(), and // of the server receiving data using the .receive and .end methods // on a connection object. let name = 'testServerInbound'; let src = ` var data = '', conn = {}; conn.onReceive = function(d) { data += d; }; conn.onEnd = function() { CC.connectionClose(this); CC.connectionUnlisten(8888); resolve(data); }; CC.connectionListen(8888, conn); send(); `; function createSend(intrp) { intrp.global.createMutableBinding('send', intrp.createNativeFunction( 'send', function() { // Send some data to server. const client = net.createConnection({port: 8888}, function() { client.write('foo'); client.write('bar'); client.end(); }); })); }; await runAsyncTest(t, name, src, 'foobar', { options: {noLog: ['net']}, onCreate: createSend }); // Run a test of the connectionListen(), connectionUnlisten(), // connectionWrite() and connectionClose functions. name = 'testServerOutbound'; src = ` var conn = {}; conn.onConnect = function() { CC.connectionWrite(this, 'foo'); CC.connectionWrite(this, 'bar'); CC.connectionClose(this); }; CC.connectionListen(8888, conn); resolve(receive()); CC.connectionUnlisten(8888); `; function createReceive(intrp) { intrp.global.createMutableBinding('receive', new intrp.NativeFunction({ name: 'receive', length: 0, call: function(intrp, thread, state, thisVal, args) { let reply = ''; const rr = intrp.getResolveReject(thread, state); // Receive some data from the server. const client = net.createConnection({port: 8888}, function() { client.on('data', function(data) { reply += data; }); client.on('end', function() { rr.resolve(reply); }); client.on('error', function() { rr.reject(); }); }); return Interpreter.FunctionResult.Block; } })); }; await runAsyncTest(t, name, src, 'foobar', { options: {noLog: ['net']}, onCreate: createReceive, }); // Check to make sure that connectionListen() throws if attempting // to bind to an invalid port or rebind a port already in use. name = 'testConnectionListenThrows'; const server = new net.Server(); server.listen(8887); src = ` // Some invalid ports: // * 8887 is in use by the above net.Server. // * 8888 will be in-use by via previous connectionListen. // * Others are not integers or are out-of-range. var ports = ['foo', {}, -1, 80.8, 8887, 8888, 65536]; try { CC.connectionListen(8888, {}); for (var i = 0; i < ports.length; i++) { try { CC.connectionListen(ports[i], {}); resolve('Unexpected success listening on port ' + ports[i]); } catch (e) { if (!(e instanceof Error)) { resolve('threw non-Error value ' + String(e)); } } } } finally { CC.connectionUnlisten(8888); } resolve('OK'); `; await runAsyncTest(t, name, src, 'OK', {options: {noLog: ['net']}}); server.close(); // Check to make sure that connectionUnlisten() throws if attempting // to unbind an invalid or not / no longer bound port. name = 'testConnectionUnlistenThrows'; src = ` var ports = ['foo', {}, -1, 22, 80.8, 4567, 8888, 65536]; CC.connectionListen(8888, {}); CC.connectionUnlisten(8888, {}); for (var i = 0; i < ports.length; i++) { try { CC.connectionUnlisten(ports[i], {}); resolve('Unexpected success unlistening on port ' + ports[i]); } catch (e) { if (!(e instanceof Error)) { resolve('threw non-Error value ' + String(e)); } } } resolve('OK'); `; await runAsyncTest(t, name, src, 'OK', {options: {noLog: ['net']}}); // Check to make sure that connectionWrite() throws if attempting to // write anything not a string or to anything not a connected // object. name = 'testConnectionWriteThrows'; src = ` var conn = {toString: function() {return 'an open connection';}}; conn.onConnect = function() { var cases = [ {obj: undefined, data: 'fine'}, {obj: null, data: 'fine'}, {obj: 42, data: 'fine'}, {obj: true, data: 'fine'}, {obj: 'a string', data: 'fine'}, {obj: {/* not connected */}, data: 'fine'}, {obj: this, data: undefined}, {obj: this, data: null}, {obj: this, data: 42}, {obj: this, data: true}, {obj: this, data: {}}, ]; for (var tc, i = 0; (tc = cases[i]); i++) { try { CC.connectionWrite(tc.obj, tc.data); resolve('Unexpected success writing ' + tc.data + ' to ' + String(tc.obj)); } catch (e) { if (!(e instanceof TypeError)) { resolve('threw non-TypeError value ' + String(e)); } } } CC.connectionClose(this); resolve('OK'); }; CC.connectionListen(8888, conn); try { receive(); } finally { CC.connectionUnlisten(8888); } `; await runAsyncTest(t, name, src, 'OK', { options: {noLog: ['net']}, onCreate: createReceive, }); // Run a test to make sure listening sockets survive the interpreter // being paused and restarted. name = 'testServerPauseStart'; src = ` var data = '', conn = {}; conn.onReceive = function(d) { data += d; }; conn.onEnd = function() { CC.connectionClose(this); CC.connectionUnlisten(8888); resolve(data); }; CC.connectionListen(8888, conn); pause(); send(); `; function createPauseAndSend(intrp) { intrp.global.createMutableBinding('pause', intrp.createNativeFunction( 'pause', function() { intrp.pause(); intrp.start(); })); createSend(intrp); }; await runAsyncTest(t, name, src, 'foobar', { options: {noLog: ['net']}, onCreate: createPauseAndSend }); // Run a test to make sure listening sockets are re-listened after // the interpreter is stopped and restarted. name = 'testServerStopStart'; src = ` var data = '', conn = {}; conn.onReceive = function(d) { data += d; }; conn.onEnd = function() { CC.connectionClose(this); CC.connectionUnlisten(8888); resolve(data); }; CC.connectionListen(8888, conn); stop(); send(); `; function createStopAndSend(intrp) { intrp.global.createMutableBinding('stop', intrp.createNativeFunction( 'stop', function() { intrp.stop(); intrp.start(); })); createSend(intrp); }; await runAsyncTest(t, name, src, 'foobar', { options: {noLog: ['net']}, onCreate: createStopAndSend }); }; /** * Run tests of the client side of the networking subsystem (xhr). * @param {!T} t The test runner object. */ exports.testClient = async function(t) { // Run test of the xhr() function using HTTP. let name = 'testXhrHttp'; const httpTestServer = http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('OK HTTP: ' + req.url); }).listen(9980); let src = ` try { resolve(CC.xhr('http://localhost:9980/foo')); } catch (e) { reject(e); } `; await runAsyncTest(t, name, src, 'OK HTTP: /foo', {options: {noLog: ['net']}}); httpTestServer.close(); // Run test of the xhr() function using HTTPS. // TODO(cpcallen): Don't depend on external webserver. name = 'testXhr'; src = ` try { resolve(CC.xhr('https://neil.fraser.name/software/JS-Interpreter/' + 'demos/async.txt')); } catch (e) { reject(e); } `; await runAsyncTest(t, name, src, 'It worked!\n', {options: {noLog: ['net']}}); }; ================================================ FILE: server/tests/interpreter_unit_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Unit tests for internal functions of JavaScript interpreter. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const util = require('util'); const Interpreter = require('../interpreter'); const {T} = require('./testing'); /** * Unit tests for Interpreter.toInteger, .toLength. and .toUint32 * @param {!T} t The test runner object. */ exports.testToIntegerEtc = function(t) { const intrp = new Interpreter; const cases = [ // [value, ToInteger(value), ToLength(value), ToUint32(value)] [false, 0, 0, 0], [true, 1, 1, 1], [0, 0, 0, 0], [-0, -0, 0, 0], [1, 1, 1, 1], [-1, -1, 0, 0xffffffff], [0xfffffffe, 0xfffffffe, 0xfffffffe, 0xfffffffe], [0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff], [0x100000000, 0x100000000, 0x100000000, 0], [4.5, 4, 4, 4], [2**53-1, 2**53-1, 2**53-1, 0xffffffff], [2**53, 2**53, 2**53-1, 0], [Infinity, Infinity, 2**53-1, 0], [-Infinity, -Infinity, 0, 0], [NaN, 0, 0, 0], ['0', 0, 0, 0], ['-0', -0, 0, 0], ['1', 1, 1, 1], ['-1', -1, 0, 0xffffffff], ['0xfffffffe', 0xfffffffe, 0xfffffffe, 0xfffffffe], ['0xffffffff', 0xffffffff, 0xffffffff, 0xffffffff], ['0x100000000', 0x100000000, 0x100000000, 0], ['4294967294', 0xfffffffe, 0xfffffffe, 0xfffffffe], ['4294967295', 0xffffffff, 0xffffffff, 0xffffffff], ['4294967296', 0x100000000, 0x100000000, 0], ['4.5', 4, 4, 4], ['9007199254740991', 2**53-1, 2**53-1, 0xffffffff], ['9007199254740992', 2**53, 2**53-1, 0], ['hello', 0, 0, 0], [null, 0, 0, 0], [undefined, 0, 0, 0], [new intrp.Array, 0, 0, 0], [new intrp.Object, 0, 0, 0], ]; const funcs = [Interpreter.toInteger, Interpreter.toLength, Interpreter.toUint32]; for (const [input, ...expected] of cases) { for (let i = 0; i < funcs.length; i++) { const name = util.format('%s(%o)', funcs[i].name, input); t.expect(name, funcs[i](input), expected[i]); } } }; /** * Unit tests for Interpreter.prototype.nativeToPseudo. * @param {!T} t The test runner object. */ exports.testNativeToPseudo = function(t) { const intrp = new Interpreter; // Test handling of Arrays (including extra non-index properties). const props = {0: 0, 1: 1, 2: 2, length: 3, extra: 4}; const arr = []; for (const k in props) { if (!props.hasOwnProperty(k)) continue; arr[/** @type{?} */(k)] = props[k]; } const pArr = intrp.nativeToPseudo(arr, intrp.ROOT); for (const k in props) { if (!props.hasOwnProperty(k)) continue; const name = 'testNativeToPseudo(array)["' + k + '"]'; const r = pArr.get(k, intrp.ROOT); t.expect(name, r, props[k]); } // Test handling of Errors. const cases = [ [Error, intrp.ERROR], [EvalError, intrp.EVAL_ERROR], [RangeError, intrp.RANGE_ERROR], [ReferenceError, intrp.REFERENCE_ERROR], [SyntaxError, intrp.SYNTAX_ERROR], [TypeError, intrp.TYPE_ERROR], [URIError, intrp.URI_ERROR], ]; for (const [Err, proto] of cases) { const name = 'testNativeToPseudo(' + Err.prototype.name + ')'; const errMessage = 'test ' + Err.prototype.name; const error = Err(errMessage); const pError = intrp.nativeToPseudo(error, intrp.ROOT); t.expect(name + ' instanceof intrp.Error', pError instanceof intrp.Error, true); t.expect(name + '.proto', pError.proto, proto); t.expect(name + '.message', pError.get('message', intrp.ROOT), errMessage); t.expect(name + '.stack', pError.get('stack', intrp.ROOT), error.stack); } }; /** * Unit tests for Interpreter.Scope class. * @param {!T} t The test runner object. */ exports.testScope = function(t) { const intrp = new Interpreter; const outer = new Interpreter.Scope( Interpreter.Scope.Type.DUMMY, intrp.ROOT, null, 'this'); const inner = new Interpreter.Scope( Interpreter.Scope.Type.DUMMY, intrp.ROOT, outer); // 0: Initial condition. t.expect("outer.this // 0", outer.this, 'this'); t.expect("inner.this // 0", inner.this, 'this'); t.expect("outer.hasBinding('foo') // 0", outer.hasBinding('foo'), false); t.expect("outer.resolve('foo') // 0", outer.resolve('foo'), null); t.expect("inner.resolve('foo') // 0", inner.resolve('foo'), null); // 1: Create outer binding. outer.createMutableBinding('foo', 42); t.expect("outer.hasBinding('foo') // 1", outer.hasBinding('foo'), true); t.expect("inner.hasBinding('foo') // 1", inner.hasBinding('foo'), false); t.expect("outer.resolve('foo') // 1", outer.resolve('foo'), outer); t.expect("inner.resolve('foo') // 1", inner.resolve('foo'), outer); t.expect("outer.get('foo') // 1", outer.get('foo'), 42); t.expect("getValueFromScope(outer, 'foo', ...) // 1", intrp.getValueFromScope(outer, 'foo'), 42); t.expect("getValueFromScope(inner, 'foo', ...) // 1", intrp.getValueFromScope(inner, 'foo'), 42); try { outer.createMutableBinding('foo', 42); t.fail("outer.createMutableBinding('foo', ...) // 1", "Didn't throw."); } catch (e) { t.pass("outer.createMutableBinding('foo', ...) // 1"); } // 2: Set outer binding. outer.set('foo', 69); t.expect("outer.get('foo') // 2", outer.get('foo'), 69); t.expect("getValueFromScope(inner, 'foo', ...) // 2", intrp.getValueFromScope(inner, 'foo'), 69); t.expect("getValueFromScope(outer, 'foo', ...) // 2", intrp.getValueFromScope(outer, 'foo'), 69); // 3: Create inner binding. inner.createImmutableBinding('foo', 105); t.expect("outer.hasBinding('foo') // 3", outer.hasBinding('foo'), true); t.expect("inner.hasBinding('foo') // 3", inner.hasBinding('foo'), true); t.expect("outer.resolve('foo') // 3", outer.resolve('foo'), outer); t.expect("inner.resolve('foo') // 3", inner.resolve('foo'), inner); t.expect("outer.get('foo') // 3", outer.get('foo'), 69); t.expect("inner.get('foo') // 3", inner.get('foo'), 105); t.expect("getValueFromScope(inner, 'foo', ...) // 3", intrp.getValueFromScope(inner, 'foo'), 105); t.expect("getValueFromScope(outer, 'foo', ...) // 3", intrp.getValueFromScope(outer, 'foo'), 69); // 4: Try to create duplicate binding. try { outer.createMutableBinding('foo', 17); t.fail("outer.createMutableBinding('foo', ...) // 4", "Didn't throw."); } catch (e) { t.pass("outer.createMutableBinding('foo', ...) // 4"); } // 5: Try to set immutable binding (two different ways) t.assert("inner.set('foo', 37) instanceof TypeError", inner.set('foo', 37) instanceof TypeError); try { intrp.setValueToScope(inner, 'foo', 37); t.fail("setValueToScope(inner, 'foo', 37, ...) // 5", "Didn't throw."); } catch (e) { t.pass("setValueToScope(inner, 'foo', 37, ...) // 5"); } }; /** * Unit tests for Interpreter.Source class. * @param {!T} t The test runner object. */ exports.testSource = function(t) { let src = new Interpreter.Source('ABCDEF'); let name = "Source('ABCDEF')"; src = src.slice(0, 6); t.expect(name + '.toString()', String(src), 'ABCDEF'); src = src.slice(1, 5); name += '.slice(1, 5)'; t.expect(name + '.toString()', String(src), 'BCDE'); src = src.slice(2, 4); name += '.slice(2, 4)'; t.expect(name + '.toString()', String(src), 'CD'); const s = '1\n.2\n..3\n.4\n5\n'; const pos3 = s.indexOf('3'); src = new Interpreter.Source(s); name = util.format('Source(%o)', s); let lc = src.lineColForPos(pos3); t.expect(name + '.lineColForPos(' + pos3 + ').line', lc.line, 3); t.expect(name + '.lineColForPos(' + pos3 + ').col', lc.col, 3); src = src.slice(2, 12); name += '.slice(2, 12)'; lc = src.lineColForPos(pos3); t.expect(name + '.lineColForPos(' + pos3 + ').line', lc.line, 2); t.expect(name + '.lineColForPos(' + pos3 + ').col', lc.col, 3); src = src.slice(2, 12); name += '.slice(2, 12)'; lc = src.lineColForPos(pos3); t.expect(name + '.toString()', String(src), '.2\n..3\n.4\n'); t.expect(name + '.lineColForPos(' + pos3 + ').line', lc.line, 2); t.expect(name + '.lineColForPos(' + pos3 + ').col', lc.col, 3); src = new Interpreter.Source('startBound').slice(0, 5).slice(0, 0); name = "Source('startBound').slice(0, 5).slice(0, 0)"; lc = src.lineColForPos(0); t.expect(name + '.lineColForPos(0).line', lc.line, 1); t.expect(name + '.lineColForPos(0).col', lc.line, 1); t.expect(name + '.toString()', String(src), ''); src = new Interpreter.Source('endBound').slice(3, 8).slice(8, 8); name = "Source('endBound').slice(3, 8).slice(8, 8)"; lc = src.lineColForPos(8); t.expect(name + '.lineColForPos(8).line', lc.line, 1); t.expect(name + '.lineColForPos(8).col', lc.line, 1); t.expect(name + '.toString()', String(src), ''); }; ================================================ FILE: server/tests/iterable_weakmap_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test for IterableWeakMap. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const util = require('util'); const IterableWeakMap = require('../iterable_weakmap'); const {T} = require('./testing'); /** * Request garbage collection and cycle the event loop to give * finalisers a chance to be run. No guarantees about either, * unfortunately. * @return {!Promise} */ async function gcAndFinalise() { // Cycle event loop to allow finalisers to run. Need to cycle it // once before GC to ensure that WeakRefs can be cleared (their // targets can never be cleared in the same turn as the WeakRef was // created), then again after to allow finalisers to run. await new Promise((res, rej) => setImmediate(res)); gc(); await new Promise((res, rej) => setImmediate(res)); } /** * Run some basic tests of IterableWeakMap. * @param {!T} t The test runner object. */ exports.testIterableWeakMap = async function(t) { const name = 'IterableWeakMap'; const assertSame = function(got, want, desc) { t.expect(name + ': ' + desc, got, want); }; assertSame(IterableWeakMap.prototype[Symbol.iterator], IterableWeakMap.prototype.entries, 'prototype[Symbol.iterator] and prototype.entries are the same method'); const obj1 = {}; const obj2 = {}; const iwm = new IterableWeakMap([[obj1, 42], [obj2, 69]]); (() => { // Sequester obj3 in an IIFE, because just doing tmp = undefined // to allow the object to be garbage collected seems to be // insufficient. (Presumably V8 optimises the assignment away.) const obj3 = {}; assertSame(iwm.set(obj3, 105), iwm, 'iwm.set(tmp, 105)'); assertSame(iwm.get(obj3), 105, 'iwm.get(tmp)'); assertSame(Array.from(iwm.values()).reduce((x, y) => x + y), 42 + 69 + 105, 'sum of .values()'); let count = 0; let sum = 0; iwm.forEach((v, k, m) => { assertSame(m, iwm, 'Map param in iwm.forEach callback'); count++; sum += v; }); assertSame(count, 3, 'Iterations in iwm.forEach callback'); assertSame(sum, 42 + 69 + 105, 'Sum of values in iwm.forEach callback'); })(); assertSame(iwm.get(obj1), 42, 'iwm.get(obj)'); assertSame(iwm.has(obj1), true, 'iwm.has(obj)'); assertSame(iwm.has({}), false, 'iwm.has({})'); assertSame(iwm.size, 3, 'iwm.size'); await gcAndFinalise(); assertSame(iwm.has(obj1), true, 'iwm.has(obj) (after GC)'); assertSame(iwm.get(obj1), 42, 'iwm.get(obj) (after GC)'); assertSame(iwm.size, 2, 'iwm.size (after GC)'); const keys = Array.from(iwm.keys()); assertSame(keys.length, 2, 'Array.from(iwm.keys()).length'); assertSame(keys[0], obj1, 'Array.from(iwm.keys())[0]'); assertSame(keys[1], obj2, 'Array.from(iwm.keys())[1]'); assertSame(iwm.delete({}), false, 'iwm.delete({})'); assertSame(iwm.delete(obj2), true, 'iwm.delete(obj)'); assertSame(iwm.size, 1, 'iwm.size (after delete)'); const entries = Array.from(iwm); assertSame(entries.length, 1, 'Array.from(iwm).length (after delete)'); assertSame(entries[0][0], obj1, 'Array.from(iwm)[0][0]'); assertSame(entries[0][1], 42, 'Array.from(iwm)[0][1]'); iwm.clear(); assertSame(iwm.has(obj1), false, 'iwm.has(obj) (after clear)'); assertSame(iwm.get(obj1), undefined, 'iwm.get(obj) (after clear)'); assertSame(iwm.size, 0, 'iwm.size (after clear)'); }; /** * Test for correct handling of cyclic garbage in IterableWeakMap. * @param {!T} t The test runner object. */ exports.testIterableWeakMapCyclic = async function(t) { const iwm = new IterableWeakMap; (() => { const objs = [{}, {}, {}]; iwm.set(objs[0], objs[0]); // obj[0] is held circularly. iwm.set(objs[1], objs[2]); // obj[1] and [2] are held by each other. iwm.set(objs[2], objs[1]); })(); t.expect('IterableWeakMapCyclic: iwm.size (before GC)', iwm.size, 3); await gcAndFinalise(); t.expect('IterableWeakMapCyclic: iwm.size (after GC)', iwm.size, 0); }; /** * Test for layered collection of IterableWeakMap. * * When a WeakMap contains a chain of object (i.e., wm.get(o1) === o2, * wm.get(o2) === o3, etc.) all should simultaneously be eligible for * collection if the 'head' object becomes unreachable. This test * will either pass (if that is true of IterableWeakMap) or issue a * warning if it takes several GCs to entierly empty the map. * @param {!T} t The test runner object. */ exports.testIterableWeakMapLayeredGC = async function(t) { /* N.B.: This test seems to be deterministic but very sensitive to * seemingly insignificant code changes, which can (for no obvious * reason, but probably due to some internal optimisations) result * in the IterableWeakMap keys not being garbage collected at all. * * This can be difficult to debug, because e.g. adding a console.log * call inside the loop that calls gc() will make the problem go * away. */ const name = 'IterableWeakMapLayeredGC'; const iwm = new IterableWeakMap; // Make a chain of entries. (() => { const objs = [{}, {}, {}, {}, {}]; for (let i = 0; i < objs.length; i++) { iwm.set(objs[i], objs[i + 1]); } })(); const limit = 10; // objs.length * 2 let count = 0; for (; count < limit && iwm.size > 0; count++) { await gcAndFinalise(); } if (count >= limit) { t.fail(name, 'Test failed to terminate in a reasonable time.'); } else if (count > 1) { t.result('WARN', name, 'IterableWeakMap causes layered GC! (' + count + ' iterations)'); } else { t.pass(name); } }; ================================================ FILE: server/tests/iterable_weakset_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test for IterableWeakSet. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const util = require('util'); const IterableWeakSet = require('../iterable_weakset'); const {T} = require('./testing'); /** * Request garbage collection and cycle the event loop to give * finalisers a chance to be run. No guarantees about either, * unfortunately. * @return {!Promise} */ async function gcAndFinalise() { // Cycle event loop to allow finalisers to run. Need to cycle it // once before GC to ensure that WeakRefs can be cleared (their // targets can never be cleared in the same turn as the WeakRef was // created), then again after to allow finalisers to run. await new Promise((res, rej) => setImmediate(res)); gc(); await new Promise((res, rej) => setImmediate(res)); } /** * Run some basic tests of IterableWeakSet. * @param {!T} t The test runner object. */ exports.testIterableWeakSet = async function(t) { const name = 'IterableWeakSet'; const assertSame = function(got, want, desc) { t.expect(name + ': ' + desc, got, want); }; assertSame(IterableWeakSet.prototype[Symbol.iterator], IterableWeakSet.prototype.values, 'prototype[Symbol.iterator] and prototype.values are the same method'); assertSame(IterableWeakSet.prototype.keys, IterableWeakSet.prototype.values, 'prototype.keys and prototype.values are the same method'); const obj1 = {x: 42}; const obj2 = {x: 69}; const iws = new IterableWeakSet([obj1, obj2]); (() => { // Sequester obj3 in an IIFE, because just doing tmp = undefined // to allow the object to be garbage collected seems to be // insufficient. (Presumably V8 optimises the assignment away.) const obj3 = {x: 105}; assertSame(iws.add(obj3), iws, 'iws.add(tmp)'); assertSame(iws.has(obj3), true, 'iws.has(tmp)'); assertSame( Array.from(iws.values()).map((obj) => obj.x).toString(), '42,69,105', '.x values from .values()'); let count = 0; let sum = 0; iws.forEach((v1, v2, s) => { assertSame(v1, v2, 'value params in iws.forEach callback'); assertSame(s, iws, 'Set param in iws.forEach callback'); count++; sum += v1.x; }); assertSame(count, 3, 'Iterations in iws.forEach callback'); assertSame(sum, 42 + 69 + 105, 'Sum of .x values in iws.forEach callback'); })(); assertSame(iws.has(obj1), true, 'iws.has(obj)'); assertSame(iws.has({}), false, 'iws.has({})'); assertSame(iws.size, 3, 'iws.size'); await gcAndFinalise(); assertSame(iws.has(obj1), true, 'iws.has(obj) (after GC)'); assertSame(iws.size, 2, 'iws.size (after GC)'); const keys = Array.from(iws.keys()); assertSame(keys.length, 2, 'Array.from(iws.keys()).length'); assertSame(keys[0], obj1, 'Array.from(iws.keys())[0]'); assertSame(keys[1], obj2, 'Array.from(iws.keys())[1]'); assertSame(iws.delete({}), false, 'iws.delete({})'); assertSame(iws.delete(obj2), true, 'iws.delete(obj)'); assertSame(iws.size, 1, 'iws.size (after delete)'); const values = Array.from(iws); assertSame(values.length, 1, 'Array.from(iws).length (after delete)'); assertSame(values[0], obj1, 'Array.from(iws)[0]'); iws.clear(); assertSame(iws.has(obj1), false, 'iws.has(obj) (after clear)'); assertSame(iws.size, 0, 'iws.size (after clear)'); }; ================================================ FILE: server/tests/priorityqueue_test.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Tests for PriorityQueue. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const util = require('util'); const PriorityQueue = require('../priorityqueue').PriorityQueue; const {T} = require('./testing'); // Unpack test-only functions. const {parent, children} = require('../priorityqueue').testOnly; /** * Test the inernal parent() function. * @param {!T} t The test runner object. */ exports.testParent = function(t) { const cases = [ [0, -1], [1, 0], [2, 0], [3, 1], [4, 1], [5, 2], [6, 2], ]; for (const [i, expected] of cases) { t.expect(util.format('parent(%d)', i), parent(i), expected); }; }; /** * Test the internal children() function. * @param {!T} t The test runner object. */ exports.testChildren = function(t) { const cases = [ [0, [1, 2]], [1, [3, 4]], [2, [5, 6]], ]; for (const [i, [left, right]] of cases) { const result = children(i); t.expect(util.format('parent(%d)[0]', i), result[0], left); t.expect(util.format('parent(%d)[0]', i), result[1], right); }; }; /** * Check pq.heap_ and pq.indices_ obey their invariants. * @param {T} t The test runner object. * @param {!PriorityQueue} pq The PriorityQueue object to test the * invariants of. * @param {string=} note A textual description of the test situation. * @suppress {accessControls} */ function checkInvariants(t, pq, note) { if (note) note = ' // ' + note; for (let i = 0; i < pq.heap_.length; i++) { // Check heap ordering invariant. const p = parent(i); if (p >= 0) { t.assert('PriorityQueue heap ordering invariant' + note, pq.heap_[i].priority >= pq.heap_[p].priority, util.format( '.heap_[%d].priority === %d, .heap_[%d].priority === %d', i, pq.heap_[i].priority, p, pq.heap_[p].priority) + util.format('\n%o\n', pq.heap_)); } // Check index is correct for .heap_[i].value t.expect(util.format('PriorityQueue: .indices_.get(.heap_[%d].value)%s', i, note), pq.indices_.get(pq.heap_[i].value), i); } for (const [value, index] of pq.indices_) { // Check value is correct for .indices_.get(v). t.expect(util.format('PriorityQueue: .heap_[.indices_.get(%o)].value%s', value, note), pq.heap_[index].value, value); } t.expect('PriorityQueue: .heap_.length (vs. .indices_.size)' + note, pq.heap_.length, pq.indices_.size); }; /** * Run some basic tests of PriorityQueue. * @param {!T} t The test runner object. */ exports.testPriorityQueue = function(t) { const name = 'PriorityQueue'; const pq = new PriorityQueue(); // Insert some values in a particular order, using value as priority. for (const v of [2, 4, 6, 8, 10, 12, 14, 15, 13, 11, 9, 7, 5, 3, 1]) { pq.set(v, v); checkInvariants(t, pq, util.format('after .insert(%d, %d)', v, v)); } // Remove three items. for (let i = 1; i <= 3; i++) { t.expect(name + ' .deleteMin() // ' + i, pq.deleteMin(), i); t.expect(name + ' .length // ' + i, pq.length, 15 - i); checkInvariants(t, pq, 'after .deleteMin #' + i); } // Reduce priority of 6 to 4.5. pq.set(6, 4.5); checkInvariants(t, pq, 'after .reducePriority(6, 4.5)'); // Remove next three items; verify order per changed priorities. t.expect(name + ' .deleteMin() // 4', pq.deleteMin(), 4); checkInvariants(t, pq, 'after .deleteMin #4'); t.expect(name + ' .deleteMin() // 5', pq.deleteMin(), 6); checkInvariants(t, pq, 'after .deleteMin #5'); t.expect(name + ' .deleteMin() // 6', pq.deleteMin(), 5); checkInvariants(t, pq, 'after .deleteMin #6'); // Remove remaining items. for (let i = 7; i <= 15; i++) { t.expect(name + ' .deleteMin() // ' + i, pq.deleteMin(), i); t.expect(name + ' .length // ' + i, pq.length, 15 - i); checkInvariants(t, pq, 'after .deleteMin #' + i); } }; ================================================ FILE: server/tests/registry_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Unit tests for the Registry class. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const Registry = require('../registry'); const {T} = require('./testing'); /** * Unit tests for the Interpreter.Registry class. * @param {!T} t The test runner object. */ exports.testRegistry = function(t) { const reg = new Registry; const obj = {}; // 0: Initial condition. t.expect("reg.has('foo') // 0", reg.has('foo'), false); try { reg.get('foo'); t.fail("reg.get('foo') // 0", "Didn't throw."); } catch(e) { t.pass("reg.get('foo') // 0"); } t.expect("reg.getKey(obj) // 0", reg.getKey(obj), undefined); t.expect("reg.keys().length // 0", reg.keys().length, 0); // 1: Register obj as 'foo'. reg.set('foo', obj); t.expect("reg.has('foo') // 1", reg.has('foo'), true); t.expect("reg.get('foo') // 1", reg.get('foo'), obj); t.expect("reg.getKey(obj) // 1", reg.getKey(obj), 'foo'); t.expect("reg.keys().length // 1", reg.keys().length, 1); t.expect("reg.keys()[0] // 1", reg.keys()[0], 'foo'); // 2: Attempt to register another object as 'foo'. try { reg.set('foo', {}); t.fail("reg.set('foo', {}) // 2", "Didn't throw."); } catch(e) { t.pass("reg.set('foo', {}) // 2"); } t.expect("reg.has('foo') // 2", reg.has('foo'), true); t.expect("reg.get('foo') // 2", reg.get('foo'), obj); t.expect("reg.getKey(obj) // 2", reg.getKey(obj), 'foo'); t.expect("reg.getKey({}) // 2", reg.getKey({}), undefined); // 3: Attempt to register obj as 'bar'. try { reg.set('bar', obj); t.fail("reg.set('bar', obj) // 3", "Didn't throw."); } catch(e) { t.pass("reg.set('bar', obj) // 3"); } t.expect("reg.has('bar') // 3", reg.has('bar'), false); t.expect("reg.getKey(obj) // 3", reg.getKey(obj), 'foo'); // Test iterators. // TODO(cpcallen): test with more than one item to iterate over? const keys = reg.keys(); t.expect("reg.keys().length", keys.length, 1); t.expect("reg.keys()[0]", keys[0], 'foo'); const values = reg.values(); t.expect("reg.values().length", values.length, 1); t.expect("reg.values()[0]", values[0], obj); const entries = reg.entries(); t.expect("reg.entries().length", entries.length, 1); t.expect("reg.entries()[0][0]", entries[0][0], 'foo'); t.expect("reg.entries()[0][1]", entries[0][1], obj); }; ================================================ FILE: server/tests/run ================================================ #!/bin/bash # Run unit tests in Node. node --expose-gc tests/run.js # Delete any existing checkpoint files. rm tests/db/*.city # Start Code City the first time. echo "Starting Code City (1 of 2)" ./codecity tests/db/test.cfg echo "Stopped Code City (1 of 2)" # Start Code City the second time. echo "Starting Code City (2 of 2)" ./codecity tests/db/test.cfg echo "Stopped Code City (2 of 2)" ================================================ FILE: server/tests/run.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test runner for server tests. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; // Force closure-compiler to compile server and testst/benchmarks (for // syntax/type checking). Server could be compiled separately but // it's faster to have do both in one run. Tests and benchmark files // need to be enumerated explicitly because closure-compiler ignores // require statements with arguments that are not a string literal. const compileTargets = [ require('../codecity'), require('./code_test'), require('./dump_test'), require('./dumper_test'), require('./interpreter_test'), require('./interpreter_unit_test'), require('./interpreter_test'), require('./iterable_weakmap_test'), require('./iterable_weakset_test'), require('./registry_test'), require('./priorityqueue_test'), require('./selector_test'), require('./serialize_test'), require('./interpreter_bench'), require('./serialize_bench'), ]; // Force compilation of tests/benchmarks (for synta const fs = require('fs'); const {T, B} = require('./testing'); /** * Run benchmarks. * @param {!Array} files Filenames containing benchmarks to run. */ async function runBenchmarks(files) { for (var i = 0; i < files.length; i++) { var benchmarks = require(files[i]); var b = new B; if (!compileTargets.includes(benchmarks)) { b.result('WARN', files[i] + ' is not being checked by closure-compiler'); } for (var k in benchmarks) { if (k.startsWith('bench') && typeof benchmarks[k] === 'function') { try { await benchmarks[k](b); } catch (e) { b.crash(k, e); } } } } } /** * Run tests. * @param {!Array} files Filenames containing tests to run. */ async function runTests(files) { var t = new T; for (var i = 0; i < files.length; i++) { var tests = require(files[i]); if (!compileTargets.includes(tests)) { t.result('WARN', files[i] + ' is not being checked by closure-compiler'); } for (var k in tests) { if (k.startsWith('test') && typeof tests[k] === 'function') { try { await tests[k](t); } catch (e) { t.crash(k, e); } } } } // Print results summary. console.log('\n%s\n', String(t)); } /** * Get list of test filenames matching a particular regexp. * @param {!RegExp} pattern RegExp to match. * @return {!Array} List of filenames. */ function getFiles(pattern) { var f = fs.readdirSync(__dirname); // __dirname is location of this module. return f.filter(function (fn) { return pattern.test(fn); }). map(function (fn) { return './' + fn; }); } /////////////////////////////////////////////////////////////////////////////// // Main program // (async function main() { await runTests(getFiles(/_test.js$/)); await runBenchmarks(getFiles(/_bench.js$/)); })(); ================================================ FILE: server/tests/selector_test.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test for CSS-style selectors for JS objects. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const Selector = require('../selector'); const {T} = require('./testing'); const util = require('util'); /** * Unit tests for Selector * @param {!T} t The test runner object. */ exports.testSelector = function(t) { const cases = [ // Test cases of form [SS, [P1, P2, ...], tS, tE, tSE] where // SS: selector string, to use as argument to Selector constructor, // [Pn...]: expected parts array, // tS: expected toString output, // tE: expected toExpr output (can be omitted if same), // tSE: expected toSetExpr output (if different not same + ' = NEW'). ['foo', ['foo'], 'foo'], ['foo.bar', ['foo', 'bar'], 'foo.bar'], ['foo["bar"]', ['foo', 'bar'], 'foo.bar'], ["foo['bar']", ['foo', 'bar'], 'foo.bar'], ['foo[42]', ['foo', '42'], 'foo[42]'], ["foo['42']", ['foo', '42'], 'foo[42]'], ['foo["42"]', ['foo', '42'], 'foo[42]'], ['foo["bar baz"]', ['foo', 'bar baz'], "foo['bar baz']"], ["foo['bar baz']", ['foo', 'bar baz'], "foo['bar baz']"], ["foo['\"\\'\"']", ['foo', '"\'"'], "foo['\"\\'\"']"], ['foo["\'\\"\'"]', ['foo', "'\"'"], 'foo["\'\\"\'"]'], ['foo.bar.baz', ['foo', 'bar', 'baz'], 'foo.bar.baz'], ['$._.__.$$', ['$', '_', '__', '$$'], '$._.__.$$'], ['foo^', ['foo', Selector.PROTOTYPE], 'foo{proto}', 'Object.getPrototypeOf(foo)', 'Object.setPrototypeOf(foo, NEW)'], ['foo{proto}.bar', ['foo', Selector.PROTOTYPE, 'bar'], 'foo{proto}.bar', 'Object.getPrototypeOf(foo).bar', 'Object.getPrototypeOf(foo).bar = NEW'], ['foo{owner}', ['foo', Selector.OWNER], 'foo{owner}', 'Object.getOwnerOf(foo)', 'Object.setOwnerOf(foo, NEW)'], ['foo{owner}.bar', ['foo', Selector.OWNER, 'bar'], 'foo{owner}.bar', 'Object.getOwnerOf(foo).bar', 'Object.getOwnerOf(foo).bar = NEW'], ]; for (const [input, parts, str, expr, setExpr] of cases) { // Do test with selector string. let name = util.format('new Selector(%o)', input); let s = new Selector(input); t.expect(name + '.length', s.length, parts.length); for (let i = 0; i < s.length; i++) { t.expect(util.format('%s[%d]', name, i), s[i], parts[i]); } t.expect(name + '.toString()', s.toString(), str); let expectedExpr = expr || str; t.expect(name + '.toExpr()', s.toExpr(), expectedExpr); let expectedSetExpr = setExpr || expectedExpr + ' = NEW'; t.expect(name + '.toSetExpr()', s.toSetExpr('NEW'), expectedSetExpr); // Repeat test using parts array. name = util.format('new Selector(%o)', parts); s = new Selector(parts); t.expect(name + '.toString()', s.toString(), str); t.expect(name + '.toExpr()', s.toExpr(), expectedExpr); t.expect(name + '.toSetExpr()', s.toSetExpr('NEW'), expectedSetExpr); } const invalidCases = [ '1foo', 'foo.', 'foo["bar]', "foo[bar']", 'foo.[42]', 'foo[42', 'foo42]', 'foo[42}', "foo['\"'\"']", 'foo["\'"\'"]', 'foo^bar', '^.bar', ['1foo'], '^', '{proto}', [Selector.PROTOTYPE], "foo['bar'}", 'foo{proto]', 'foo{proto', 'foo.proto}', 'foo{blah}', 'foo{}', '{owner}', [Selector.OWNER], ]; for (const input of invalidCases) { // Do test with selector string. const name = util.format('new Selector(%o)', input); try { new Selector(input); t.fail(name, "didn't throw"); } catch (e) { t.pass(name); } } }; /** * Unit tests for Selector.prototype.isVar / isProp / isProto * @param {!T} t The test runner object. */ exports.testSelectorPrototypeIsWhatever = function(t) { const cases = [ // Test cases of form [selector, isVar]. ['foo', true, false, false, false], ['foo.bar', false, true, false, false], ['foo^', false, false, true, false], ['foo{proto}', false, false, true, false], ['foo{owner}', false, false, false, true], ]; for (const [input, isVar, isProp, isProto, isOwner] of cases) { const name = util.format('new Selector(%o)', input); const s = new Selector(input); t.expect(name + '.isVar()', s.isVar(), isVar); t.expect(name + '.isProp()', s.isProp(), isProp); t.expect(name + '.isProto()', s.isProto(), isProto); t.expect(name + '.isOwner()', s.isOwner(), isOwner); } }; /** * Unit tests for Selector.partBadness * @param {!T} t The test runner object. */ exports.testSelectorPartBadness = function(t) { // Test verifies these are in monotonically increasing order of badness. const cases = [ 'bar', 'quux', '10', '100', '&', '&*', 'ridiculouslyLongIdentifier', '2872498713723', '#^@*%*!@#', Selector.PROTOTYPE, ]; let previous = '(no previous)'; let previousBadness = -Infinity; for (const part of cases) { const badness = Selector.partBadness(part); const name = util.format( 'Selector.partBadness(%o) (===%d) < Selector.partBadness(%o) (===%d)', previous, previousBadness, part, badness); t.assert(name, previousBadness < badness); previous = part; previousBadness = badness; } }; /** * Unit tests for Selector.prototype.badness * @param {!T} t The test runner object. */ exports.testSelectorPrototypeBadness = function(t) { // Test verifies these are in monotonically increasing order of badness. const cases = [ 'foo', 'foobar', 'foo.bar', 'foo[10]', 'foo["&"]', 'foo.bar.baz.quux.quuux.quuux', 'foo{proto}', 'foo.bar.baz.quux.quuux.quuux.quuuux.quuuuux.quuuuuux.quuuuuuux', ]; let previous = '(no previous)'; let previousBadness = -Infinity; for (const ss of cases) { const s = new Selector(ss); const badness = s.badness(); const name = util.format('Selector(%o).badness() < Selector(%o).badness()', previous, ss); t.assert(name, previousBadness < badness); previous = ss; previousBadness = badness; } }; ================================================ FILE: server/tests/serialize_bench.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Benchmarks for JavaScript interpreter. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const fs = require('fs'); const path = require('path'); const util = require('util'); const Interpreter = require('../interpreter'); const {getInterpreter, startupFiles} = require('./interpreter_common'); const Serializer = require('../serialize'); /** * Run a benchmark of the interpreter being serialized/deserialized. * @param {!B} b The benchmark runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled before roundtripping. * @param {function(!Interpreter)=} initFunc Optional function to be * called after creating new interpreter instance but before * running src. Can be used to insert extra native functions into * the interpreter. initFunc is called with the interpreter * instance to be configured as its parameter. */ function runSerializationBench(b, name, src, initFunc) { for (let i = 0; i < 4; i++) { const intrp1 = new Interpreter(); const intrp2 = new Interpreter(); if (initFunc) { initFunc(intrp1); initFunc(intrp2); } const err = undefined; try { intrp1.createThreadForSrc(src); intrp1.run(); intrp1.stop(); b.start(name, i); let json = Serializer.serialize(intrp1); b.end(name + ' serialize', i); let str = JSON.stringify(json); let len = str.length; b.end(name + ' stringify (' + Math.ceil(len / 1024) + 'kiB)', i); json = JSON.parse(str); b.end(name + ' parse', i); Serializer.deserialize(json, intrp2); b.end(name + ' deserialize', i); } catch (err) { b.crash(name, util.format('%s\n%s', src, err.stack)); } } }; /** * Run a benchmark of the interpreter being serialized/deserialized. * @param {!B} b The benchmark runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled before roundtripping. * @param {function(!Interpreter)=} initFunc Optional function to be * called after creating new interpreter instance but before * running src. Can be used to insert extra native functions into * the interpreter. initFunc is called with the interpreter * instance to be configured as its parameter. */ function runDeserializationBench(b, name, src, initFunc) { for (var i = 0; i < 4; i++) { const intrp1 = new Interpreter(); const intrp2 = new Interpreter(); if (initFunc) { initFunc(intrp1); initFunc(intrp2); } const err = undefined; try { intrp1.createThreadForSrc(src); intrp1.run(); intrp1.stop(); b.start(name, i); const json = Serializer.serialize(intrp1); var len = JSON.stringify(json).length; Serializer.deserialize(json, intrp2); b.end(name + ' (' + Math.ceil(len / 1024) + 'kiB)', i); } catch (err) { b.crash(name, util.format('%s\n%s', src, err.stack)); } } }; /** * Run a benchmark of the interpreter after being * serialized/deserialized. * @param {!B} b The benchmark runner object. * @param {string} name The name of the test. * @param {string} src The code to be evaled. */ function runInterpreterBench(b, name, src) { for (let i = 0; i < 4; i++) { const intrp1 = getInterpreter(); const intrp2 = new Interpreter(); try { intrp1.createThreadForSrc(src); intrp1.stop(); const json = Serializer.serialize(intrp1); Serializer.deserialize(json, intrp2); // Deserialized interpreter was stopped, but we want to be able to // step/run it, so wake it up to PAUSED. intrp2.pause(); b.start(name, i); intrp2.run(); b.end(name, i); } catch (err) { b.crash(name, util.format('%s\n%s', src, err.stack)); } finally { intrp2.stop(); } } }; /** * Run benchmarks roundtripping the interpreter. * @param {!B} b The test runner object. */ exports.benchRoundtrip = function(b) { let name = 'Roundtrip demo'; const demoDir = path.join(__dirname, '../../core'); const filenames = fs.readdirSync(demoDir); filenames.sort(); let src = ''; for (const filename of filenames) { if (!(filename.match(/.js$/))) continue; src += fs.readFileSync(String(path.join(demoDir, filename))); } const fakeBuiltins = function(intrp) { // Hack to install stubs for builtins found in codecity.js. const builtins = [ 'CC.log', 'CC.checkpoint', 'CC.shutdown', 'CC.hash', 'CC.acorn.parse', 'CC.acorn.parseExpressionAt', ]; for (const bi of builtins) { new intrp.NativeFunction({id: bi, length: 0,}); } }; runSerializationBench(b, name, src, fakeBuiltins); }; /** * Run the fibbonacci10k benchmark. * @param {!B} b The test runner object. */ exports.benchResurrectedFibbonacci10k = function(b) { let name = 'ressurrectedFibonacci10k'; let src = ` var fibonacci = function(n, output) { var a = 1, b = 1, sum; for (var i = 0; i < n; i++) { output.push(a); sum = a + b; a = b; b = sum; } } for(var i = 0; i < 10000; i++) { var result = []; fibonacci(78, result); } result; `; runInterpreterBench(b, name, src); }; ================================================ FILE: server/tests/serialize_test.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Serialization/deserialization tests for JavaScript interpreter. * @author fraser@google.com (Neil Fraser) */ 'use strict'; const net = require('net'); const util = require('util'); const Interpreter = require('../interpreter'); const {getInterpreter} = require('./interpreter_common'); const Serializer = require('../serialize'); const {T} = require('./testing'); /////////////////////////////////////////////////////////////////////////////// // Test helper functions. /////////////////////////////////////////////////////////////////////////////// /** * Serialize an interpreter to JSON, then create and return a new * interpreter by deserializing that JSON. * @param {!Interpreter} intrp The interpreter to be serialized. * @return {?Interpreter} the freshly deserialized interpreter, or * null if an error occurred. */ function roundTrip(intrp) { intrp.pause(); // Save timer info. const json = JSON.stringify(Serializer.serialize(intrp), null, ' '); const intrp2 = new Interpreter; Serializer.deserialize(JSON.parse(json), intrp2); // Deserialized interpreter was stopped, but we want to be able to // step/run it, so wake it up to PAUSED. intrp2.pause(); return intrp2; } /** * Run a (possibly multiple) roundtrip test: * - Create an interpreter instance. * - Create a thread to eval src1, and run it to completion. * - Create a thread to eval src2 * - Step through src2, periodically serializing and unserializing. * - Do a final round-trip serialization, if none done yet. * - Create a thread to eval src3, and run it to completion. * - Verify value of final expression evaluated is === expected. * @param {!T} t The test runner object. * @param {string} name The name of the test. * @param {string} src1 The code to be evaled before any serialization. * @param {string} src2 The code to be evaled while periodically serializing. * @param {string} src3 The code to be evaled after final serialization. * @param {number|string|boolean|null|undefined} expected The expected * completion value. * @param {!TestOptions=} options Custom test options. */ function runTest(t, name, src1, src2, src3, expected, options) { options = options || {}; let intrp = getInterpreter(options.options, options.standardInit); if (options.onCreate) { options.onCreate(intrp); } let thread; try { if (src1) { thread = intrp.createThreadForSrc(src1).thread; intrp.run(); } } catch (e) { t.crash(name + 'Pre', e); return; } try { if (src2) { thread = intrp.createThreadForSrc(src2).thread; } let trips = 0; if (options.steps === undefined) { intrp.run(); } else { let s = 0; while(intrp.step()) { if ((++s % options.steps) === 0) { intrp = roundTrip(intrp); trips++; } } } if (trips === 0) { intrp = roundTrip(intrp); trips++; } } catch (e) { t.crash(name, e); return; } try { intrp.run(); if (src3) { thread = intrp.createThreadForSrc(src3).thread; intrp.run(); } } catch (e) { t.crash(name + 'Post', e); return; } const r = intrp.pseudoToNative(thread.value); const allSrc = util.format( '%s\n/* begin roundtrips */\n%s\n/* end roundtrips */\n%s', src1, src2, src3); t.expect(name, r, expected, allSrc); }; /** * Run a (truly) asynchronous roundtrip test of the interpreter. * A new Interpreter instance is created for each test. Special functions * resolve() and reject() are inserted in the global scope; they will * end each section of the test. The caller can additionally supply a * callback to be run before starting the interpreter. * * Full procedure: * - Create and initialize an interpreter instance. * - Call options.onCreate, if supplied, on first interpreter instance. * - Start the interpreter and run src1 (if supplied). * - Await a call to resolve() or reject(); abort the test if the latter occurs. * - Stop the interpreter. * - Serialize interpreter to JSON. * - Create second interpreter instance. Don't initialize it. * - Call options.onCreate, if supplied, on second interpreter instance. * - Deserialize JSON into second interpreter instance. * - Start the second interpreter and allow it to run to completion. * - Run src2 (if supplied). * - Await a call to resolve() or reject(). * - If resolve was called, verify the result is as expected. * @param {!T} t The test runner object. * @param {string} name The name of the test. * @param {string} src1 The code to be evaled before serialization. * @param {string} src2 The code to be evaled after serialization. * @param {number|string|boolean|null|undefined} expected The expected * completion value. * @param {!TestOptions=} options Custom test options. */ async function runAsyncTest(t, name, src1, src2, expected, options) { options = options || {}; const intrp1 = getInterpreter(options.options, options.standardInit); if (options.onCreate) { options.onCreate(intrp1); } let thread; // Create promise to signal completion of test from within // interpreter. Awaiting p will block until resolve or reject is // called. let resolve, reject, result; let p = new Promise(function(res, rej) { resolve = res; reject = rej; }); intrp1.global.createMutableBinding( 'resolve', intrp1.createNativeFunction('resolve', resolve, false)); intrp1.global.createMutableBinding( 'reject', intrp1.createNativeFunction('reject', reject, false)); try { intrp1.start(); if (src1) { intrp1.createThreadForSrc(src1); } await p; intrp1.pause(); } catch (e) { t.crash(name + 'Pre', e); return; } // Serialize. let json; try { json = JSON.stringify(Serializer.serialize(intrp1), null, ' '); } catch (e) { t.crash(name + 'Serialize', e); return; } intrp1.stop(); // Restore into new interpreter. const intrp2 = getInterpreter(options.options, options.standardInit); if (options.onCreate) { options.onCreate(intrp2); } // New promise. p = new Promise(function(res, rej) { resolve = res; reject = rej; }); intrp2.global.createMutableBinding( 'resolve', intrp2.createNativeFunction('resolve', resolve, false)); intrp2.global.createMutableBinding( 'reject', intrp2.createNativeFunction('reject', reject, false)); try { Serializer.deserialize(JSON.parse(json), intrp2); } catch (e) { t.crash(name + 'Deserialize', e); return; } try { intrp2.start(); if (src2) { intrp2.createThreadForSrc(src2); } result = await p; } catch (e) { t.crash(name + 'Post', e); return; } finally { intrp2.stop(); } const r = intrp2.pseudoToNative(result); const allSrc = util.format('%s\n/* roundtrip */\n%s', src1, src2); t.expect(name, r, expected, allSrc); }; /** * Options for runTest and runAsyncTest. * @record */ const TestOptions = function() {}; /** * Interpreter constructor options. * @type {!Interpreter.Options|undefined} */ TestOptions.prototype.options; /** * Load the standard startup files at startup? (Default: true.) * Setting to false speeds up tests with many roundtrips that do not * need builtins. * @type {boolean|undefined} */ TestOptions.prototype.standardInit; /** * Callback to be called after creating new interpreter instance (and * running standard starup files, if not suppressed with standardInit: * false) but before creating a thread for srcN. Can be used to * insert extra bindings into the global scope (e.g., to create * additional builtins). * * The first argument is the interpreter instance to be configured. * * @type {function(!Interpreter)|undefined} */ TestOptions.prototype.onCreate; /** * How many steps to run between serializations (run src1 to * completion if unspecified). * @type {number|undefined} */ TestOptions.prototype.steps; /////////////////////////////////////////////////////////////////////////////// // Tests: serialisation /////////////////////////////////////////////////////////////////////////////// /** * Run a round trip serialization-deserialization. * @param {!T} t The test runner object. */ exports.testRoundtripSimple = function(t) { runTest(t, 'testRoundtripSimple', '', ` var x = 1; for (var i = 0; i < 8; i++) { x *= 2; } `, 'x;', 256, {steps: 100}); }; /** * Run a round trip of serializing the Interpreter.SCOPE_REFERENCE * sentinel and an Interpreter.PropertyIterator. * * BUG(#193): running this test causes *subsequent* benchmarks to run * about 15% slower for no obvious reason. Investigate. * @param {!T} t The test runner object. */ exports.testRoundtripScopeRefAndPropIter = function(t) { runTest(t, 'testRoundtripScopeRefAndPropIter', ` var r = 0, o = {a: 1, b: 2}; `,` for (var k in o) { r += o[k]; } `, 'r;', 3, {steps: 1, standardInit: false}); }; /** * Run a round trip of serializing WeakMaps. * @param {!T} t The test runner object. */ exports.testRoundtripWeakMap = function(t) { runTest(t, 'testRoundtripWeakMap', ` var o1 = {}; var wm = new WeakMap; var o2 = {}; wm.set(o1, 105); wm.set(o2, 42); var empty = new WeakMap; `, '', ` (empty instanceof WeakMap) && (wm instanceof WeakMap) && wm.get(o1) - wm.get(o2); `, 105 - 42); }; /** * Run more detailed tests of the state of the post-rountrip interpreter. * @param {!T} t The test runner object. */ exports.testRoundtripDetails = function(t) { runTest(t, 'testRoundtripPropertyAttributes', ` var obj = {}; for (var i = 0; i < 8; i++) { var desc = {value: i, writable: !!(i & 0x1), enumerable: !!(i & 0x2), configurable: !!(i & 0x4)}; Object.defineProperty(obj, i, desc); } `, '', ` for (var i = 0; i < 8; i++) { desc = Object.getOwnPropertyDescriptor(obj, i); if (desc.value !== i || desc.writable !== !!(i & 0x1) || desc.enumerable !== !!(i & 0x2) || desc.configurable !== !!(i & 0x4)) { throw new Error('Roundtrip failure for property ' + i); } } 'All good'; `, 'All good'); runTest(t, 'testRoundtripObjectExtensibility', ` var ext = {}; var nonExt = {}; Object.preventExtensions(nonExt); `, '', ` Object.isExtensible(ext) && !Object.isExtensible(nonExt); `, true); // Test preservation of prototype identity, including protypes used // by various built-in functions. // // exprs is a large object literal which maps built-in constructors // to arrays of values which should all be that constructor's // .prototype object. const exprs = `{ Object: [ Object.prototype, new 'Object.prototype', Object.getPrototypeOf(new Object), Object.getPrototypeOf({}), Object.getPrototypeOf(Object.getOwnPropertyDescriptor( Object.prototype, 'constructor')), ], Function: [ Function.prototype, new 'Function.prototype', Object.getPrototypeOf(new Function), Object.getPrototypeOf(function() {}), Object.getPrototypeOf(Function), ], Array: [ Array.prototype, new 'Array.prototype', Object.getPrototypeOf(new Array), Object.getPrototypeOf([]), Object.getPrototypeOf([].slice(0,0)), ], Boolean: [ Boolean.prototype, new 'Boolean.prototype', Object.getPrototypeOf(false), ], Number: [ Number.prototype, new 'Number.prototype', Object.getPrototypeOf(0), ], String: [ String.prototype, new 'String.prototype', Object.getPrototypeOf(''), ], RegExp: [ RegExp.prototype, new 'RegExp.prototype', Object.getPrototypeOf(new RegExp), Object.getPrototypeOf(/foo/), ],${['Date', 'Error', 'EvalError', 'RangeError', 'SyntaxError', 'TypeError', 'URIError', 'PermissionError'].map((c) => ` ${c}: [ ${c}.prototype, new '${c}.prototype', Object.getPrototypeOf(new ${c}), ],`).join('')} }`; runTest(t, 'testRoundtripBuiltinPrototypes', ` var pre = ${exprs}; `, '', ` var post = ${exprs}; try { // Check expressions all had same value intially. for (var key in pre) { if (!pre.hasOwnProperty(key)) continue; for (var i = 1; i < pre[key].length; i++) { if (pre[key][0] !== pre[key][i]) { throw 'pre["' + key + '"][0] !== pre["' + key + '"][' + i + ']'; } } } // Check expressions all had same value before and after. for (var key in pre) { if (!pre.hasOwnProperty(key)) continue; for (var i = 0; i < pre[key].length; i++) { if (pre[key][i] !== post[key][i]) { throw 'pre["' + key + '"][' + i + '] !== post["' + key + '"][' + i + ']'; } } } 'OK'; } catch (e) { e; } `, 'OK'); runTest(t, 'testRoundtripArrayLengthRemainsMagical', ` var arr = [0, 1, 2]; `, '', ` arr[3] = 3; arr.length; `, 4); }; /** * Run tests of post-roundtrip interpreter timers & networking state. * @param {!T} t The test runner object. */ exports.testRoundtripAsync = async function(t) { // Run a test of timer preservation during serialization/deserialization. var name = 'testRestoreTimers'; var src1 = ` var x = ''; setTimeout(function() { x += '1'; }, 0); setTimeout(function() { resolve(); }, 10); setTimeout(function() { x += '3'; }, 20); setTimeout(function() { x += '4'; }, 40); `; var src2 = ` x += '2'; setTimeout(function() { resolve(x); }, 11); `; await runAsyncTest(t, name, src1, src2, '123'); // Run a test of the server re-listening to sockets after being // deserialized. name = 'testPostRestoreNetworkInbound'; src1 = ` var data = '', conn = {}; conn.onReceive = function(d) { data += d; }; conn.onEnd = function() { CC.connectionClose(this); CC.connectionUnlisten(8888); resolve(data); }; CC.connectionListen(8888, conn); resolve(); `; src2 = ` send(); `; const installSend = function(intrp) { intrp.global.createMutableBinding('send', intrp.createNativeFunction( 'send', function() { // Send some data to server. var client = net.createConnection({ port: 8888 }, function() { client.write('foo'); client.write('bar'); client.end(); }); })); }; await runAsyncTest(t, name, src1, src2, 'foobar', { options: {noLog: ['net']}, onCreate: installSend, }); // Run a test to verify that the connection object's .error method // is called with a suitable Error object if the previously-listened // port is in use when the interpreter is restarted. name = 'testFailedRelistenFiresError'; src1 = ` var connection = {onError: function(err) {resolve(err.name);}}; CC.connectionListen(8888, connection); resolve(); // Start serialisation roundtrip. `; src2 = ` suspend(); // Allow pending onError thread to run. resolve('No error thrown'); `; let /** number */ count = 0; let /** ?net.Server */ server = null; const blockPort = function(intrp) { if (count++) { // Do only when creating post-roundtrip Interpreter. server = new net.Server(); server.listen(8888); } }; await runAsyncTest(t, name, src1, src2, 'Error', { options: {noLog: ['net']}, onCreate: blockPort, }); server.close(); }; ================================================ FILE: server/tests/testcases.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Test cases for JavaScript interpreter. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; // Testcases for testSimple in interpreter_test.js. module.exports = [ {src: `1 + 1;`, expected: 2}, {src: `2 + 2;`, expected: 4}, {src: `6 * 7;`, expected: 42}, {src: `(3 + 12 / 4) * (10 - 3);`, expected: 42}, {src: `var x = 43; x;`, expected: 43}, {src: `true ? 'then' : 'else';`, expected: 'then'}, {src: `false ? 'then' : 'else';`, expected: 'else'}, { name: 'if(true)', src: ` if (true) { 'then'; } else { 'else'; } `, expected: 'then', }, { name: 'if(false)', src: ` if (false) { 'then'; } else { 'else'; } `, expected: 'else', }, { name: 'simpleAssignment', src: `var x = 0; x = 44; x;`, expected: 44, }, { name: 'propertyAssignment', src: `var o = {}; o.foo = 45; o.foo;`, expected: 45, }, { name: 'getPropertyOnPrimitive', src: `'foo'.length;`, expected: 3, }, { name: 'setPropertyOnPrimitive', src: ` try { 'foo'.bar = 42; } catch (e) { e.name; } `, expected: 'TypeError', }, {src: `var x = 45; x++; x++;`, expected: 46}, {src: `var x = 45; ++x; ++x;`, expected: 47}, {src: `'foo' + 'bar';`, expected: 'foobar'}, { name: 'Effect of += on left argument', src: `var x = 40, y = 8; x += y; x;`, expected: 48, }, { name: 'Effect of += on right argument', src: `var x = 40, y = 8; x += y; y;`, expected: 8, }, { name: 'FunctionExpression', src: `var v, f = function() {v = 49;}; f(); v;`, expected: 49, }, { name: 'variable assignment sets anonymous function name', src: ` var myAssignedFunc; myAssignedFunc = function() {}; myAssignedFunc.name; `, expected: 'myAssignedFunc', }, { name: 'property assignment does not set anonymous FunctionExpression name', src: ` var obj = {}; obj.myMethod = function() {}; obj.myMethod.name; `, expected: '', }, { // This one is a CodeCity extension. name: 'property assignment optionally sets anonymous function name', src: ` var obj = {}; obj.myMethod = function() {}; obj.myMethod.name; `, options: {methodNames: true}, expected: 'myMethod', }, { name: 'object expression sets anonymous FunctionExpression name', src: `({myPropFunc: function() {}}).myPropFunc.name;`, expected: 'myPropFunc', }, { name: 'variable declaration sets anonymous FunctionExpression name', src: `var myVarDeclFunc = function() {}; myVarDeclFunc.name;`, expected: 'myVarDeclFunc', }, { name: 'funExpWithParameter', src: `var v; var f = function(x) {v = x;}; f(50); v;`, expected: 50, }, { name: 'funExpParameterNotShadowedByVar', src: `var f = function(x) {var x; return x;}; f(50.1);`, expected: 50.1, }, { name: 'funExpParameterNotShadowedByVar', src: `var f = function(x) {var x = 50.2; return x;}; f(50.2);`, expected: 50.2, }, { name: 'functionWithReturn', src: `(function(x) {return x;})(51);`, expected: 51, }, { name: 'functionWithoutReturn', src: `(function() {})();`, expected: undefined, }, { name: 'multipleReturn', src: ` var f = function() { try { return true; } finally { return false; } } f(); `, expected: false, }, { name: 'throwCatch', src: ` var f = function() { throw 26; } try { f(); } catch (e) { e * 2; } `, expected: 52, }, { name: 'throwCatchFalsey', src: ` try { throw null; } catch (e) { 'caught ' + String(e); } `, expected: 'caught null', }, // N.B.: This and next tests have no equivalent in the test DB. { name: 'throwUnhandledError', src: `throw new Error('not caught');`, options: {noLog: ['unhandled']}, expected: undefined, }, { name: 'throwUnhandledException', src: `throw 'not caught';`, options: {noLog: ['unhandled']}, expected: undefined, }, { src: `try {throw new Error('not caught');} finally {}`, options: {noLog: ['unhandled']}, expected: undefined, }, { src: `try {throw 'not caught';} finally {}`, options: {noLog: ['unhandled']}, expected: undefined, }, {src: `51, 52, 53;`, expected: 53}, { name: 'sequenceExpression', src: ` var x, y, z; x = (y = 60, z = 5, 0.5); x + y + z; `, expected: 65.5, }, { name: 'labeledStatement', src: `foo: 54;`, expected: 54, }, { name: 'whileLoop', src: ` var a = 0; while (a < 55) a++; a; `, expected: 55, }, { name: 'while(false)', src: ` var a = 56; while (false) a++; a; `, expected: 56, }, { name: 'do ... while(false)', src: ` var a = 56; do a++; while (false); a; `, expected: 57, }, { name: 'do ... break ... while', src: ` var a = 57; do { a++; break; a++; } while (false); a; `, expected: 58, }, { src: `foo: break foo;`, expected: undefined, // (but legal!) }, { name: 'try ... break ... finally', src: ` var a = 6; foo: { try { a *= 10; break foo; } finally { a--; } } a; `, expected: 59, }, { name: 'do ... while with try ... continue ... finally ...', src: ` var a = 59; do { try { continue; } finally { a++; } } while (false); a; `, expected: 60, }, { name: 'while with try ... break ... finally continue', src: ` var a = 0; while (a++ < 60) { try { break; } finally { continue; } } a; `, expected: 61, }, { name: 'while with try ... return ... finally continue', src: ` (function() { var i = 0; while (i++ < 61) { try { return 42; } finally { continue; } } return i; })(); `, expected: 62, }, {src: `63 || 'foo';`, expected: 63}, {src: `false || 64;`, expected: 64}, { name: '|| short-circuit', src: `var r = 0; true || (r++); r;`, expected: 0, }, {src: `({}) && 65;`, expected: 65}, {src: `0 && 65;`, expected: 0}, { name: '&& sort-circuit', src: `var r = 0; false && (r++); r;`, expected: 0, }, { name: 'for', src: ` var t = 0; for (var i = 0; i < 12; i++) { t += i; } t; `, expected: 66, }, { name: 'forIn', src: ` var x = 0, a = {a: 60, b:3, c:4}; for (var i in a) {x += a[i];} x; `, expected: 67, }, { name: 'forInMemberExp', src: ` var x = 1, o = {foo: 'bar'}, a = {a:2, b:2, c:17}; for (o.foo in a) {x *= a[o.foo];} x; `, expected: 68, }, { name: 'forInMembFunc', src: ` var x = 0, o = {}; var f = function() {x += 20; return o;}; var a = {a:2, b:3, c:4}; for (f().foo in a) {x += a[o.foo];} x; `, expected: 69, }, { name: 'forInNullUndefined', src: ` var x = 0, o = {}; var f = function() {x++; return o;}; for (f().foo in null) {x++;} for (f().foo in undefined) {x++;} x; `, expected: 0, }, { name: 'switchDefaultFirst', src: ` switch ('not found') { default: 'OK'; break; case 'decoy': 'fail'; }; `, expected: 'OK', }, { name: 'switchDefaultOnly', src: ` switch ('not found') { default: 'OK'; }; `, expected: 'OK', }, { name: 'switchEmptyToEnd', src: ` 'ok'; switch ('foo') { default: 'fail'; case 'foo': case 'bar': }; `, expected: 'ok', }, { name: 'value of this in function call', src: ` var f = function() {return this;}; f(); `, expected: undefined, }, { name: 'value of this in method call', src: ` var obj = {method: function() {return this;}}; obj.method() === obj; `, expected: true, }, { name: 'value of this in method called as function', src: ` var obj = {method: function() {return this;}}; var f = obj.method; f(); `, expected: undefined, }, { name: 'value of this outside function body', src: `this === undefined;`, expected: true, }, { name: 'value of this not boxed (in strict mode)', destructive: true, // Modifies String.prototype! src: ` String.prototype.method = function() {return typeof this;}; 'a primitive string'.method(); `, expected: 'string', // Would be an [object String] in non-strict mode. }, {src: `[].length;`, expected: 0}, {src: `[1,,3,,].length;`, expected: 4}, { name: 'arrayElidedNotDefinedNotUndefined', src: ` var a = [,undefined,null,0,false]; !(0 in a) && (1 in a) && (2 in a) && (3 in a) && (4 in a); `, expected: true, }, { name: 'arrayLengthPropertyDescriptor', src: ` var a = [1, 2, 3]; var pd = Object.getOwnPropertyDescriptor(a, 'length'); (pd.value === 3) && pd.writable && !pd.enumerable && !pd.configurable; `, expected: true, }, { name: 'arrayLength', src: ` try { var a; function checkLen(exp, desc) { if (a.length !== exp) { var msg = 'a.length === ' + a.length + ' (expected: ' + exp + ')' throw new Error(desc ? msg + ' ' + desc : msg); } } // Empty array has length == 0 a = []; checkLen(0, 'on empty array'); // Adding non-numeric properties does not increase length: a['zero'] = 0; checkLen(0, 'after setting non-index property on []'); // Adding numeric properties >= length does increase length: for (var i = 0; i < 5; i++) { a[i] = i; checkLen(i + 1, 'after setting a[' + i + ']'); } // .length works propery even for large, sparse arrays, and even // if values are undefined: for (i = 3; i <= 31; i++) { var idx = (1 << i) >>> 0; // >>> 0 converts int32 to uint32 a[idx] = undefined; checkLen(idx + 1, 'after setting a[' + idx + ']'); } // Adding numeric properties < length does not increase length: a[idx - 1] = 'not the largest'; checkLen(idx + 1, 'after setting non-largest element'); // Verify behaviour around largest possible index: a[0xfffffffd] = null; checkLen(0xfffffffe); a[0xfffffffe] = null; checkLen(0xffffffff); a[0xffffffff] = null; // Not an index. checkLen(0xffffffff); // Unchanged. a[0x100000000] = null; // Not an index. checkLen(0xffffffff); // Unchanged. function checkIdx(idx, exp, desc) { var r = a.hasOwnProperty(idx); if (r !== exp) { var msg = 'a.hasOwnProperty(' + idx + ') === ' + r; throw new Error(desc ? msg + ' ' + desc : msg); } } // Setting length to existing value should have no effect: a.length = 0xffffffff; checkIdx(0xfffffffd, true); checkIdx(0xfffffffe, true); checkIdx(0xffffffff, true); checkIdx(0x100000000, true); // Setting length one less than maximum should remove largest // index, but leave properties with keys too large to be indexes: a.length = 0xfffffffe; checkIdx(0xfffffffd, true); checkIdx(0xfffffffe, false); checkIdx(0xffffffff, true); checkIdx(0x100000000, true); // Setting length to zero should remove all index properties: a.length = 0; for (var key in a) { if (!a.hasOwnProperty(key)) { continue; } if (String(key >>> 0) === key && (key >>> 0) !== 0xffffffff) { throw new Error( 'Setting a.length = 0 failed to remove property ' + key); } } // Make sure we didn't wipe everything! if (Object.getOwnPropertyNames(a).length !== 4) { throw new Error( 'Setting .length == 0 removed some non-index properties'); } 'OK'; } catch (e) { String(e); } `, expected: 'OK', }, { name: 'arrayLengthWithNonWritableProps', src: ` var a = []; Object.defineProperty(a, 0, {value: 'hi', writable: false, configurable: true}); a.length = 0; a[0] === undefined && a.length === 0; `, expected: true, }, { name: 'arrayLengthWithNonConfigurableProps', src: ` var a = []; Object.defineProperty(a, 0, {value: 'hi', writable: false, configurable: false}); try { a.length = 0; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'compValEmptyBlock', src: `{};`, expected: undefined, }, {src: `undefined;`, expected: undefined}, { name: 'unaryVoid', src: `var x = 70; (undefined === void x++) && x;`, expected: 71, }, {src: `+'72';`, expected: 72}, {src: `-73;`, expected: -73}, {src: `~0xffffffb5;`, expected: 74}, {src: `!false && (!true === false);`, expected: true}, {src: `typeof undefined;`, expected: 'undefined'}, {src: `typeof null;`, expected: 'object'}, {src: `typeof false;`, expected: 'boolean'}, {src: `typeof 0;`, expected: 'number'}, {src: `typeof '';`, expected: 'string'}, {src: `typeof {};`, expected: 'object'}, {src: `typeof [];`, expected: 'object'}, {src: `typeof function() {};`, expected: 'function'}, { name: 'unaryTypeofUndeclared', src: ` try { typeof undeclaredVar; } catch (e) { 'whoops!' } `, expected: 'undefined', }, { name: 'binaryIn', src: `var o = {foo: 'bar'}; 'foo' in o && !('bar' in o);`, expected: true, }, { name: 'binaryInParent', src: ` var p = {foo: 'bar'}; var o = Object.create(p); 'foo' in o && !('bar' in o); `, expected: true, }, {src: `'length' in [];`, expected: true}, { name: 'binaryInStringLength', src: ` try { 'length' in ''; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'instanceofBasics', src: ` function F(){} var f = new F; f instanceof F && f instanceof Object && !(f.prototype instanceof F); `, expected: true, }, { name: 'instanceofNonObjectLHS', src: ` function F() {} F.prototype = null; 42 instanceof F; `, expected: false, }, { name: 'instanceofNonFunctionRHS', src: ` try { ({}) instanceof 0; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'instanceofNonObjectPrototype', src: ` function F() {}; F.prototype = 'hello'; try { ({}) instanceof F; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'undefined.foo', src: ` try { undefined.foo; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'undefined.foo = ...', src: ` try { var c = 0; undefined.foo = c++; } catch (e) { e.name + ',' + c; } `, expected: 'TypeError,0', }, { name: 'null.foo', src: ` try { null.foo; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'null.foo = ...', src: ` try { var c = 0; null.foo = c++; } catch (e) { e.name + ',' + c; } `, expected: 'TypeError,0', }, { name: 'delete', src: ` var o = {foo: 'bar'}; (delete o.quux) + ('foo' in o) + (delete o.foo) + !('foo' in o) + (delete o.foo); `, expected: 5, }, { name: 'deleteNonexistentFromPrimitive', src: `(delete false.nonexistent) && (delete (42).toString);`, expected: true, }, // This "actually" tries to delete the non-configurable own .length // property from the auto-boxed String instance created by step 4a // of algorithm in §11.4.1 of the ES 5.1 spec. We have to use a // string here, because only String instances have own properties // (and yes: they are all non-configurable, so delete *always* // fails). { name: 'deleteOwnFromPrimitive', src: ` try { delete 'hello'.length; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'funcDecl', src: ` var v; function f() { v = 75; } f(); v; `, expected: 75, }, { name: 'namedFunctionExpression', src: ` var f = function half(x) { if (x < 100) { return x; } return half(x / 2); }; f(152) `, expected: 76, }, { name: 'namedFunExpNameBinding', src: `var f = function foo() {return foo;}; f() === f;`, expected: true, }, { name: 'namedFunExpNameBindingNoLeak', src: `var f = function foo() {}; typeof foo;`, expected: 'undefined', }, { name: 'namedFunExpNameBindingImmutable', src: ` var f = function foo() { try { foo = null; } catch (e) { return e.name; } }; f(); `, expected: 'TypeError', }, { name: 'namedFunExpNameBindingShadowedByParam', src: ` var f = function foo(foo) { foo += 0.1; // Verify mutability. return foo; }; f(76); `, expected: 76.1, }, { name: 'namedFunExpNameBindingShadowedByVar', src: ` var f = function foo() { var foo; foo = 76.2; // Verify mutability. return foo; }; f(); `, expected: 76.2, }, { name: 'closureIndependence', src: ` function makeAdder(x) { return function(y) {return x + y;}; } var plus3 = makeAdder(3); var plus4 = makeAdder(4); plus3(plus4(70)); `, expected: 77, }, { name: 'internalObjectToString', src: ` var o = {}; o[{}] = null; for(var key in o) { key; } `, expected: '[object Object]', }, { name: 'internalFunctionToString', src: ` var o = {}, s, f = function(){}; o[f] = null; for(var key in o) { s = key; } /^function.*\(.*\).*{[^]*}$/.test(s); `, expected: true, }, { name: 'internalNativeFuncToString', src: ` var o = {}, s, f = Object.create; o[f] = null; for(var key in o) { s = key; } /^function.*\(.*\).*{[^]*}$/.test(s); `, expected: true, }, { name: 'internalArrayToString', src: ` var o = {}; o[[1, 2, 3]] = null; for(var key in o) { key; } `, expected: '1,2,3', }, { name: 'internalDateToString', src: ` var o = {}; o[new Date(0)] = null; for(var key in o) { key; } `, expected: (new Date(0)).toString(), }, { name: 'internalRegExpToString', src: ` var o = {}; o[/foo/g] = null; for(var key in o) { key; } `, expected: '/foo/g', }, { name: 'internalErrorToString', src: ` var o = {}; o[Error('oops')] = null; for(var key in o) { key; } `, expected: 'Error: oops', }, { name: 'internalArgumentsToString', src: ` var o = {}; (function() { o[arguments] = null; })(); for(var key in o) { key; } `, expected: '[object Arguments]', }, {src: `debugger;`, expected: undefined}, { name: 'newExpression', src: ` function T(x, y) {this.sum += x + y;}; T.prototype = {sum: 70} var t = new T(7, 0.7); t.sum; `, expected: 77.7, }, { name: 'newExpressionReturnObj', src: ` function T() {return {};}; T.prototype = {p: 'the prototype'}; (new T).p; `, expected: undefined, }, { name: 'newExpressionReturnPrimitive', src: ` function T() {return 0;}; T.prototype = {p: 'the prototype'}; (new T).p; `, expected: 'the prototype', }, {src: `/foo/.test('foobar');`, expected: true}, { name: 'evalSeeEnclosing', src: `var n = 77.77; eval('n');`, expected: 77.77, }, { name: 'evalIndirectNoSeeEnclosing', src: ` (function() { var n = 77.77, gEval = eval; try { gEval('n'); } catch (e) { return e.name; } })(); `, expected: 'ReferenceError', }, { name: 'evalIndirectNoSeeEnclosing2', src: ` (function() { var n = 77.77; try { (function() {return eval;})()('n'); } catch (e) { return e.name; } })(); `, expected: 'ReferenceError', }, { name: 'evalIndirectSeeGlobal', src: `var gEval = eval; gEval('typeof Array');`, expected: 'function', }, { name: 'evalModifyEnclosing', src: `var n = 77.77; eval('n = 77.88'); n;`, expected: 77.88, }, { name: 'evalNoLeakingDecls', src: `eval('var n = 88.88'); typeof n;`, expected: 'undefined', }, // A bug in eval would cause it to return the value of the // previously-evaluated ExpressionStatement if the eval program did // not contain any ExpressionStatements. { name: 'evalEmptyBlock', src: `'fail'; eval('{}');`, expected: undefined, }, { name: 'callEvalOrder', src: ` var r = ''; function log(x) { r += x; return function() {}; }; (log('f'))(log('a'), log('b'), log('c')); r; `, expected: 'fabc', }, { name: 'callEvalArgsBeforeCallability', src: ` try { var invalid = undefined; function t() {throw {name: 'args'};}; invalid(t()); } catch(e) { e.name; } `, expected: 'args', }, { name: 'callNonCallable', src: ` var tests = [ undefined, null, false, 42, 'hello', Object.create(Function.prototype), ]; var ok = 0; for (var i = 0; i < tests.length; i++) { try { tests[i](); } catch (e) { var r = e; if (e.name === 'TypeError') { ok++; } } } (ok === tests.length) ? 'pass' : 'fail'; `, expected: 'pass', }, ///////////////////////////////////////////////////////////////////////////// // Object and Object.prototype { name: 'Object.defineProperty()', src: ` try { Object.defineProperty(); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.defineProperty non-object', src: ` try { Object.defineProperty('not an object', 'foo', {}); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.defineProperty bad descriptor', src: ` var o = {}; try { Object.defineProperty(o, 'foo', 'not an object'); } catch (e) { e.name; } `, expected: 'TypeError', }, // This also tests iteration over (non-)enumerable properties. { name: 'Object.defineProperty', src: ` var o = {foo: 50}, r = 0; Object.defineProperty(o, 'bar', { writable: true, enumerable: true, configurable: true, value: 0 }); o.bar = 20; Object.defineProperty(o, 'baz', { writable: true, enumerable: true, configurable: false }); Object.defineProperty(o, 'baz', { value: 4, }); Object.defineProperty(o, 'quux', { enumerable: false, value: 13 }); for (var k in o) { r += o[k]; } r += Object.getOwnPropertyNames(o).length; r; `, expected: 78, }, { name: 'Object.getPrototypeOf(null) and undefined', src: ` var r = '', prims = [null, undefined]; for (var i = 0; i < prims.length; i++) { try { Object.getPrototypeOf(prims[i]); } catch (e) { r += e.name; } } r; `, expected: 'TypeErrorTypeError', }, // This tests for ES6 behaviour: { name: 'Object.getPrototypeOf primitives', src: ` Object.getPrototypeOf(true) === Boolean.prototype && Object.getPrototypeOf(1337) === Number.prototype && Object.getPrototypeOf('hi') === String.prototype; `, expected: true, }, { name: 'Object.setPrototypeOf(null, ...) and undefined', src: ` var r = '', prims = [null, undefined]; for (var i = 0; i < prims.length; i++) { try { Object.setPrototypeOf(prims[i], null); } catch (e) { r += e.name; } } r; `, expected: 'TypeErrorTypeError', }, { name: 'Object.setPrototypeOf primitives', src: ` Object.setPrototypeOf(true, null) === true && Object.setPrototypeOf(1337, null) === 1337 && Object.setPrototypeOf('hi', null) === 'hi'; `, expected: true, }, { name: 'Object.setPrototypeOf', src: ` var o = {parent: 'o'}; var p = {parent: 'p'}; var q = Object.create(o); Object.setPrototypeOf(q, p) === q && Object.getPrototypeOf(q) === p && q.parent; `, expected: 'p', }, { name: 'Object.setPrototypeOf(..., null)', src: ` var o = {parent: 'o'}; var q = Object.create(o); Object.setPrototypeOf(q, null) === q && Object.getPrototypeOf(q); `, expected: null, }, { name: 'Object.setPrototypeOf circular', src: ` var o = {}; var p = Object.create(o); try { Object.setPrototypeOf(o, p); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.create()', src: ` try { Object.create(); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.create non-object prototype', src: ` try { Object.create(42); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.create(null) prototype', src: `Object.getPrototypeOf(Object.create(null));`, expected: null, }, { name: 'Object.create', src: ` var o = Object.create({foo: 79}); delete o.foo o.foo; `, expected: 79, }, { name: 'Object.getOwnPropertyDescriptor()', src: ` try { Object.getOwnPropertyDescriptor(); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.getOwnPropertyDescriptor non-object', src: ` try { Object.getOwnPropertyDescriptor('not an object', 'foo'); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.getOwnPropertyDescriptor bad key', src: `Object.getOwnPropertyDescriptor({}, 'foo');`, expected: undefined, }, { name: 'Object.getOwnPropertyDescriptor', src: ` var o = {}, r = 0; Object.defineProperty(o, 'foo', {value: 'bar'}); var desc = Object.getOwnPropertyDescriptor(o, 'foo'); desc.value === o.foo && !desc.writable && !desc.enumerable && !desc.configurable; `, expected: true, }, { name: 'Object.getOwnPropertyNames()', src: ` try { Object.getOwnPropertyNames(); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.getOwnPropertyNames string', src: ` var i, r = 0, names = Object.getOwnPropertyNames('foo'); for (i = 0; i < names.length; i++) { if (names[i] === 'length') { r += 10; } else { r += Number(names[i]) + 1; } } `, expected: 16, }, {src: `Object.getOwnPropertyNames(42).length`, expected: 0}, {src: `Object.getOwnPropertyNames(true).length`, expected: 0}, { name: 'Object.getOwnPropertyNames(null)', src: ` try { Object.getOwnPropertyNames(null).length; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.getOwnPropertyNames(undefined)', src: ` try { Object.getOwnPropertyNames(undefined).length; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.getOwnPropertyNames', src: ` var o = Object.create({baz: 999}); o.foo = 42; Object.defineProperty(o, 'bar', {value: 38}); var keys = Object.getOwnPropertyNames(o); var r = 0; for (var i = 0; i < keys.length; i++) { r += o[keys[i]]; } r; `, expected: 80, }, { name: 'Object.defineProperties()', src: ` try { Object.defineProperties(); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.defineProperties non-object', src: ` try { Object.defineProperties('not an object', {}); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.defineProperties non-object props', src: ` try { Object.defineProperties({}, undefined); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.defineProperties bad descriptor', src: ` var o = {}; try { Object.defineProperties(o, {foo: 'not an object'}); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.defineProperties', src: ` var o = {foo: 70}, r = 0; Object.defineProperties(o, { bar: { writable: true, enumerable: true, configurable: true, value: 8 }, baz: {value: 999}}); for (var k in o) { r += o[k]; } r + Object.getOwnPropertyNames(o).length; `, expected: 81, }, { name: 'Object.create(..., properties)', src: ` var o = Object.create({foo: 70}, { bar: { writable: true, enumerable: true, configurable: true, value: 10 }, baz: {value: 999}}); var r = 0; for (var k in o) { r += o[k]; } r + Object.getOwnPropertyNames(o).length; `, expected: 82, }, { name: 'Object.assign', src: ` var p = {x: 'inherited enumerable', y: 'inherited nonenumerable'}; var o = Object.create(p); o.a = 'own enumerable'; o.b = 'own nonenumerable'; o.c = 'own enumerable'; Object.defineProperty(p, 'y', {enumerable: false}); Object.defineProperty(o, 'b', {enumerable: false}); var t = {a: 'to be overwritten', b: 'not overwritten', d: 'preserved'}; Object.assign(t, o, {e: 'extra'}); [Object.getOwnPropertyNames(t).length, t.a, t.b, t.c, t.d, t.e].toString(); `, expected: '5,own enumerable,not overwritten,own enumerable,preserved,extra', }, { name: 'Object.getOwnPropertyNames', src: ` var p = {x: 'inherited enumerable', y: 'inherited nonenumerable'}; var o = Object.create(p); o.a = 'own enumerable'; o.b = 'own nonenumerable'; o.c = 'own enumerable'; Object.defineProperty(p, 'y', {enumerable: false}); Object.defineProperty(o, 'b', {enumerable: false}); Object.getOwnPropertyNames(o).toString(); `, expected: 'a,b,c', }, { name: 'Object.keys', src: ` var p = {x: 'inherited enumerable', y: 'inherited nonenumerable'}; var o = Object.create(p); o.a = 'own enumerable'; o.b = 'own nonenumerable'; o.c = 'own enumerable'; Object.defineProperty(p, 'y', {enumerable: false}); Object.defineProperty(o, 'b', {enumerable: false}); Object.keys(o).toString(); `, expected: 'a,c', }, { name: 'Object.prototype.toString', src: `({}).toString();`, expected: '[object Object]', }, { name: 'Object.protoype.hasOwnProperty', src: ` var o = Object.create({baz: 999}); o.foo = 42; Object.defineProperty(o, 'bar', {value: 41, enumerable: true}); var r = 0; for (var key in o) { if (!o.hasOwnProperty(key)) continue; r += o[key]; } r; `, expected: 83, }, { name: 'Object.protoype.isPrototypeOf primitives', src: ` Boolean.prototype.isPrototypeOf(false) || Number.prototype.isPrototypeOf(0) || String.prototype.isPrototypeOf('') || Object.prototype.isPrototypeOf.call(false, false) || Object.prototype.isPrototypeOf.call(0, 0) || Object.prototype.isPrototypeOf.call('', '') || Object.prototype.isPrototypeOf.call(null, null) || Object.prototype.isPrototypeOf.call(undefined, undefined); `, expected: false, }, { name: 'Object.protoype.isPrototypeOf.call(null, ...)', src: ` try { Object.prototype.isPrototypeOf.call(null, Object.create(null)); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.protoype.isPrototypeOf.call(undefined, ...)', src: ` try { Object.prototype.isPrototypeOf .call(undefined, Object.create(undefined)); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.protoype.isPrototypeOf self', src: `var o = {}; o.isPrototypeOf(o);`, expected: false, }, {src: `Object.prototype.isPrototypeOf(Object.create(null))`, expected: false}, { name: 'Object.protoype.isPrototypeOf related', src: ` var g = {}; var p = Object.create(g); var o = Object.create(p); !o.isPrototypeOf({}) && g.isPrototypeOf(o) && p.isPrototypeOf(o) && !o.isPrototypeOf(p) && !o.isPrototypeOf(g); `, expected: true, }, { name: 'Object.protoype.propertyIsEnumerable(null)', src: ` try { Object.prototype.propertyIsEnumerable.call(null, ''); } catch(e) { e.name; } `, expected: 'TypeError', }, { name: 'ObjectProtoypePropertyIsEnumerableUndefined', src: ` try { Object.prototype.propertyIsEnumerable.call(undefined, ''); } catch(e) { e.name; } `, expected: 'TypeError', }, { name: 'Object.protoype.propertyIsEnumerable primitives', src: ` var OppIE = Object.prototype.propertyIsEnumerable; OppIE.call('foo', '0') && !OppIE.call('foo', 'length'); `, expected: true, }, { name: 'Object.protoype.propertyIsEnumerable', src: ` var o = {foo: 'foo'}; Object.defineProperty(o, 'bar', {value: 'bar', enumerable: false}); o.propertyIsEnumerable('foo') && !o.propertyIsEnumerable('bar') && !o.propertyIsEnumerable('baz'); `, expected: true, }, ///////////////////////////////////////////////////////////////////////////// // Function and Function.prototype { name: 'new Function() returns callable', src: `new Function()();`, expected: undefined, }, {src: `(new Function()).length;`, expected: 0}, {src: `new Function().toString()`, expected: 'function anonymous(\n) {\n\n}'}, { name: 'new Function(/* body */) returns callable', src: `new Function('return 42;')();`, expected: 42, }, { name: 'Function constructor accepts trailing line comments in body', src: `typeof new Function('//');`, expected: 'function', }, {src: `new Function(/* body */).length;`, expected: 0}, { src: `new Function('return 42;').toString()`, expected: 'function anonymous(\n) {\nreturn 42;\n}' }, { name: 'new Function(/* args... */, /* body */) returns callable', src: `new Function('a, b', 'c', 'return a + b * c;')(2, 3, 10);`, expected: 32, }, { name: "(new Function('a, b', 'c', /* body */)).length", src: `new Function('a, b', 'c', 'return a + b * c;').length;`, expected: 3, }, { name: 'new Function(/* args... */, /* body */).toString()', src: `new Function('a, b', 'c', 'return a + b * c;').toString()`, expected: 'function anonymous(a, b,c\n) {\nreturn a + b * c;\n}', }, { name: 'Function constructor accepts non-ASCII parameter names', src: `new Function('fußball', '').toString()`, expected: 'function anonymous(fußball\n) {\n\n}', }, { name: 'Function constructor rejects non-unicode-letter parameter names', src: ` try { new Function('a…z', ''); } catch (e) { e.name; } `, expected: 'SyntaxError', }, { name: 'Function constructor accepts block comments in parameter list', src: `new Function('a, /*test*/b', 'c', 'return a + b * c;')(2, 4, 10)`, expected: 42, }, { name: 'Function constructor accepts line comments in parameter list', src: `new Function('a, b', 'c //test', 'return a + b * c;')(2, 4, 10)`, expected: 42, }, { name: 'Function constructor parameter line comments hide later parameters', src: `new Function('dummy //', 'escape', 'return typeof escape')(0, 0);`, expected: 'function', }, { name: 'Function.prototype has no .prototype', src: `Function.prototype.hasOwnProperty('prototype');`, expected: false, }, { src: `Function.prototype.toString()`, expected: 'function () { [native code] }' }, { name: 'Function.prototype.toString.call(/* non-function */) throws', src: ` try { Function.prototype.toString.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Function.prototype.toSting on NativeFunction', src: `escape.toString();`, expected: 'function escape() { [native code] }', }, { name: 'Function.prototype.toSting on modified NativeFunction', destructive: true, // Modifies escape. src: ` // Delete escape's original .name make it inherit a new one. delete escape.name; Object.setPrototypeOf(escape, function parent() {}); escape.toString(); `, expected: 'function escape() { [native code] }', }, { name: 'Function.prototype.apply.call(/* non-function */) throws', src: ` try { Function.prototype.apply.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Function.prototype.apply this', src: ` var o = {}; function f() {return this;} f.apply(o, []) === o; `, expected: true, }, { name: 'Function.prototype.apply(..., undefined) or null', src: ` var n = 0; function f() {n += arguments.length;} f.apply(undefined, undefined); f.apply(undefined, null); n; `, expected: 0, }, { name: 'Function.prototype.apply(..., /* non-object */) throws', src: ` try { (function() {}).apply(undefined, 'not an object'); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Function.prototype.apply(..., /* sparse array */)', src: ` (function(a, b, c) { if (!(1 in arguments)) { throw new Error('arguments[1] missing'); } return a + c; }).apply(undefined, [1, , 3]); `, expected: 4, }, { name: 'Function.prototype.apply(..., /* array-like */)', src: ` (function(a, b, c) { return a + b + c; }).apply(undefined, {0: 1, 1: 2, 2: 3, length: 3}); `, expected: 6, }, { name: 'Function.prototype.apply(..., /* non-array-like */)', src: ` (function(a, b, c) { return a + b + c; }).apply(undefined, {0: 1, 1: 2, 2: 4}); `, expected: NaN // Because undefined + undefined === NaN., }, { name: 'Function.prototype.call.call(/* non-function */) throws', src: ` try { Function.prototype.call.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Function.prototype.call this', src: ` var o = {}; function f() {return this;} f.call(o) === o; `, expected: true, }, { name: 'Function.prototype.call() gives arguments.length === 0', src: `(function() {return arguments.length;}).call();`, expected: 0, }, { name: 'Function.prototype.call(..., /* sparse array */)', src: ` (function(a, b, c) { if (!(1 in arguments)) { throw new Error('Argument 1 missing'); } return a + c; }).call(undefined, 1, 2, 3); `, expected: 4, }, { name: 'Function.prototype.bind.call(/* non-function */) throws', src: ` try { Function.prototype.bind.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'Function.prototype.bind this', src: ` var o = {}; function f() {return this;} f.bind(o)() === o; `, expected: true, }, { name: 'Function.prototype.bind no args', src: `(function() {return arguments.length;}).bind()();`, expected: 0, }, { name: 'Function.prototype.bind', src: ` var d = 4; (function(a, b, c) { return a + b + c + d; }).bind(undefined, 1).bind(undefined, 2)(3); `, expected: 10, }, { name: 'Function.prototype.bind call BF', src: ` var constructed; function Foo() {constructed = (this instanceof Foo)} var f = Foo.bind(); f(); constructed; `, expected: false, }, { name: 'Function.prototype.bind construct BF', src: ` var constructed; function Foo() {constructed = (this instanceof Foo)} var f = Foo.bind(); new f; constructed; `, expected: true, }, { name: 'Function.prototype.call.bind construct BF', src: ` var invoked; function Foo() {invoked = true}; var f = Foo.call.bind(Foo); try { new f; } catch (e) { !invoked && e.name; } `, expected: 'TypeError', }, // N.B.: tests of semantics of class constructors are unavoidably ES6. { name: 'Function.prototype.bind class constructor w/o new', src: ` var f = WeakMap.bind(); // Should be O.K. try { f(); } catch (e) { e.name; } `, expected: 'TypeError', }, // N.B.: tests of semantics of class constructors are unavoidably ES6. { name: 'Function.prototype.bind class constructor', src: `String(new (WeakMap.bind()));`, expected: '[object WeakMap]', }, ///////////////////////////////////////////////////////////////////////////// // Array and Array.prototype { name: 'new Array()', src: `var a = new Array(); Array.isArray(a) && a.length;`, expected: 0, }, { name: 'newArray(/* number */)', src: ` var a = new Array(42); Array.isArray(a) && !(0 in a) && !(41 in a) && a.length; `, expected: 42, }, { name: 'new Array(/* non-number */)', src: ` var a = new Array('foo'); Array.isArray(a) && a.length === 1 && a[0]; `, expected: 'foo', }, { name: 'new Array(/* multiple args */)', src: ` var a = new Array(1, 2, 3); Array.isArray(a) && a.length === 3 && String(a); `, expected: '1,2,3', }, {src: `Array.isArray(Array.prototype);`, expected: true}, {src: `Array.isArray(new Array);`, expected: true}, {src: `Array.isArray([]);`, expected: true}, {src: `Array.isArray({0: 'foo', 1: 'bar', length: 2});`, expected: false}, { name: 'Array.prototype.concat()', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var c = a.concat(); a.length === 6 && c.length === 6 && c !== a && String(c); `, expected: 'foo,bar,baz,,quux,quuux', }, { name: 'Array.prototype.concat(...)', src: ` var o = {0: 'quux', 1: 'quuux', length: 2}; var c = [].concat(['foo', 'bar'], 'baz', undefined, o); c.length === 5 && '3' in c && c[3] === undefined && String(c); `, expected: 'foo,bar,baz,,[object Object]', }, { name: 'Array.prototype.concat.call(object, ...)', src: ` var o = {0: 'foo', 1: 'bar', length: 2}; var c = Array.prototype.concat.call(o, 'baz', [, 'quux', 'quuux']); c.length === 5 && String(c); `, expected: '[object Object],baz,,quux,quuux', }, {src: `[1, 2, 3, 2, 1].includes(2);`, expected: true}, {src: `[1, 2, 3, 2, 1].includes(4);`, expected: false}, { name: 'Array.prototype.includes fromIndex', src: `[1, 2, 3, 2, 1].includes(2, 2);`, expected: true, }, { name: 'Array.prototype.includes negative fromIndex', src: `[1, 2, 3, 2, 1].includes(1, -3);`, expected: true, }, {src: `['x', NaN, 'y'].includes(NaN);`, expected: true}, { name: 'Array.prototype.includes.call(array-like, ...)', src: ` var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5}; Array.prototype.includes.call(o, 2); `, expected: true, }, { name: 'Array.prototype.indexOf', src: `[1, 2, 3, 2, 1].indexOf(2);`, expected: 1, }, { name: 'Array.prototype.indexOf not found', src: `[1, 2, 3, 2, 1].indexOf(4);`, expected: -1, }, { name: 'Array.prototype.indexOf fromIndex', src: `[1, 2, 3, 2, 1].indexOf(2, 2);`, expected: 3, }, { name: 'Array.prototype.indexOf negative fromIndex', src: `[1, 2, 3, 2, 1].indexOf(1, -3);`, expected: 4, }, { name: 'Array.prototype.indexOf NaN', src: `['x', NaN, 'y'].indexOf(NaN);`, expected: -1, }, { name: 'Array.prototype.indexOf.call(array-like, ...)', src: ` var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5}; Array.prototype.indexOf.call(o, 2); `, expected: 1, }, { name: 'Array.prototype.join', src: `[1, 2, 3].join('-');`, expected: '1-2-3', }, { name: 'Array.prototype.join cycle detection', src: ` var a = [1, , 3]; a[1] = a; a.join('-'); "Didn't crash!"; `, expected: 'Didn\'t crash!', }, { name: 'Array.prototype.lastIndexOf', src: `[1, 2, 3, 2, 1].lastIndexOf(2);`, expected: 3, }, { name: 'Array.prototype.lastIndexOf not found', src: `[1, 2, 3, 2, 1].lastIndexOf(4);`, expected: -1, }, { name: 'Array.prototype.lastIndexOf(..., +)', src: `[1, 2, 3, 2, 1].lastIndexOf(2, 2);`, expected: 1, }, { name: 'Array.prototype.lastIndexOf(..., -)', src: `[1, 2, 3, 2, 1].lastIndexOf(1, -3);`, expected: 0, }, { name: 'Array.prototype.lastIndexOf.call(array-like, ...)', src: ` var o = {0: 1, 1: 2, 2: 3, 3: 2, 4: 1, length: 5}; Array.prototype.lastIndexOf.call(o, 2); `, expected: 3, }, { name: 'Array.prototype.pop', src: ` var a = ['foo', 'bar', 'baz']; var r = a.pop(); a.length === 2 && r; `, expected: 'baz', }, { name: 'Array.prototype.pop empty array', src: ` var a = []; var r = a.pop(); a.length === 0 && r; `, expected: undefined, }, { name: 'Array.prototype.pop.apply(array-like)', src: ` var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3}; var r = Array.prototype.pop.apply(o); o.length === 2 && r; `, expected: 'baz', }, { name: 'Array.prototype.pop.apply(empty array-like)', src: ` var o = {length: 0}; var r = Array.prototype.pop.apply(o); o.length === 0 && r; `, expected: undefined, }, { name: 'Array.prototype.pop.apply(huge array-like)', src: ` var o = {5000000000000000: 'foo', 5000000000000001: 'quux', length: 5000000000000002}; var r = Array.prototype.pop.apply(o); o.length === 5000000000000001 && o[5000000000000000] === 'foo' && r; `, expected: 'quux', }, { name: 'Array.prototype.push', src: ` var a = []; a.push('foo') === 1 && a.push('bar') === 2 && a.length === 2 && a[0] === 'foo' && a[1] === 'bar'; `, expected: true, }, { name: 'Array.prototype.push.call(array-like, ...)', src: ` var o = {length: 0}; Array.prototype.push.call(o, 'foo') === 1 && Array.prototype.push.call(o, 'bar') === 2 && o.length === 2 && o[0] === 'foo' && o[1] === 'bar'; `, expected: true, }, { name: 'Array.prototype.push.call(huge array-like, ...)', src: ` var o = {length: 5000000000000000}; var o = {length: 5000000000000000}; Array.prototype.push.call(o, 'foo') === 5000000000000001 && Array.prototype.push.call(o, 'bar') === 5000000000000002 && o[5000000000000000] === 'foo' && o[5000000000000001] === 'bar' && o.length === 5000000000000002 `, expected: true, }, { name: 'Array.prototype.reverse odd-length', src: ` var a = [1, 2, 3]; a.reverse() === a && a.length === 3 && String(a); `, expected: '3,2,1', }, { name: 'Array.prototype.reverse even-length', src: ` var a = [1, 2, , 4]; a.reverse() === a && a.length === 4 && String(a); `, expected: '4,,2,1', }, { name: 'Array.prototype.reverse empty', src: ` var a = []; a.reverse() === a && a.length; `, expected: 0, }, { name: 'Array.prototype.reverse.call(odd-length array-like)', src: ` var o = {0: 1, 1: 2, 2: 3, length: 3}; Array.prototype.reverse.call(o) === o && o.length === 3 && Array.prototype.slice.apply(o).toString(); `, expected: '3,2,1', }, { name: 'Array.prototype.reverse.call(even-length array-like)', src: ` var o = {0: 1, 1: 2, 3: 4, length: 4}; Array.prototype.reverse.call(o) === o && o.length === 4 && Array.prototype.slice.apply(o).toString(); `, expected: '4,,2,1', }, { name: 'Array.prototype.reverse.call(empty array-like)', src: ` var o = {length: 0}; Array.prototype.reverse.call(o) === o && o.length; `, expected: 0, }, { name: 'Array.prototype.shift', src: ` var a = ['foo', 'bar', 'baz']; var r = a.shift(); a.length === 2 && a[0] === 'bar' && a[1] === 'baz' && r; `, expected: 'foo', }, { name: 'Array.prototype.shift empty array', src: ` var a = []; var r = a.shift(); a.length === 0 && r; `, expected: undefined, }, { name: 'Array.prototype.shift.apply(array-like)', src: ` var o = {0: 'foo', 1: 'bar', 2: 'baz', length: 3}; var r = Array.prototype.shift.apply(o); o.length === 2 && o[0] === 'bar' && o[1] === 'baz' && r; `, expected: 'foo', }, { name: 'Array.prototype.shift.apply(empty array-like)', src: ` var o = {length: 0}; var r = Array.prototype.shift.apply(o); o.length === 0 && r; `, expected: undefined, }, { name: 'Array.prototype.shift.apply(huge array-like)', src: ` var o = {5000000000000000: 'foo', 5000000000000001: 'quux', length: 5000000000000002}; var r = Array.prototype.shift.apply(o); o.length === 5000000000000001 && o[5000000000000000] === 'quux' && r; `, // SKIP until more efficient shift implementation available. /* expected: 'foo' */ }, { name: 'Array.prototype.slice()', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.slice(); a.length === 6 && s.length === 6 && String(s); `, expected: 'foo,bar,baz,,quux,quuux', }, { name: 'Array.prototype.slice(-)', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.slice(-2); a.length === 6 && s.length === 2 && String(s); `, expected: 'quux,quuux', }, { name: 'Array.prototype.slice(+, +)', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.slice(1, 4); a.length === 6 && s.length === 3 && !('2' in s) && String(s); `, expected: 'bar,baz,', }, { name: 'Array.prototype.slice(+, -)', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.slice(1, -2); a.length === 6 && s.length === 3 && !('2' in s) && String(s); `, expected: 'bar,baz,', }, { name: 'Array.prototype.slice.call(array-like, -, +)', src: ` var o = { 0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6 }; var s = Array.prototype.slice.call(o, -5, 4); !Array.isArray(o) && o.length === 6 && Array.isArray(s) && s.length === 3 && !('2' in s) && String(s); `, expected: 'bar,baz,', }, { name: 'Array.prototype.slice.call(huge array-like, -, -)', src: ` var o = { 5000000000000000: 'foo', 5000000000000001: 'bar', 5000000000000002: 'baz', 5000000000000004: 'quux', 5000000000000005: 'quuux', length: 5000000000000006 }; var s = Array.prototype.slice.call(o, -5, -2); !Array.isArray(o) && o.length === 5000000000000006 && Array.isArray(s) && s.length === 3 && !('2' in s) && String(s); `, expected: 'bar,baz,', }, { name: 'Array.prototype.sort()', src: `[5, 2, 3, 1, 4].sort().join(); // Sorts ASCIIbetically.`, expected: '1,2,3,4,5', }, { name: 'Array.prototype.sort() compaction', src: ` ['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1].sort() .map(String).join(); `, expected: '1,10,5,NaN,a,aa,null,z,undefined,,', }, { name: 'Array.prototype.sort(/* comparefn */)', src: ` [99, 9, 10, 11, 1, 0, 5] .sort(function(a, b) {return a - b;}).join(); `, expected: '0,1,5,9,10,11,99', }, { name: 'Array.prototype.sort(/* comparefn */) compaction', src: ` ['z', undefined, 10, , 'aa', null, 'a', 5, NaN, , 1] .sort(function(a, b) { // Try to put undefineds first - should not succeed. if (a === undefined) return b === undefined ? 0 : -1; if (b === undefined) return 1; // Reverse order of ususal sort. a = String(a); b = String(b); if (a > b) return -1; if (b > a) return 1; return 0; }).map(String).join(); `, expected: 'z,null,aa,a,NaN,5,10,1,undefined,,', }, { name: 'Array.prototype.splice()', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.splice(); a.length === 6 && s.length === 0 && String(a) + ':' + String(s); `, expected: 'foo,bar,baz,,quux,quuux:', }, { name: 'Array.prototype.splice(-)', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.splice(-2); a.length === 4 && s.length === 2 && String(a) + ':' + String(s); `, expected: 'foo,bar,baz,:quux,quuux', }, { name: 'Array.prototype.splice(+, +, ...)', src: ` var a = ['foo', 'bar', 'baz', , 'quux', 'quuux']; var s = a.splice(1, 3, 'bletch'); a.length === 4 && s.length === 3 && String(a) + ':' + String(s); `, expected: 'foo,bletch,quux,quuux:bar,baz,', }, { name: 'Array.prototype.splice.call(array-like, 0, large, ...)', src: ` var o = { 0: 'foo', 1: 'bar', 2: 'baz', 4: 'quux', 5: 'quuux', length: 6 }; var s = Array.prototype.splice.call(o, 0, 100, 'bletch'); !Array.isArray(o) && o.length === 1 && Object.keys(o).length === 2 && o[0] === 'bletch' && Array.isArray(s) && s.length === 6 && !('3' in s) && String(s); `, expected: 'foo,bar,baz,,quux,quuux', }, { name: 'Array.prototype.splice.call(huge array-like, -, -, many...)', src: ` var o = { 5000000000000000: 'foo', 5000000000000001: 'bar', 5000000000000002: 'baz', 5000000000000004: 'quux', 5000000000000005: 'quuux', length: 5000000000000006 }; var s = Array.prototype.splice.call(o, -2, -999, 'bletch', 'qux'); !Array.isArray(o) && o.length === 5000000000000008 && o[5000000000000004] === 'bletch' && o[5000000000000005] === 'qux' && o[5000000000000006] === 'quux' && o[5000000000000007] === 'quuux' && Array.isArray(s) && s.length === 0; `, expected: true, }, { name: 'Array.prototype.toString cycle detection', src: ` var a = [1, , 3]; a[1] = a; a.toString(); "Didn't crash!"; `, expected: 'Didn\'t crash!', }, { name: 'Array.prototype.toString.call(obj-w/join)', src: `Array.prototype.toString.apply({join: function() {return 'OK';}});`, expected: 'OK', }, { name: 'Array.prototype.toString.call(array-like)', src: `Array.prototype.toString.apply({0: 'foo', 1: 'bar', length: 2});`, expected: '[object Object]', }, { name: 'Array.prototype.unshift', src: ` var a = []; a.unshift('foo') === 1 && a.unshift('bar') === 2 && a.length === 2 && a[0] === 'bar' && a[1] === 'foo'; `, expected: true, }, { name: 'Array.prototype.unshift.call(array-like, ...)', src: ` var o = {length: 0}; Array.prototype.unshift.call(o, 'foo') === 1 && Array.prototype.unshift.call(o, 'bar') === 2 && o.length === 2 && o[0] === 'bar' && o[1] === 'foo'; `, expected: true, }, { name: 'Array.prototype.unshift.call(huge array-like, ...)', src: ` var o = {length: 5000000000000000}; var o = {length: 5000000000000000}; Array.prototype.unshift.call(o, 'foo') === 5000000000000001 && Array.prototype.push.call(o, 'bar') === 5000000000000002 && o[5000000000000000] === 'bar' && o[5000000000000001] === 'foo' && o.length === 5000000000000002 `, // SKIP until more efficient unshift implementation available. /* expected: true */ }, ///////////////////////////////////////////////////////////////////////////// // Boolean and Boolean.prototype {src: `Boolean(undefined);`, expected: false}, {src: `Boolean(null);`, expected: false}, {src: `Boolean(false);`, expected: false}, {src: `Boolean(true);`, expected: true}, {src: `Boolean(NaN);`, expected: false}, {src: `Boolean(0);`, expected: false}, {src: `Boolean(1);`, expected: true}, {src: `Boolean('');`, expected: false}, {src: `Boolean('foo');`, expected: true}, {src: `Boolean({});`, expected: true}, {src: `Boolean([]);`, expected: true}, {src: `Boolean(function() {});`, expected: true}, {src: `Boolean.prototype.toString();`, expected: 'false'}, {src: `Boolean.prototype.toString.call(true);`, expected: 'true'}, {src: `Boolean.prototype.toString.call(false);`, expected: 'false'}, { name: 'Boolean.prototype.toString.call non-Boolean object', src: ` try { Boolean.prototype.toString.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, {src: `Boolean.prototype.valueOf();`, expected: false}, {src: `Boolean.prototype.valueOf.call(true);`, expected: true}, {src: `Boolean.prototype.valueOf.call(false);`, expected: false}, { name: 'Boolean.prototype.valueOf.call non-Boolean object', src: ` try { Boolean.prototype.valueOf.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, ///////////////////////////////////////////////////////////////////////////// // Number and Number.prototype {src: `Number();`, expected: 0}, {src: `Number(undefined);`, expected: NaN}, {src: `Number(null);`, expected: 0}, {src: `Number(true);`, expected: 1}, {src: `Number(false);`, expected: 0}, {src: `Number('42');`, expected: 42}, {src: `Number('');`, expected: 0}, {src: `Number({});`, expected: NaN}, {src: `Number([]);`, expected: 0}, {src: `Number([42]);`, expected: 42}, {src: `Number([1,2,3]);`, expected: NaN}, {src: `Number(function() {});`, expected: NaN}, { name: 'Number.MAX_SAFE_INTEGER', src: ` Number.MAX_SAFE_INTEGER + 1 === Math.pow(2, 53) && Number.isSafeInteger(Number.MAX_SAFE_INTEGER) && !Number.isSafeInteger(Number.MAX_SAFE_INTEGER + 1); `, expected: true, }, {src: `Number.prototype.toString();`, expected: '0'}, {src: `Number.prototype.toString.call(84);`, expected: '84'}, { name: 'Number.prototype.toString.call non-Number object', src: ` try { Number.prototype.toString.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, {src: `Number.prototype.valueOf();`, expected: 0}, {src: `Number.prototype.valueOf.call(85);`, expected: 85}, { name: 'Number.prototype.valueOf.call non-Number object', src: ` try { Number.prototype.valueOf.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, ///////////////////////////////////////////////////////////////////////////// // String and String.prototype {src: `String();`, expected: ''}, {src: `String(undefined);`, expected: 'undefined'}, {src: `String(null);`, expected: 'null'}, {src: `String(true);`, expected: 'true'}, {src: `String(false);`, expected: 'false'}, {src: `String(0);`, expected: '0'}, {src: `String(-0);`, expected: '0'}, {src: `String(Infinity);`, expected: 'Infinity'}, {src: `String(-Infinity);`, expected: '-Infinity'}, {src: `String(NaN);`, expected: 'NaN'}, {src: `String({});`, expected: '[object Object]'}, {src: `String([1, 2, 3,,5]);`, expected: '1,2,3,,5'}, { name: 'String calls valueOf', src: ` var o = Object.create(null); o.valueOf = function() {return 'OK';}; String(o); `, expected: 'OK', }, { name: 'String calling valueOf returns string', src: ` var o = Object.create(null); o.valueOf = function() {return 42;}; String(o); `, expected: '42', }, { name: 'String calling valueOf throws', src: ` var o = Object.create(null); o.valueOf = function() {return {};}; try { String(o); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'String calls toString', src: ` var o = Object.create(null); o.valueOf = function() {return 'Whoops: called valueOf';}; o.toString = function() {return 'OK';}; String(o); `, expected: 'OK', }, { name: 'String calling toString returns string', src: ` var o = Object.create(null); o.valueOf = function() {return 42;}; String(o); `, expected: '42', }, { name: 'String calling toString throws', src: ` var o = Object.create(null); o.valueOf = function() {return {};}; o.toString = function() {return {};}; try { String(o); } catch (e) { e.name; } `, expected: 'TypeError', }, {src: `String.prototype.length;`, expected: 0}, { name: 'String.prototype.replace(string, string)', src: `'xxxx'.replace('xx', 'y');`, expected: 'yxx', }, { name: 'String.prototype.replace(regexp, string)', src: `'xxxx'.replace(/(X)\\1/ig, 'y');`, expected: 'yy', }, { name: 'String.prototype.replace(string, function)', src: ` 'xxxx'.replace('xx', function() { return '[' + Array.prototype.join.apply(arguments) + ']'; }); `, expected: '[xx,0,xxxx]xx', }, { name: 'String.prototype.replace(regexp, function)', src: ` 'xxxx'.replace(/(X)\\1/ig, function() { return '[' + Array.prototype.join.apply(arguments) + ']'; }); `, expected: '[xx,x,0,xxxx][xx,x,2,xxxx]', }, { name: 'String.prototype.search(string) not found', src: `'hello'.search('H')`, expected: -1, }, { name: 'String.prototype.search(string) found', src: `'hello'.search('ll')`, expected: 2, }, { name: 'String.prototype.search(regexp) not found', src: `'hello'.search(/H/)`, expected: -1, }, { name: 'String.prototype.search(regexp) found', src: `'hello'.search(/(.)\\1/)`, expected: 2, }, {src: `String.prototype.toString();`, expected: ''}, { name: 'String.prototype.toString.call primitive', src: `String.prototype.toString.call('a string');`, expected: 'a string', }, { name: 'String.prototype.toString.call non-String object', src: ` try { String.prototype.toString.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, {src: `String.prototype.valueOf();`, expected: ''}, { name: 'String.prototype.valueOf.call primitive', src: `String.prototype.valueOf.call('a string');`, expected: 'a string', }, { name: 'String.prototype.valueOf.call non-String object', src: ` try { String.prototype.valueOf.call({}); } catch (e) { e.name; } `, expected: 'TypeError', }, ///////////////////////////////////////////////////////////////////////////// // RegExp {src: `new RegExp(undefined).source`, expected: '(?:)'}, {src: `new RegExp(null).source`, expected: 'null'}, {src: `new RegExp(true).source`, expected: 'true'}, {src: `new RegExp(false).source`, expected: 'false'}, {src: `new RegExp('').source`, expected: '(?:)'}, {src: `new RegExp('foo').source`, expected: 'foo'}, {src: `new RegExp('0').source`, expected: '0'}, {src: `new RegExp({}).source`, expected: '[object Object]'}, {src: `new RegExp([]).source`, expected: '(?:)'}, {src: `RegExp(undefined).source`, expected: '(?:)'}, {src: `RegExp(null).source`, expected: 'null'}, {src: `RegExp(true).source`, expected: 'true'}, {src: `RegExp(false).source`, expected: 'false'}, {src: `RegExp('').source`, expected: '(?:)'}, {src: `RegExp('foo').source`, expected: 'foo'}, {src: `RegExp('0').source`, expected: '0'}, {src: `RegExp({}).source`, expected: '[object Object]'}, {src: `RegExp([]).source`, expected: '(?:)'}, // TODO(ES6): // {src: `new RegExp('foo', '').flags`, expected: ''}, // {src: `new RegExp('foo', 'g').flags`, expected: 'g'}, // {src: `new RegExp('foo', 'i').flags`, expected: 'i'}, // {src: `new RegExp('foo', 'gi').flags`, expected: 'gi'}, // {src: `new RegExp('foo', 'm').flags`, expected: 'm'}, // {src: `new RegExp('foo', 'gm').flags`, expected: 'gm'}, // {src: `new RegExp('foo', 'im').flags`, expected: 'im'}, // {src: `new RegExp('foo', 'gim').flags`, expected: 'gim'}, {src: `new RegExp('foo', '').global`, expected: false}, {src: `new RegExp('foo', 'g').global`, expected: true}, {src: `new RegExp('foo', '').ignoreCase`, expected: false}, {src: `new RegExp('foo', 'i').ignoreCase`, expected: true}, {src: `new RegExp('foo', '').multiline`, expected: false}, {src: `new RegExp('foo', 'm').multiline`, expected: true}, { name: "new RegExp('', 'x') throws", src: ` try { new RegExp('', 'x'); } catch (e) { e.name; } `, expected: 'SyntaxError', }, { name: "new RegExp('', 'gg') throws", src: ` try { new RegExp('', 'gg'); } catch (e) { e.name; } `, expected: 'SyntaxError', }, // Check behaviour of RegExp when called with and without new, when // pattern is itself a RegExp, and flags are or are not supplied. {src: `var re = /foo/; new RegExp(re) === re;`, expected: false}, {src: `var re = /foo/; RegExp(re) === re;`, expected: true}, {src: `var re = /foo/; RegExp(re, 'm') === re;`, expected: false}, {src: `var re = /foo/m; RegExp(re, 'm') === re;`, expected: false}, {src: `var re = /foo/m; RegExp(re) === re;`, expected: true}, { name: 'RegExp called as function checks .constructor', src: ` function SubClass() {}; Object.setPrototypeOf(SubClass, RegExp); Object.setPrototypeOf(SubClass.prototype, RegExp.prototype); var re = /foo/; re.constructor = SubClass; RegExp(re) === re; `, expected: false, }, // TODO(ES6): // {src: `var re = /foo/m; RegExp(re, 'i').flags;`, expected: 'i'}, {src: `var re = /foo/m; RegExp(re, 'i').multiline;`, expected: false}, {src: `var re = /foo/m; RegExp(re, 'i').ignoreCase;`, expected: true}, // Check behaviour of RegExp.prototype methods. { name: 'RegExp.prototype.exec.call(undefined) throws', src: ` try { RegExp.prototype.exec.call(undefined, 'foo'); } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'RegExp.prototype.exec.call(non-regexp) throws', src: ` try { RegExp.prototype.exec.call({}, 'foo'); } catch (e) { e.name; } `, expected: 'TypeError', }, {src: `/undefined/.exec(undefined).length;`, expected: 1}, {src: `/null/.exec(null).length;`, expected: 1}, { name: 'RegExp.prototype.test.call(undefined) throws', src: ` try { RegExp.prototype.test.call(undefined); } catch (e) { e.name; } `, expected: 'TypeError' }, { name: 'RegExp.prototype.test.call(/* non-regexp */) throws', src: ` try { RegExp.Prototype.test.call({}, 'foo'); } catch (e) { e.name; } `, expected: 'TypeError', }, ///////////////////////////////////////////////////////////////////////////// // Error and Error.prototype (and all the other native error types too) { name: 'new Error has .stack', src: ` // Use eval to make parsing .stack easier. var e = eval('new Error;'); var lines = e.stack.split('\\n'); lines[0].trim(); `, expected: 'at "new Error;" 1:1', }, { name: 'thrown Error has .stack', src: ` try { (function buggy() {1 instanceof 2;})(); } catch (e) { var lines = e.stack.split('\\n'); } lines[0].trim(); `, expected: 'at buggy 1:19', }, { name: 'Error .stack correctly reports anonymous function', src: ` // Use eval to make parsing .stack easier. var e = eval('(function() {return new Error;})()'); var lines = e.stack.split('\\n'); lines[0].trim(); `, expected: 'at anonymous function 1:20', }, // Bug #241. { name: 'Error .stack correctly blames MemberExpression', src: ` function foo() { switch (1) { case 1: return undefined.hasNoProperties; } } try { foo(); } catch (e) { var lines = e.stack.split('\\n'); } lines[0].trim(); `, expected: 'at foo 4:20', }, { name: 'Error .stack correctly blames Identifier', src: ` function foo() { return undefinedVariable; } try { foo(); } catch (e) { var lines = e.stack.split('\\n'); } lines[0].trim(); `, expected: 'at foo 2:16', }, ///////////////////////////////////////////////////////////////////////////// // JSON { name: 'JSON.parse(undefined) throws', src: ` try { JSON.parse(undefined); } catch (e) { e.name; } `, expected: 'SyntaxError', }, {src: `JSON.parse(null);`, expected: null}, {src: `JSON.parse(true);`, expected: true}, {src: `JSON.parse(false);`, expected: false}, {src: `JSON.parse(42);`, expected: 42}, { name: "JSON.parse('') throws", src: ` try { JSON.parse(''); } catch (e) { e.name; } `, expected: 'SyntaxError', }, { name: 'JSON.parse([]) throws', src: ` try { JSON.parse([]); // Equivalent to JSON.parse(''); } catch (e) { e.name; } `, expected: 'SyntaxError', }, { name: 'JSON.parse({}) throws', src: ` try { JSON.parse({}); // Equivalent to JSON.parse('[object Object]'); } catch (e) { e.name; } `, expected: 'SyntaxError', }, {src: `JSON.stringify(undefined);`, expected: undefined}, {src: `JSON.stringify(null);`, expected: 'null'}, {src: `JSON.stringify(true);`, expected: 'true'}, {src: `JSON.stringify(false);`, expected: 'false'}, {src: `JSON.stringify(42);`, expected: '42'}, {src: `JSON.stringify('string');`, expected: '"string"'}, {src: `JSON.stringify([1,2,,4]);`, expected: '[1,2,null,4]'}, { name: 'JSON.stringify({...})', src: ` JSON.stringify({ string: 'foo', number: 42, true: true, false: false, null: null, object: {obj: {}, arr: []}, array: [{}, []] }); `, expected: '{"string":"foo","number":42,"true":true,"false":false,' + '"null":null,"object":{"obj":{},"arr":[]},"array":[{},[]]}', }, {src: `JSON.stringify(function(){});`, expected: undefined}, {src: `JSON.stringify([function(){}]);`, expected: '[null]'}, {src: `JSON.stringify({f: function(){}});`, expected: '{}'}, { name: 'JSON.stringify({...}, [/* filter array */])', src: ` JSON.stringify({ string: 'foo', number: 42, true: true, false: false, null: null, object: {obj: {}, arr: []}, array: [{}, []] }, ['string', 'number']); `, expected: '{"string":"foo","number":42}', }, { name: 'JSON.stringify({...}, [...], /* space number */)', src: ` JSON.stringify({ string: 'foo', number: 42, true: true, false: false, null: null, object: {obj: {}, arr: []}, array: [{}, []] }, ['string', 'number'], 2); `, expected: '{\n "string": "foo",\n "number": 42\n}', }, { name: 'JSON.stringify({...}, [...], /* space string */)', src: ` JSON.stringify({ string: 'foo', number: 42, true: true, false: false, null: null, object: {obj: {}, arr: []}, array: [{}, []] }, ['string', 'number'], '--'); `, expected: '{\n--"string": "foo",\n--"number": 42\n}', }, { name: 'JSON.stringify ignores nonenumerable properties', src: ` var obj = {e: 'enumerable', ne: 'nonenumerable'}; Object.defineProperty(obj, 'ne', {enumerable: false}); JSON.stringify(obj); `, expected: '{"e":"enumerable"}', }, { name: 'JSON.stringify ignores inherited properties', src: `JSON.stringify(Object.create({foo: 'bar'}));`, expected: '{}', }, { name: 'JSON.stringify throws when value is cyclic', src: ` var obj = {}; obj.circular = obj; try { JSON.stringify(obj); } catch (e) { e.name; } `, expected: 'TypeError', }, ///////////////////////////////////////////////////////////////////////////// // Other built-in functions { name: 'decodeURI throws', src: ` try { decodeURI('%xy'); } catch (e) { e.name; } `, expected: 'URIError', }, ///////////////////////////////////////////////////////////////////////////// // WeakMap { name: 'WeakMap', src: ` var w = new WeakMap; var p = {}; var o = Object.create(p); var fails = 0; !w.has(p) || fails++; !w.delete(p) || fails++; w.set(o, 'o') === w || fails++; w.get(o) === 'o' || fails++; w.get(p) === undefined || fails++; w.has(o) || fails++; w.delete(o) || fails++; !w.has(o) || fails++; fails; `, expected: 0, }, { name: 'WeakMap.prototype methods reject non-WeakMap this', src: ` var w = new WeakMap; var fails = 0; function expectError(method, thisVal, args) { try { w[method].apply(thisVal, args); fails++; } catch (e) { if (e.name !== 'TypeError') fails++; } } var methods = ['delete', 'get', 'has', 'set']; var values = [null, undefined, true, false, 0, 42, '', 'hi']; for (var i = 0; i < methods.length; i++) { var method = methods[i]; for (var j = 0; j < values.length; j++) { var value = values[j]; expectError(method, value, [{}]); // Can't call method on non-WeakMap. expectError(method, w, [value]); // Can't store non-object in WeakMap. } // WeakMap.prototype is an ordinary object, not a WeakMap. expectError(method, WeakMap.prototpye, [{}]); } fails; `, expected: 0, }, { name: 'WeakMap', src: ` var w = new WeakMap; var p = {}; var o = Object.create(p); var fails = 0; !w.has(p) || fails++; !w.delete(p) || fails++; w.set(o, 'o') === w || fails++; w.get(o) === 'o' || fails++; w.get(p) === undefined || fails++; w.has(o) || fails++; w.delete(o) || fails++; !w.has(o) || fails++; fails; `, expected: 0, }, ///////////////////////////////////////////////////////////////////////////// // Thread and Thread.prototype: // TODO(cpallen): change .eval to .program when test harness no // longer relies on eval. { name: 'Thread.callers() ownership', src: ` var owner = {}; setPerms(owner); var callers = Thread.callers(); Object.getOwnerOf(callers) === owner && Object.getOwnerOf(callers[0]) === owner; `, expected: true, }, { name: 'Thread.callers()[0].eval', src: `Thread.callers()[0].eval`, expected: 'Thread.callers()[0].eval', }, { name: 'Thread.callers()[0].line & .col', src: `var frame = Thread.callers()[0]; frame.line + "," + frame.col;`, expected: '1,13', }, { name: 'Thread.callers()[/* last */].program', src: ` var callers = Thread.callers(); typeof callers[callers.length - 1].program; `, expected: 'string', }, { name: 'Thread.callers()[0].callerPerms', src: ` CC.root.name = 'root'; var user = {name: 'user'}; function f() { return Thread.callers()[0].callerPerms.name; } setPerms(user); f(); `, expected: 'user', }, // Time limit tests. Actual enforcement is tested in // interpreter_tests.js; this is just checking behaviour of get/set // builtins. { name: 'Thread.prototype.getTimeLimit() initially 0', src: `Thread.current().getTimeLimit();`, expected: 0, }, { name: 'Thread.prototype.setTimeLimit()', src: ` Thread.current().setTimeLimit(1000); Thread.current().getTimeLimit(); `, expected: 1000, }, { name: 'Thread.prototype.setTimeLimit(...)', src: ` Thread.current().setTimeLimit(1000); Thread.current().getTimeLimit(); `, expected: 1000, }, // Check invalid time limits are rejected. { name: 'Thread.prototype.setTimeLimit(/* invalid value */) throws', src: ` Thread.current().setTimeLimit(1000); var invalid = [0, 1001, NaN, 'foo', true, {}]; var failures = []; for (var i = 0; i < invalid.length; i++) { try { Thread.current().setTimeLimit(invalid[i]); failures.push(invalid[i]); } catch (e) { } } (failures.length === 0) ? 'OK' : String(failures); `, expected: 'OK', }, ///////////////////////////////////////////////////////////////////////////// // Permissions system: { name: 'perms returns root', src: `perms() === CC.root;`, expected: true, }, { name: 'setPerms', src: ` CC.root.name = 'Root'; var bob = {}; bob.name = 'Bob'; var r = ''; r += perms().name; (function() { setPerms(bob); r += perms().name; // Perms revert at end of scope. })(); r += perms().name; r; `, expected: 'RootBobRoot', }, { name: 'getOwnerOf', src: ` var bob = {}; var roots = {}; setPerms(bob); var bobs = new Object; Object.getOwnerOf(Object) === CC.root && Object.getOwnerOf(roots) === CC.root && Object.getOwnerOf(bobs) === bob `, expected: true, }, { name: 'setOwnerOf', src: ` var bob = {}; var obj = {}; Object.setOwnerOf(obj, bob) === obj && Object.getOwnerOf(obj) === bob; `, expected: true, }, ///////////////////////////////////////////////////////////////////////////// // Other tests: { name: 'new hack', src: `(new 'Array.prototype.push') === Array.prototype.push`, expected: true, }, { name: 'new hack with unkown builtin', src: ` try { new 'nonexistent-builtin-name'; } catch (e) { e.name; } `, expected: 'ReferenceError', }, { name: 'new hack with other than string literal', src: ` try { var builtin = 'Object.prototype'; new builtin; } catch (e) { e.name; } `, expected: 'TypeError', }, { name: 'ES6 causes syntax errors', src: ` var tests = [ // Class statements & expressions 'class Foo{};', 'false && class Foo{};', // Arrow functions. 'false && [].map((item) => String(item));', // For-of statement. 'for (var x of [1, 2, 3]) {};', // Let & const. 'let x;', 'const x;', ]; var failed = []; for (var i = 0; i < tests.length; i++) { try { eval(tests[i]); failed.push("Didn't throw: " + tests[i]); } catch (e) { if (e.name !== 'SyntaxError') { failed.push('Wrong error: ' + tests[i] + ' threw ' + String(e)); } } } failed.length ? failed.join('\\n') : 'OK'; `, expected: 'OK', }, { name: 'Strict mode syntax errors', src: ` var tests = [ // With statement. 'var o = {foo: 42}; var f = function() {with (o) {foo;}};', // Binding eval in global scope, or arguments in a function. 'var eval = "rebinding eval?!?";', '(function() {arguments = undefined;});', // Duplicate argument names. '(function(a, a) {});', "new Function('a', 'a', '');", // Octal numeric literals. '0777;', // Delete of unqualified or undeclared identifier. 'var foo; delete foo;', 'delete foo;', ]; var failed = []; for (var i = 0; i < tests.length; i++) { try { eval(tests[i]); failed.push("Didn't throw: " + tests[i]); } catch (e) { if (e.name !== 'SyntaxError') { failed.push('Wrong error: ' + tests[i] + ' threw ' + String(e)); } } } failed.length ? failed.join('\\n') : 'OK'; `, expected: 'OK', }, { name: 'Stack overflow errors', src: ` try { (function f() {f();})(); } catch (e) { e.name; } `, options: {stackLimit: 100}, expected: 'RangeError', }, { name: 'Minimum stack depth limit', src: ` function f() { try { return f() + 1; } catch (e) { return 1; } } var limit = f(); limit > 100 ? 'OK' : limit; `, options: {stackLimit: 1000}, expected: 'OK', }, ]; ================================================ FILE: server/tests/testing.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview General-purpose test infrastructure. * @author cpcallen@google.com (Christopher Allen) */ 'use strict'; const util = require('util'); /////////////////////////////////////////////////////////////////////////////// /** * Class that records benchmark results; much like Go's testing.B type. * @constructor */ function B() { this.results = {}; } /** * Report a benchmark or test result. * @param {string} status The test result status (e.g., 'OK', 'FAIL', 'SKIP'). * @param {string} name Name of test. * @param {string=} message Additional information to lot about result. */ B.prototype.result = function(status, name, message) { console.log('%s\t%s', status, name); if (message) { console.log(message); } this.results[status] = this.results[status] + 1 || 1; }; /** * Report a benchmark start. * @param {string} name Name of test. (Not used.) * @param {number} run Which run is this? (Run 0 is warm-up run.) */ B.prototype.start = function(name, run) { const r = (run === 0) ? 'WARMUP' : ('RUN ' + run); this.startTime = Date.now(); }; /** * Report a benchmark end. * @param {string} name Name of test. * @param {number} run Which run is this? (Run 0 is warm-up run.) */ B.prototype.end = function(name, run) { const endTime = Date.now(); const r = (run === 0) ? 'WARMUP' : ('RUN ' + run); console.log('%s\t%s: %d ms', r, name, endTime - this.startTime); this.startTime = Date.now(); }; /** * Report a benchmark or test failure due to crash. * @param {string} name Name of test. * @param {string=} message Additional info (e.g., stack trace) to log. */ B.prototype.crash = function(name, message) { this.result('CRASH', name, message); }; /** * Report a bench or test skip. * @param {string} name Name of test. * @param {string=} message Additional info to log. */ B.prototype.skip = function(name, message) { this.result('SKIP', name, message); }; /** * Return results as string. * @return {string} */ B.prototype.toString = function() { const lines = ['Totals:']; for (const status in this.results) { lines.push(util.format('%s\t%d tests', status, this.results[status])); } return lines.join('\n'); }; /////////////////////////////////////////////////////////////////////////////// /** * Class that records test results; much like Go's testing.T type. * @constructor * @extends {B} */ function T() { B.call(this); this.results['OK'] = 0; this.results['FAIL'] = 0; } T.prototype = Object.create(B.prototype); T.prototype.constructor = T; /** * Report a test result. * @param {string} status The test result status (e.g., 'OK', 'FAIL', 'SKIP'). * @param {string} name Name of test. * @param {string=} message Additional info to log. */ T.prototype.result = function(status, name, message) { status === 'OK' || console.log('%s:\t%s', status, name); if (message) { console.log(message); } this.results[status] = this.results[status] + 1 || 1; }; /** * Report a test pass. * @param {string} name Name of test. * @param {string=} message Additional info to log. */ T.prototype.pass = function(name, message) { this.result('OK', name, message); }; /** * Report a test failure. * @param {string} name Name of test. * @param {string=} message Additional info to log. */ T.prototype.fail = function(name, message) { this.result('FAIL', name, message); }; /** * Check if assertion is true and nd record test pass if so or test * failure otherwise. * @param {string} name The name of the test. * @param {*} assertion Condition to verify. * @param {string=} message Additional info to log on failure only. */ T.prototype.assert = function(name, assertion, message) { if (assertion) { this.pass(name); } else { this.fail(name, message); } }; /** * Check if Object.is(got, want) and record test pass if so or test * failure otherwise. * @param {string} name The name of the test. * @param {*} got The actual result of the test. * @param {*} want The expected result of the test. * @param {string=} message Additional info to log on failure only. */ T.prototype.expect = function(name, got, want, message) { if (Object.is(got, want)) { this.pass(name); } else { message = message ? message + '\n' : ''; // Are they both strings, and at least one has multiple lines? if (typeof(got) === 'string' && typeof(want) === 'string' && (got.trimRight().split('\n').length > 1 || want.trimRight().split('\n').length > 1)) { message = util.format('%sgot:\n%s\nwant:\n%s', message, got, want); } else { message = util.format('%sgot %o want %o', message, got, want); } this.fail(name, message); } }; exports.B = B; exports.T = T; ================================================ FILE: server/tests/tinycore/README ================================================ A very tiny database, just big enough to run an eval server. ================================================ FILE: server/tests/tinycore/core_00_es_minimal.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Polyfills to bring the server's partial JavaScript * implementation up to JavaScript 5.1 (or close to it). * @author fraser@google.com (Neil Fraser) */ // Global functions. var parseInt = new 'parseInt'; var parseFloat = new 'parseFloat'; var isNaN = new 'isNaN'; var isFinite = new 'isFinite'; // Global objects. var Object = new 'Object'; var Function = new 'Function'; var Array = new 'Array'; var String = new 'String'; var Boolean = new 'Boolean'; var Number = new 'Number'; var Date = new 'Date'; var RegExp = new 'RegExp'; var Error = new 'Error'; var EvalError = new 'EvalError'; var RangeError = new 'RangeError'; var ReferenceError = new 'ReferenceError'; var SyntaxError = new 'SyntaxError'; var TypeError = new 'TypeError'; var URIError = new 'URIError'; var Math = {}; var JSON = {}; // Bootstrap the defineProperty function in two steps. Object.defineProperty = new 'Object.defineProperty'; Object.defineProperty(Object, 'defineProperty', {enumerable: false}); (function() { // Hack to work around restriction that the 'new hack' only works on // literal strings. Note name must not contain any double quotes or // backslashes, because we have no easy way to escape them yet! var builtin = function(name) { return eval('new "' + name + '"'); }; var classes = ['Object', 'Function', 'Array', 'String', 'Boolean', 'Number', 'Date', 'RegExp', 'Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError']; // Prototypes of global constructors. for (var i = 0; i < classes.length; i++) { var constructor = builtin(classes[i]); Object.defineProperty(constructor, 'prototype', { configurable: false, enumerable: false, writable: false, value: builtin(classes[i] + '.prototype') }); Object.defineProperty(constructor.prototype, 'constructor', { configurable: true, enumerable: false, writable: true, value: constructor }); } // Configure Error and its subclasses. var errors = ['Error', 'EvalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError']; for (var i = 0; i < errors.length; i++) { var constructor = builtin(errors[i]); Object.defineProperty(constructor.prototype, 'name', { configurable: true, enumerable: false, writable: true, value: errors[i] }); } Object.defineProperty(Error.prototype, 'message', { configurable: true, enumerable: false, writable: true, value: '' }); // Struct is a list of tuples: // [Object, 'Object', [static methods], [instance methods]] var struct = [ [Object, 'Object', ['create', 'getOwnPropertyNames', 'keys', 'getOwnPropertyDescriptor', 'getPrototypeOf', 'isExtensible', 'preventExtensions'], ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'propertyIsEnumerable', 'isPrototypeOf']], [Function, 'Function', [], ['apply', 'bind', 'call', 'toString']], [Array, 'Array', ['isArray'], ['toString', 'pop', 'push', 'shift', 'unshift', 'reverse', 'splice', 'slice', 'concat', 'indexOf', 'lastIndexOf']], [String, 'String', ['fromCharCode'], ['trim', 'toLowerCase', 'toUpperCase', 'toLocaleLowerCase', 'toLocaleUpperCase', 'charAt', 'charCodeAt', 'substring', 'slice', 'substr', 'indexOf', 'lastIndexOf', 'concat', 'localeCompare', 'replace', 'split', 'match', 'search', 'replace', 'toString', 'valueOf']], [Boolean, 'Boolean', [], ['toString', 'valueOf']], [Number, 'Number', [], ['toExponential', 'toFixed', 'toLocaleString', 'toPrecision', 'toString', 'valueOf']], [Date, 'Date', ['now', 'parse', 'UTC'], ['toString', 'getDate', 'getDay', 'getFullYear', 'getHours', 'getMilliseconds', 'getMinutes', 'getMonth', 'getSeconds', 'getTime', 'getTimezoneOffset', 'getUTCDate', 'getUTCDay', 'getUTCFullYear', 'getUTCHours', 'getUTCMilliseconds', 'getUTCMinutes', 'getUTCMonth', 'getUTCSeconds', 'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds', 'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear', 'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds', 'setYear', 'toDateString', 'toISOString', 'toJSON', 'toGMTString', 'toTimeString', 'toUTCString', 'toLocaleDateString', 'toLocaleString', 'toLocaleTimeString']], [RegExp, 'RegExp', [], ['toString', 'test', 'exec']], [Error, 'Error', [], ['toString']], [Math, 'Math', ['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'random', 'round', 'sin', 'sqrt', 'tan'], []], [JSON, 'JSON', ['parse', 'stringify'], []] ]; for (var i = 0; i < struct.length; i++) { var obj = struct[i][0]; var objName = struct[i][1]; var staticMethods = struct[i][2]; var instanceMethods = struct[i][3]; for (var j = 0; j < staticMethods.length; j++) { var member = staticMethods[j]; Object.defineProperty(obj, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.' + member)}); } for (var j = 0; j < instanceMethods.length; j++) { var member = instanceMethods[j]; Object.defineProperty(obj.prototype, member, {configurable: true, enumerable: false, writable: true, value: builtin(objName + '.prototype.' + member)}); } } })(); Object.defineProperty(Number, 'MAX_VALUE', { configurable: false, enumerable: false, writable: false, value: 1.7976931348623157e+308 }); Object.defineProperty(Number, 'MIN_VALUE', { configurable: false, enumerable: false, writable: false, value: 5e-324 }); Object.defineProperty(Number, 'NaN', { configurable: false, enumerable: false, writable: false, value: NaN }); Object.defineProperty(Number, 'NEGATIVE_INFINITY', { configurable: false, enumerable: false, writable: false, value: -Infinity }); Object.defineProperty(Number, 'POSITIVE_INFINITY', { configurable: false, enumerable: false, writable: false, value: Infinity }); Object.defineProperty(Math, 'E', { configurable: false, enumerable: false, writable: false, value: 2.718281828459045 }); Object.defineProperty(Math, 'LN2', { configurable: false, enumerable: false, writable: false, value: 0.6931471805599453 }); Object.defineProperty(Math, 'LN10', { configurable: false, enumerable: false, writable: false, value: 2.302585092994046 }); Object.defineProperty(Math, 'LOG2E', { configurable: false, enumerable: false, writable: false, value: 1.4426950408889634 }); Object.defineProperty(Math, 'LOG10E', { configurable: false, enumerable: false, writable: false, value: 0.4342944819032518 }); Object.defineProperty(Math, 'PI', { configurable: false, enumerable: false, writable: false, value: 3.141592653589793 }); Object.defineProperty(Math, 'SQRT1_2', { configurable: false, enumerable: false, writable: false, value: 0.7071067811865476 }); Object.defineProperty(Math, 'SQRT2', { configurable: false, enumerable: false, writable: false, value: 1.4142135623730951 }); Object.defineProperty(RegExp.prototype, 'global', { configurable: false, enumerable: false, writable: false, value: undefined }); Object.defineProperty(RegExp.prototype, 'ignoreCase', { configurable: false, enumerable: false, writable: false, value: undefined }); Object.defineProperty(RegExp.prototype, 'multiline', { configurable: false, enumerable: false, writable: false, value: undefined }); Object.defineProperty(RegExp.prototype, 'source', { configurable: false, enumerable: false, writable: false, value: '(?:)' }); /////////////////////////////////////////////////////////////////////////////// // Array.prototype polyfills /////////////////////////////////////////////////////////////////////////////// (function() { // For cycle detection in array to string and error conversion; see // spec bug github.com/tc39/ecma262/issues/289. var visited = []; Object.defineProperty(Array.prototype, 'join', {value: function(separator) { // This implements Array.prototype.join from ES5 §15.4.4.5, with // the addition of cycle detection as discussed in // https://github.com/tc39/ecma262/issues/289. // // Variable names reflect those in the spec. // // N.B. This function is defined in a closure! var isObj = (typeof this === 'object' || typeof this === 'function') && this !== null; if (isObj) { if (visited.indexOf(this) !== -1) { return ''; } visited.push(this); } try { // TODO(cpcallen): setPerms(callerPerms()); var len = this.length >>> 0; var sep = (separator === undefined) ? ',' : String(separator); if (!len) { return ''; } var r = ''; for (var k = 0; k < len; k++) { if (k > 0) r += sep; var element = this[k]; if (element !== undefined && element !== null) { r += String(element); } } return r; } finally { if (isObj) visited.pop(); } }, configurable: true, writable: true}); })(); /////////////////////////////////////////////////////////////////////////////// // String.prototype polyfills /////////////////////////////////////////////////////////////////////////////// // String.prototype.length is always 0. Object.defineProperty(String.prototype, 'length', {value: 0}); ================================================ FILE: server/tests/tinycore/core_10_base.js ================================================ /** * @license * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Demonstration database for Code City. * @author fraser@google.com (Neil Fraser) */ var $ = function() { throw new Error('not implemented'); }; // System object: $.system $.system = {}; $.system.connectionListen = new 'CC.connectionListen'; $.system.connectionUnlisten = new 'CC.connectionUnlisten'; $.system.connectionWrite = new 'CC.connectionWrite'; $.system.connectionClose = new 'CC.connectionClose'; $.system.xhr = new 'CC.xhr'; // Utility object: $.utils $.utils = {}; $.connection = {}; $.connection.onConnect = function() { this.user = null; this.buffer = ''; }; $.connection.onReceive = function(text) { this.buffer += text.replace(/\r/g, ''); var lf; while ((lf = this.buffer.indexOf('\n')) !== -1) { var line = this.buffer.substring(0, lf); this.buffer = this.buffer.substring(lf + 1); this.onReceiveLine(line); } }; $.connection.onReceiveLine = function(text) { // Override this on child classes. }; $.connection.onEnd = function() { // Override this on child classes. }; $.connection.write = function(text) { $.system.connectionWrite(this, text); }; $.connection.close = function() { $.system.connectionClose(this); }; $.servers = {}; ================================================ FILE: server/tests/tinycore/core_13_$.utils.code.js ================================================ /** * @license * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Code utilities for Code City. * @author fraser@google.com (Neil Fraser) */ $.utils.code = {}; $.utils.code.toSource = function(value, opt_seen) { // Given an arbitrary value, produce a source code representation. // Primitive values are straightforward: "42", "'abc'", "false", etc. // Functions, RegExps, Dates, Arrays, and errors are returned as their // definitions. // Other objects and symbols are returned as selector expression. // Throws if a code representation can't be made. var type = typeof value; if (value === undefined || value === null || type === 'number' || type === 'boolean') { if (Object.is(value, -0)) { return '-0'; } return String(value); } else if (type === 'string') { return JSON.stringify(value); } else if (type === 'function') { return Function.prototype.toString.call(value); } else if (type === 'object') { // TODO: Replace opt_seen with Set, once available. if (opt_seen) { if (opt_seen.includes(value)) { throw new RangeError('[Recursive data structure]'); } opt_seen.push(value); } else { opt_seen = [value]; } var proto = Object.getPrototypeOf(value); if (proto === RegExp.prototype) { return String(value); } else if (proto === Date.prototype) { return 'Date(\'' + value.toJSON() + '\')'; } else if (proto === Array.prototype && Array.isArray(value) && value.length <= 100) { var props = Object.getOwnPropertyNames(value); var data = []; for (var i = 0; i < value.length; i++) { if (props.includes(String(i))) { try { data[i] = $.utils.code.toSource(value[i], opt_seen); } catch (e) { // Recursive data structure. Bail. data = null; break; } } else { data[i] = ''; } } if (data) { return '[' + data.join(', ') + ']'; } } else if (value instanceof Error) { var constructor; if (proto === Error.prototype) { constructor = 'Error'; } else if (proto === EvalError.prototype) { constructor = 'EvalError'; } else if (proto === RangeError.prototype) { constructor = 'RangeError'; } else if (proto === ReferenceError.prototype) { constructor = 'ReferenceError'; } else if (proto === SyntaxError.prototype) { constructor = 'SyntaxError'; } else if (proto === TypeError.prototype) { constructor = 'TypeError'; } else if (proto === URIError.prototype) { constructor = 'URIError'; } else if (proto === PermissionError.prototype) { constructor = 'PermissionError'; } var msg; if (value.message === undefined) { msg = ''; } else { try { msg = $.utils.code.toSource(value.message, opt_seen); } catch (e) { // Leave msg undefined. } } if (constructor && msg !== undefined) { return constructor + '(' + msg + ')'; } } } if (type === 'object' || type === 'symbol') { // No Selectors in this tiny db, so just toString it. return Object.prototype.toString.call(value); } // Can't happen. throw new TypeError('[' + type + ']'); }; $.utils.code.eval = function(src, evalFunc) { // Eval src and attempt to print the resulting value readably. // // Evaluation is done by calling evalFunc (passing src) if supplied, // or by calling the eval built-in function (under a different name, // so it operates in the global scope). Unhandled exceptions are // caught and converted to a string. // // Caller may wish to transform input with // $.utils.code.rewriteForEval before passing it to this function. evalFunc = evalFunc || eval; var out; try { out = evalFunc(src); try { // Attempt to print a source-legal representation. out = $.utils.code.toSource(out); } catch (e) { try { // Maybe it's something JSON can deal with (like an array). out = JSON.stringify(out); } catch (e) { try { // Maybe it's a recursive data structure. out = String(out); } catch (e) { // Maybe it's Object.create(null). out = '[Unprintable value]'; } } } } catch (e) { // Exception thrown. Use built-in ToString via + to avoid calling // String, least it call a .toString method that itself throws. // TODO(cpcallen): find an alternative way of doing this safely // once the interpreter calls String for all string conversions. if (e instanceof Error) { out = 'Unhandled error: ' + e.name; if (e.message) { out += ': ' + e.message; } if (e.stack) { out += '\n' + e.stack; } } else { out = 'Unhandled exception: ' + e; } } return out; }; ================================================ FILE: server/tests/tinycore/core_35_$.servers.eval.js ================================================ /** * @license * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Eval server for Code City. * @author cpcallen@google.com (Christopher Allen) */ $.servers.eval = {}; $.servers.eval.connected = null; $.servers.eval.connection = Object.create($.connection); $.servers.eval.connection.onConnect = function() { $.connection.onConnect.apply(this, arguments); if ($.servers.eval.connected) { $.servers.eval.connected.close(); } $.servers.eval.connected = this; this.write('eval> '); }; $.servers.eval.connection.onReceiveLine = function(text) { if (this !== $.servers.eval.connected) { this.close(); return; } this.write('⇒ ' + $.utils.code.eval(text) + '\n'); this.write('eval> '); }; $.servers.eval.connection.onEnd = function() { $.servers.eval.connected = null; return $.connection.onEnd.apply(this, arguments); }; $.servers.eval.connection.close = function() { this.write('This session has been terminated.\n'); return $.connection.close.apply(this, arguments); }; $.system.connectionListen(9999, $.servers.eval.connection, 100); ================================================ FILE: server/tests/tinycore/dump_spec.json ================================================ [ { "filename": "core_00_es_minimal.js", "contents": [ {"path": "Object", "do": "SET"}, {"path": "Function", "do": "SET"}, {"path": "Object.defineProperty", "do": "ATTR"}, "Object", "Function", "Array", "String", "Boolean", "Number", "Date", "RegExp", "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError", "URIError", "Math", "JSON", "isFinite", "isNaN", "parseFloat", "parseInt" ] }, { "filename": "core_10_base.js", "contents": [ {"path": "$", "do": "SET"}, "$.system", "$.utils", "$.connection", "$.servers" ] }, { "filename": "core_13_$.utils.code.js", "contents": [ "$.utils.code" ] }, { "filename": "core_35_$.servers.eval.js", "contents": [ "$.servers.eval" ] }, { "options": {"treeOnly": false} }, { "filename": "core_99_rest.js", "rest": true } ] ================================================ FILE: server/tests/tinycore/tiny.cfg ================================================ { "databaseDirectory": "./", "checkpointInterval": 0, "checkpointAtShutdown": false, "checkpointMinFiles": 0, "checkpointMaxDirectorySize": 0 } ================================================ FILE: static/503.html ================================================ 503 - Code City

503 Unavailable

Uh oh…

For some reason the Code City server is not responding to HTTP connections. Could be that it has crashed, overloaded, or down for maintenance—or it could be that we've accidentally broken the internal web server ($.servers.http). In the latter case you might still be able to login via the telnet interface as usual.

In any case the problem is likely to be temporary so do please come back later and try again!

================================================ FILE: static/code/code.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Integrated Development Environment for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; /** * If not otherwise specified, what should /code point at? */ Code.DEFAULT = '$'; /** * Raw string of selector. * E.g. '$.foo["bar"]' */ Code.selector = location.search ? decodeURIComponent(location.search.substring(1)) : Code.DEFAULT; /** * Got a ping from someone. Check sessionStorage to see if selector has * changed and, if so, propagate ping to subframes. * @param {?Event} event Message event, or null if called from popState. */ Code.receiveMessage = function(event) { // Check to see if the stored values have changed. var selector = sessionStorage.getItem(Code.Common.SELECTOR); if (selector === Code.selector) { return; } Code.selector = selector; if (event) { // Change the URL if this is NOT the result of a forwards/back navigation. var query = encodeURIComponent(selector); query = query.replace(/%24/g, '$'); // No need to encode $. history.pushState(selector, selector, '?' + query); } // Propagate the ping down the tree of frames. try { document.getElementById('explorer').contentWindow.postMessage('ping', '*'); } catch (e) { // Maybe explorer frame hasn't loaded yet. } try { document.getElementById('editor').contentWindow.postMessage('ping', '*'); } catch (e) { // Maybe editor frame hasn't loaded yet. } Code.setTitle(); }; /** * User has navigated forwards or backwards. * @param {!Event} event History change event. */ Code.popState = function(event) { var selector = event.state || Code.DEFAULT; sessionStorage.setItem(Code.Common.SELECTOR, selector); // Attempt to pull the focus away from the explorer's input field. // This will allow it to update the displayed selector. try { document.getElementById('explorer').contentDocument .getElementById('input').blur(); } catch (e) { console.log('Unable to blur input: ' + e); } Code.receiveMessage(null); }; /** * Set the code editor's title. */ Code.setTitle = function() { var title = Code.selector; if (title.length > 36) { // Max title length in Chrome is 36 before truncation. title = '…' + title.substr(-35); } document.title = title; }; if (!window.TEST) { Code.setTitle(); sessionStorage.setItem(Code.Common.SELECTOR, Code.selector); window.addEventListener('message', Code.receiveMessage, false); window.addEventListener('popstate', Code.popState, false); } //////////////////////////////////////////// // Add bridge for SVG editor's clipboard. This copy allows the clipboard to // sync across all /code tabs even if the SVG editor isn't currently loaded. // Copied from /code/SVG-Edit/svgcanvas.js const CLIPBOARD_ID = 'svgedit_clipboard'; /** * Flash the clipboard data momentarily on localStorage so all tabs can see. * @returns {void} */ function flashStorage () { const data = sessionStorage.getItem(CLIPBOARD_ID); localStorage.setItem(CLIPBOARD_ID, data); setTimeout(function () { localStorage.removeItem(CLIPBOARD_ID); }, 1); } /** * Transfers sessionStorage from one tab to another. * @param {!Event} ev Storage event. * @returns {void} */ function storageChange(ev) { if (!ev.newValue) return; // This is a call from removeItem. if (ev.key === CLIPBOARD_ID + '_startup') { // Another tab asked for our sessionStorage. localStorage.removeItem(CLIPBOARD_ID + '_startup'); flashStorage(); } else if (ev.key === CLIPBOARD_ID) { // Another tab sent data. sessionStorage.setItem(CLIPBOARD_ID, ev.newValue); } } // Listen for changes to localStorage. window.addEventListener('storage', storageChange, false); // Ask other tabs for sessionStorage (this is ONLY to trigger event). localStorage.setItem(CLIPBOARD_ID + '_startup', Math.random()); // End of bridge for SVG editor's clipboard. //////////////////////////////////////////// ================================================ FILE: static/code/common.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Integrated Development Environment for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; var Code = {}; Code.Common = {}; // Keys for the sessionStorage. Code.Common.SELECTOR = 'code selector'; // Set containing all supported {xyz} names. Code.Common.KEYWORD_TYPES = new Set(['{proto}', '{owner}', '{children}', '{owned}', '{keys}', '{values}']); /** * Tokenize a string such as '$.foo["bar"]' into tokens: * {type: "id", raw: "$", valid: true, index: 0, value: "$"} * {type: ".", raw: ".", valid: true, index: 1} * {type: "id", raw: "foo", valid: true, index: 2, value: "foo"} * {type: "[", raw: "[", valid: true, index: 5} * {type: "str", raw: ""bar"", valid: true, index: 6, value: "bar"} * {type: "]", raw: "]", valid: true, index: 11} * Other tokens include: * {type: "num", raw: "42", valid: true, index: 2, value: 42} * {type: "keyword", raw: "{proto}", valid: true, index: 5, value: '{proto}'} * {type: "keyword", raw: "{owner}", valid: true, index: 5, value: '{owner}'} * {type: "keyword", raw: "{children}", valid: true, index: 5, value: '{children}'} * {type: "keyword", raw: "{owned}", valid: true, index: 5, value: '{owned}'} * {type: "keyword", raw: "{keys}", valid: true, index: 5, value: '{keys}'} * {type: "keyword", raw: "{values}", valid: true, index: 5, value: '{values}'} * If the string is permanently invalid, the last token is: * {type: "?", raw: "", valid: false} * A temporary token is used internally during parsing: * {type: "unparsed", raw: "[42].foo", index: 8} * @param {string} text Selector string. * @return {!Array} Array of tokens. */ Code.Common.tokenizeSelector = function(text) { // Trim left whitespace. var trimText = text.replace(/^[\s\xa0]+/, ''); if (!trimText) { return []; } var whitespaceLength = text.length - trimText.length; text = trimText; // Split the text into an array of tokens. // First step is to create two types of tokens: 'str' and 'unparsed'. var state = null; // null - non-string state // 'sqStr' - single quote string // 'dqStr' - double quote string // 'sqSlash' - backslash in single quote string // 'dqSlash' - backslash in double quote string var tokens = []; var buffer = []; for (var i = 0; i < text.length; i++) { var char = text[i]; var index = whitespaceLength + i; if (state === null) { if (char === "'") { Code.Common.pushUnparsed_(buffer, index, tokens); state = 'sqStr'; } else if (char === '"') { Code.Common.pushUnparsed_(buffer, index, tokens); state = 'dqStr'; } else { buffer.push(char); } } else if (state === 'sqStr') { if (char === "'") { Code.Common.pushString_("'", buffer, index, tokens); state = null; } else { buffer.push(char); if (char === '\\') { state = 'sqSlash'; } } } else if (state === 'dqStr') { if (char === '"') { Code.Common.pushString_('"', buffer, index, tokens); state = null; } else { buffer.push(char); if (char === '\\') { state = 'dqSlash'; } } } else if (state === 'sqSlash') { buffer.push(char); state = 'sqStr'; } else if (state === 'dqSlash') { buffer.push(char); state = 'dqStr'; } } if (state !== null) { // Convert state into quote type. var quotes = (state === 'sqStr' || state === 'sqSlash') ? "'" : '"'; Code.Common.pushString_(quotes, buffer, index + 1, tokens); } else if (buffer.length) { Code.Common.pushUnparsed_(buffer, index + 1, tokens); } // Second step is to parse each 'unparsed' token and split out '[', and ']' // tokens. for (var i = tokens.length - 1; i >= 0; i--) { var token = tokens[i]; if (token.type === 'unparsed') { var index = token.index + token.raw.length; // Split string on brackets. var split = token.raw.split(/(\s*[\[\]]\s*)/); for (var j = split.length - 1; j >= 0; j--) { var raw = split[j]; index -= raw.length; var rawTrim = raw.trim(); if (raw === '') { split.splice(j, 1); // Delete the empty string. continue; } else if (rawTrim === '[' || rawTrim === ']') { split[j] = {type: rawTrim, valid: true}; } else { split[j] = {type: 'unparsed'}; } split[j].raw = raw; split[j].index = index; } // Replace token with split array. split.unshift(i, 1); Array.prototype.splice.apply(tokens, split); } } // Third step is to parse each 'unparsed' token and split out '{xxx}' tokens. for (var i = tokens.length - 1; i >= 0; i--) { var token = tokens[i]; if (token.type === 'unparsed') { var index = token.index + token.raw.length; var split = token.raw.split(/(\s*{\s*\w*\s*(?:}\s*|$))/); for (var j = split.length - 1; j >= 0; j--) { var raw = split[j]; index -= raw.length; var rawTrim = raw.trim(); if (raw === '') { split.splice(j, 1); // Delete the empty string. continue; } var m = rawTrim.match(/{\s*(\w*)\s*(}|$)/); if (m) { var keywordToken = {type: 'keyword', value: '{' + m[1] + m[2]}; keywordToken.complete = Code.Common.KEYWORD_TYPES.has(keywordToken.value); if (keywordToken.complete) { keywordToken.valid = true; } else { keywordToken.valid = false; for (var validKeyword of Code.Common.KEYWORD_TYPES) { if (validKeyword.startsWith(keywordToken.value)) { keywordToken.valid = true; break; } } } split[j] = keywordToken; } else { split[j] = {type: 'unparsed'}; } split[j].raw = raw; split[j].index = index; } // Replace token with split array. split.unshift(i, 1); Array.prototype.splice.apply(tokens, split); } } // Fourth step is to parse each 'unparsed' token as a number, if it is // preceded by a '[' token. If the result is NaN (e.g. in the case it is an // unquoted identifier) mark the token as invalid. for (var i = 1; i < tokens.length; i++) { var token = tokens[i]; if (tokens[i - 1].type === '[' && token.type === 'unparsed') { token.type = 'num'; token.value = NaN; token.valid = false; // Does not support E-notation or NaN. if (/^\s*[-+]?(\d*\.?\d*|Infinity)\s*$/.test(token.raw)) { token.value = Number(token.raw); token.valid = !isNaN(token.value); token.value = String(token.value); } } } // Fifth step is to split remaining 'unparsed' tokens into 'id' and '.' // tokens. The '.' tokens could not be split out before numbers were parsed, // since numbers have decimal points. var unicodeRegex = /\\u([0-9A-F]{4})/ig; function decodeUnicode(m, p1) { return String.fromCodePoint(parseInt(p1, 16)); } for (var i = tokens.length - 1; i >= 0; i--) { var token = tokens[i]; if (token.type !== 'unparsed') { continue; } var index = token.index + token.raw.length; // Split string on periods. var split = token.raw.split(/(\s*\.\s*)/); for (var j = split.length - 1; j >= 0; j--) { var raw = split[j]; index -= raw.length; if (raw === '') { split.splice(j, 1); // Delete the empty string. continue; } else if (raw.trim() === '.') { split[j] = { type: '.', valid: true }; } else { // Parse Unicode escapes in identifiers. var valid = true; var value = split[j]; while (true) { var test = value.replace(unicodeRegex, ''); if (!test.includes('\\')) { break; } // Invalid escape found. Trim off last char and try again. value = value.substring(0, value.length - 1); valid = false; } // Decode Unicode. value = value.replace(unicodeRegex, decodeUnicode); split[j] = {type: 'id', value: value, valid: valid}; } split[j].raw = raw; split[j].index = index; } // Replace token with split array. split.unshift(i, 1); Array.prototype.splice.apply(tokens, split); } // Finally, validate order of tokens. Only check for permanent errors. // E.g. '$..foo' can never be legal. // E.g. '$["foo' isn't legal now, but could become legal after more typing. var state = 0; // 0 - Start or after '.'. Expecting 'id'. // 1 - After 'id' or ']' or 'keyword'. // Expecting '.' or '[' or 'keyword'. // 2 - After '['. Expecting 'str' or 'num'. // 3 - After 'str' or 'num'. Expecting ']'. for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (state === 0) { if (token.type === 'id') { state = 1; } else { break; } } else if (state === 1) { if (token.type === '.') { state = 0; } else if (token.type === 'keyword') { state = 1; } else if (token.type === '[') { state = 2; } else { break; } } else if (state === 2) { if (token.type === 'str' || token.type === 'num') { state = 3; } else { break; } } else if (state === 3) { if (token.type === ']') { state = 1; } else { break; } } else { break; } } // Remove any illegal tokens. if (i < tokens.length) { tokens = tokens.slice(0, i); // Add fail token to prevent autocompletion. tokens.push({type: '?', raw: '', valid: false}); } return tokens; }; /** * Push a 'str' token type onto the list of tokens. * Handles invalid strings, e.g. 'abc \u---- xyz' * @param {string} quotes Quote type (' vs "). * @param {!Array} buffer Array of chars that make the string. * @param {number} index Char index of start of this token in original input. * @param {!Array} tokens List of tokens. * @private */ Code.Common.pushString_ = function(quotes, buffer, index, tokens) { var token = { type: 'str', raw: quotes + buffer.join('') + quotes, valid: true }; token.index = index - (token.raw.length - 1); do { var raw = quotes + buffer.join('') + quotes; // Attempt to parse a string. try { var str = eval(raw); break; } catch (e) { // Invalid escape found. Trim off last char and try again. buffer.pop(); token.valid = false; } } while (true); buffer.length = 0; token.value = str; tokens.push(token); }; /** * Push an 'unparsed' token type onto the list of tokens. * @param {!Array} buffer Array of chars that make the value. * @param {number} index Character index of this token in original input. * @param {!Array} tokens List of tokens. * @private */ Code.Common.pushUnparsed_ = function(buffer, index, tokens) { var raw = buffer.join(''); buffer.length = 0; if (raw) { var token = { type: 'unparsed', raw: raw, index: index - raw.length }; tokens.push(token); } }; /** * Split a path selector into a list of parts. * E.g. '${proto}.foo' -> * [{type: 'id', value: '$'}, {type: 'keyword', value: '{proto}'}, {type: 'id', value: 'foo'}] * @param {string} text Selector string. * @return {?Array} Array of parts or null if invalid. */ Code.Common.selectorToParts = function(text) { // TODO: Try caching the results for performance. var tokens = Code.Common.tokenizeSelector(text); var parts = []; for (var token of tokens) { if (!token.valid) { return null; } if (['id', 'str', 'num'].includes(token.type)) { parts.push({type: 'id', value: token.value}); } else if (token.type === 'keyword') { parts.push({type: token.type, value: token.value}); } } return parts; }; /** * Join a list of parts into a path selector. * E.g. [{type: 'id', value: '$'}, {type: 'keyword', value: '{proto}'}, {type: 'id', value: 'foo'}] -> * '${proto}.foo' * @param {!Array} parts Array of parts. * @return {string} Selector string. */ Code.Common.partsToSelector = function(parts) { var text = ''; for (var i = 0; i < parts.length; i++) { var part = parts[i]; if (part.type === 'id') { var value = part.value; if (/^[A-Z_$][0-9A-Z_$]*$/i.test(value)) { if (i !== 0) { text += '.'; } text += value; } else { text += '['; if (/^-?\d{1,15}$/.test(value)) { text += value; } else { text += JSON.stringify(value); } text += ']'; } } else if (part.type === 'keyword') { text += part.value; } } return text; }; /** * Turn a selector string into a valid code reference. * E.g. "$.foo" -> "$.foo" * E.g. "${proto}.foo" -> "$('${proto}.foo')" * Join a list of parts into a valid code reference. * @param {string} selector Selector string. * @return {string} Code reference. */ Code.Common.selectorToReference = function(selector) { var noStrings = selector.replace(/(["'])(?:[^\1\\]|\\.)*?\1/g, ''); if (noStrings.includes('{')) { return "$('" + selector + "')"; } return selector; }; /** * Comparison function to sort strings A-Z without regard to case. * @param {string} a One string. * @param {string} b Another string. * @return {number} -1/0/1 comparator value. */ Code.Common.caseInsensitiveComp = function(a, b) { a = a.toLowerCase(); b = b.toLowerCase(); var aNum = parseFloat(a); var bNum = parseFloat(b); if (!isNaN(aNum) && !isNaN(bNum) && aNum !== bNum) { // Numeric. return (aNum < bNum) ? -1 : 1; } // ASCIIbetical. return (a < b) ? -1 : ((a > b) ? 1 : 0); }; // Set background colour to differentiate server vs local copy. if (location.hostname === 'localhost') { window.addEventListener('load', function() { document.body.style.backgroundColor = '#ffe'; }); } ================================================ FILE: static/code/diff.css ================================================ body { white-space: pre-wrap; } ins { background: #e6ffe6; } del { background: #ffe6e6; } ================================================ FILE: static/code/diff.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Diff Editor. * @author fraser@google.com (Neil Fraser) */ 'use strict'; var diffEditor = {}; /** * Diff Match Patch object. */ diffEditor.dmp = new diff_match_patch(); /** * Current source. */ diffEditor.source = ''; /** * Check to see if the parent window left us an initial source to render. */ diffEditor.init = function() { var newSource = window.initialSource; var oldSource = window.originalSource; if (newSource && oldSource) { diffEditor.setString(newSource, oldSource); delete window.initialSource; delete window.originalSource; } }; /** * Set the strings for a new diff. * @param {string} newString Current source. * @param {string} oldString Source as of last save. */ diffEditor.setString = function(newString, oldString) { this.source = newString; var diff = this.dmp.diff_main(oldString, newString); this.dmp.diff_cleanupSemantic(diff); diffEditor.render(diff, document.body); }; /** * Return the current source. * @return {string} Source. */ diffEditor.getString = function() { return this.source; }; /** * Convert a diff array into a pretty HTML report and inject it on the page. * @param {!Array.} diffs Array of diff tuples. * @param {!Element} container HTML element into which to render the diff. */ diffEditor.render = function(diffs, container) { container.innerHTML = ''; for (var i = 0; i < diffs.length; i++) { var op = diffs[i][0]; // Operation (insert, delete, equal) var text = diffs[i][1]; // Text of change. var el = document.createElement(diffEditor.tagMap[op]); el.appendChild(document.createTextNode(text)); container.appendChild(el); } }; /** * Mapping from diff operation to relevant tag. */ diffEditor.tagMap = {}; diffEditor.tagMap[DIFF_INSERT] = 'ins'; diffEditor.tagMap[DIFF_DELETE] = 'del'; diffEditor.tagMap[DIFF_EQUAL] = 'span'; window.addEventListener('load', diffEditor.init); ================================================ FILE: static/code/editor.css ================================================ #editorButter { display: none; left: 0; position: absolute; right: 0; top: 0; pointer-events: none; z-index: 10; } #editorButter>div { text-align: center; } #editorButterText { background: #f9edbe; border: 1px solid #f0c36d; border-radius: 0 0 2px 2px; border-top: 0; box-shadow: 0 2px 4px rgba(0,0,0,0.2); display: inline-block; padding: 0 10px; pointer-events: auto; } #valueEditor { position: absolute; top: 60px; bottom: 20px; left: 10px; right: 20px } #functionEditor { position: absolute; top: 60px; bottom: 45px; left: 10px; right: 20px } #jsspEditor { position: absolute; top: 60px; bottom: 45px; left: 10px; right: 20px } .editorBigQuotes { font-family: serif; font-size: 48pt; position: absolute; } ================================================ FILE: static/code/editor.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Integrated Development Environment for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; Code.Editor = {}; /** * List of complete object selector parts. * @type {Array} */ Code.Editor.parts = null; /** * Currently selected editor. * @type {?Code.GenericEditor} */ Code.Editor.currentEditor = null; /** * Current source code for editors that haven't yet been created. * @type {string} */ Code.Editor.uncreatedEditorSource = ''; /** * URL of this script. * Might be with or without subdomains: * https://static.google.codecity.world/code/editor.js * http://localhost:8080/static/code/editor.js * @type {string} */ Code.Editor.mySource = document.getElementById('editor_js').src; /** * Got a ping from someone. Something might have changed and need updating. */ Code.Editor.receiveMessage = function() { if (Code.Editor.isSaveDialogVisible) { return; // Ignore messages if the modal save dialog is up. } var selector = sessionStorage.getItem(Code.Common.SELECTOR); var parts = Code.Common.selectorToParts(selector); if (!parts || !parts.length) { return; // Invalid parts, ignore. } if (parts === Code.Editor.parts) { return; // No change. } if (Code.Editor.parts === null) { Code.Editor.load(); // Initial load of content. } else { Code.Editor.updateCurrentSource(); if (Code.Editor.currentSource === Code.Editor.originalSource) { Code.Editor.reload(); // Reload to load different content. } else { Code.Editor.showSave(); // User needs to save/discard/cancel. } } }; /** * Page has loaded, initialize the editor. */ Code.Editor.init = function() { // Initialize button handlers. document.getElementById('editorConfirmDiscard').addEventListener('click', Code.Editor.reload); document.getElementById('editorConfirmCancel').addEventListener('click', Code.Editor.hideDialog); document.getElementById('editorConfirmSave').addEventListener('click', Code.Editor.save); document.getElementById('editorSave').addEventListener('click', Code.Editor.save); document.getElementById('editorShare').addEventListener('click', Code.Editor.showShare); document.getElementById('editorShareOk').addEventListener('click', Code.Editor.hideDialog); document.getElementById('editorShareCheck').addEventListener('change', Code.Editor.checkShare); // Create the tabs. var tabRow = document.getElementById('editorTabs'); var containerRow = document.getElementById('editorContainers'); for (var i = 0, editor; (editor = Code.Editor.editors[i]); i++) { var span = document.createElement('span'); span.className = 'jfk-button'; span.appendChild(document.createTextNode(editor.name)); span.setAttribute('role', 'button'); span.setAttribute('tabindex', i); span.addEventListener('click', Code.Editor.tabClick); tabRow.appendChild(span); var spacer = document.createElement('span'); spacer.className = 'spacer'; tabRow.appendChild(spacer); var div = document.createElement('div'); containerRow.appendChild(div); // Cross-link span/div to editor. span.editor = editor; div.editor = editor; editor.tabElement = span; editor.containerElement = div; } document.addEventListener('keydown', Code.Editor.keyDown); Code.Editor.receiveMessage(); // Defer loading of JSHint to get editors running faster. setTimeout(Code.Editor.importJSHint, 1); }; /** * Load content into the editors. */ Code.Editor.load = function() { var selector = sessionStorage.getItem(Code.Common.SELECTOR); var parts = Code.Common.selectorToParts(selector); if (!parts) { return; // Invalid parts, ignore. } Code.Editor.parts = parts.slice(); // Shallow copy, since it's popped below. // Request data from Code City server. Code.Editor.key = undefined; Code.Editor.sendXhr(); // Set the header. var header = document.getElementById('editorHeader'); header.innerHTML = ''; if (parts.length < 2) { // Global object. var reference = Code.Common.partsToSelector(parts) + ' = '; } else { // Remove the last part. var lastPart = parts.pop(); var selector = Code.Common.partsToSelector(parts); var reference = Code.Common.selectorToReference(selector); // Put the last part back on. // Render as '.foo' or '[42]' or '["???"]' or '{xxx}'. if (lastPart.type === 'id') { var mockParts = [{type: 'id', value: 'X'}, lastPart]; reference += Code.Common.partsToSelector(mockParts).substring(1) + ' = '; } else if (lastPart.type === 'keyword') { if (lastPart.value === '{proto}') { reference = 'Object.setPrototypeOf(' + reference + ', ...) '; } else if (lastPart.value === '{owner}') { reference = 'Object.setOwnerOf(' + reference + ', ...) '; } else { throw new TypeError('Unknown keyword value: ' + lastPart.value); } } else { throw new TypeError('Unknown part type: ' + lastPart.type); } } header.appendChild(document.createTextNode(reference)); }; /** * Check the currently active editor and update Code.Editor.currentSource * if there has been a change. */ Code.Editor.updateCurrentSource = function() { if (Code.Editor.currentEditor && !Code.Editor.currentEditor.isSaved()) { Code.Editor.currentSource = Code.Editor.currentEditor.getSource(); } if (!Code.Editor.isSaveDialogVisible) { Code.Editor.saturateSave( Code.Editor.currentSource !== Code.Editor.originalSource); } }; /** * Keydown handler for the editor frame. * @param {!KeyboardEvent} e Keydown event. */ Code.Editor.keyDown = function(e) { // Save the editor if ⌘-s or Ctrl-s is pressed. if (e.key === 's' && (e.metaKey || e.ctrlKey)) { Code.Editor.save(); e.preventDefault(); e.stopPropagation(); } // Before starting a search, render the editors' entire document. if ((e.key === 'f' || e.key === 'g') && (e.metaKey || e.ctrlKey)) { if (Code.Editor.currentEditor) { var cm = Code.Editor.currentEditor.getCodeMirror(); if (cm) { cm.setOption('viewportMargin', Infinity); } } } }; /** * Save the current editor content. */ Code.Editor.save = function() { Code.Editor.updateCurrentSource(); Code.Editor.sendXhr(); // Prevent the user from interacting with the editor during an async save. // TODO: Implement merging. var mask = document.getElementById('editorSavingMask'); mask.style.display = 'block'; Code.Editor.saveMaskPid = setTimeout(function() { mask.style.opacity = 0.2; }, 1000); // Wait a second before starting visible transition. }; /** * Force a reload of this editor. Used to switch to edit something else. */ Code.Editor.reload = function() { Code.Editor.hideDialog(); Code.Editor.beforeUnload.disabled = true; location.reload(); }; /** * Issue a warning if the user has unsaved changes and is attempting to leave * the code editor (e.g. typing a new URL). This is not triggered due to * in-editor navigation. * @param {!Event} e A beforeunload event. */ Code.Editor.beforeUnload = function(e) { if (Code.Editor.isSaveDialogVisible) { // The user has already got a warning but is ignoring it. Just leave. Code.Editor.hideDialog(); return; } Code.Editor.updateCurrentSource(); if (!Code.Editor.beforeUnload.disabled && Code.Editor.currentSource !== Code.Editor.originalSource) { e.returnValue = 'You have unsaved changes.'; e.preventDefault(); } }; /** * Flag to allow navigation away from current page, despite unsaved changes. */ Code.Editor.beforeUnload.disabled = false; /** * Asynchronously load MobWrite's JavaScript files. * @param {!Function} callback Function to call when MobWrite is loaded. */ Code.Editor.loadMobWrite = function(callback) { if (!Code.Editor.waitMobWrite_.isLoaded) { var files = ['dmp.js', 'mobwrite_core.js', 'mobwrite_cc.js']; for (var file of files) { var script = document.createElement('script'); script.src = Code.Editor.mySource.replace('editor.js', 'mobwrite/' + file); document.head.appendChild(script); } } Code.Editor.waitMobWrite_(callback); }; /** * Wait for MobWrite to load. Initialize it, then run the callback. * @param {!Function} callback Function to call when MobWrite is loaded. * @private */ Code.Editor.waitMobWrite_ = function(callback) { if (typeof diff_match_patch === 'undefined' || typeof mobwrite === 'undefined' || typeof Code.MobwriteShare === 'undefined') { // Not loaded, try again later. setTimeout(Code.Editor.waitMobWrite_, 50, callback); } else { if (!Code.Editor.waitMobWrite_.isLoaded) { Code.MobwriteShare.init(); // Point MobWrite at the daemon on Code City. var url = Code.Editor.mySource.replace('/code/editor.js', ''); if (url.endsWith('/static')) { // http://localhost:8080/static mobwrite.syncGateway = url.replace(/\/static$/, '/mobwrite'); } else if (/:\/\/static\./.test(url)) { // https://static.google.codecity.world mobwrite.syncGateway = url.replace('://static.', '://mobwrite.'); } else { throw Error('Source does not match known pattern: ' + url); } Code.Editor.waitMobWrite_.isLoaded = true; } callback(); } }; Code.Editor.waitMobWrite_.isLoaded = false; /** * When a tab is clicked, highlight it and show its container. * @param {!Event|!Object} e Click event or object pretending to be an event. */ Code.Editor.tabClick = function(e) { if (Code.Editor.tabClick.disabled) { return; } // Unhighlight all tabs, hide all containers. var tab = document.querySelector('#editorTabs>.highlighted'); tab && tab.classList.remove('highlighted'); var containers = document.querySelectorAll('#editorContainers>div'); for (var container of containers) { container.style.display = 'none'; } Code.Editor.updateCurrentSource(); // Highlight one tab, show one container. var tab = e.target; tab.classList.add('highlighted'); var editor = tab.editor; Code.Editor.currentEditor = editor; var container = editor.containerElement; if (!editor.created) { editor.createDom(container); editor.created = true; } container.style.display = 'block'; Code.Editor.setSourceToAllEditors(Code.Editor.currentSource); // If e is an event, then this click is the result of a user's direct action. // If not, then it's a fake event as a result of page load. var userAction = e instanceof Event; editor.focus(userAction); }; /** * Don't allow clicking of tabs before data is received from Code City. */ Code.Editor.tabClick.disabled = true; /** * Send a request to Code City's code editor service. */ Code.Editor.sendXhr = function() { var selector = Code.Common.partsToSelector(Code.Editor.parts); var xhr = Code.Editor.codeRequest_; xhr.abort(); xhr.open('POST', 'editorXhr'); xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhr.onload = Code.Editor.receiveXhr; var src = Code.Editor.currentSource || ''; var data = 'key=' + encodeURIComponent(Code.Editor.key) + '&selector=' + encodeURIComponent(selector); if (src) { data += '&src=' + encodeURIComponent(src); } xhr.send(data); }; /** * Reusable XHR object for server pings. */ Code.Editor.codeRequest_ = new XMLHttpRequest(); /** * Got a response from Code City's code editor service. */ Code.Editor.receiveXhr = function() { var xhr = Code.Editor.codeRequest_; if (xhr.status !== 200) { Code.Editor.clearSaveMask(); Code.Editor.showButter('Save failed: Status ' + xhr.status, 5000); return; } var data = JSON.parse(xhr.responseText); if (data.hasOwnProperty('key')) { Code.Editor.key = data.key; } if (data.hasOwnProperty('src')) { Code.Editor.originalSource = data.src; // Only update the displayed source if a) this is the initial load, // or b) the previous save was successful. if (Code.Editor.currentSource === null || data.saved) { Code.Editor.currentSource = data.src; Code.Editor.setSourceToAllEditors(data.src); } } Code.Editor.clearSaveMask(); if (data.saved === false && !data.login) { // Save was requested, but failed due to lack of a login. // Open login window. var loginWindow = open('login', 'login', 'height=600,width=500'); if (loginWindow) { window.addEventListener('message', function(event) { if (event.data === 'closeMe') { loginWindow.close(); Code.Editor.save(); } }, false); } else { alert('Your browser has blocked the opening of the page you requested.\n' + 'Please allow pop-ups on this domain. ✓️'); } } // While a save is in-flight, the user might have navigated away and be // currently blocked by a warning dialog regarding unsaved work. if (Code.Editor.isSaveDialogVisible) { if (data.saved) { // If the save was successful, then proceed with the requested navigation. Code.Editor.reload(); } else { // If the save was not successful, close the dialog and hope there's some // butter to show. Code.Editor.hideDialog(); } } // If there's a message, show it in the butter. if (data.butter) { Code.Editor.showButter(data.butter, 5000); } Code.Editor.ready && Code.Editor.ready(); }; /** * Remove saving mask that prevents UI interaction. */ Code.Editor.clearSaveMask = function() { clearTimeout(Code.Editor.saveMaskPid); var mask = document.getElementById('editorSavingMask'); mask.style.display = 'none'; mask.style.opacity = 0; }; /** * The original source text from the server. * @type {?string} */ Code.Editor.originalSource = null; /** * Current source text from the most recent active editor. * @type {?string} */ Code.Editor.currentSource = null; /** * Data has been received, ready to allow the user to edit. */ Code.Editor.ready = function() { // Configure tabs. document.getElementById('editorTabs').classList.remove('disabled'); Code.Editor.tabClick.disabled = false; // Switch tabs to show the highest confidence editor. var bestEditor = Code.Editor.mostConfidentEditor(); if (bestEditor) { var fakeEvent = {target: bestEditor.tabElement}; Code.Editor.tabClick(fakeEvent); } // Remove the loading animation. var header = document.getElementById('editorHeader'); header.className = ''; // Update the save button's saturation state once a second. setInterval(Code.Editor.updateCurrentSource, 1000); var hash = parent && parent.location && parent.location.hash; if (hash.length > 1) { Code.Editor.loadMobWrite(function() { mobwrite.share('Code'); }); } // Only run this code once. Code.Editor.ready = undefined; }; /** * Find the editor with the highest confidence for the current text. * Confidence levels are recorded when text is set in each editor. * @return {Code.GenericEditor} Best editor, or null if none. */ Code.Editor.mostConfidentEditor = function() { var bestEditor = null; var bestConfidence = -Infinity; for (var editor of Code.Editor.editors) { if (bestConfidence < editor.confidence) { bestConfidence = editor.confidence; bestEditor = editor; } } return bestEditor; }; /** * Set the values of all the editors. * @param {string} src Plain text contents. */ Code.Editor.setSourceToAllEditors = function(src) { if (typeof src !== 'string') { throw TypeError(src); } Code.Editor.uncreatedEditorSource = src; for (var editor of Code.Editor.editors) { editor.setSource(src); // Round-trip version of the source. editor.unmodifiedSource = editor.getSource(); } }; /** * Show the save dialog. */ Code.Editor.showSave = function() { Code.Editor.showDialog('editorConfirmBox'); // Desaturate save button. Don't visually conflict with the 'save' button // in save dialog. Code.Editor.saturateSave(false); Code.Editor.isSaveDialogVisible = true; }; /** * Show the share dialog. */ Code.Editor.showShare = function() { Code.Editor.showDialog('editorShareBox'); document.body.style.cursor = 'wait'; Code.Editor.loadMobWrite(Code.Editor.populateShare); }; /** * Show the share dialog. */ Code.Editor.populateShare = function() { document.body.style.cursor = ''; document.getElementById('editorShareBox').className = ''; var check = document.getElementById('editorShareCheck'); check.disabled = ''; check.checked = !!Object.keys(mobwrite.shared).length; Code.Editor.checkShare(); }; /** * Called when the sharing checkbox is ticked or unticked. */ Code.Editor.checkShare = function() { var check = document.getElementById('editorShareCheck'); var input = document.getElementById('editorShareAddress'); input.disabled = !check.checked; var shared = !!Object.keys(mobwrite.shared).length; var hash = '#'; if (check.checked) { if (!shared) { mobwrite.share('Code'); } hash += Code.MobwriteShare.id; } else if (!check.checked) { if (shared) { mobwrite.unshare('Code'); } } if (parent && parent.history) { // Update the URL on the parent frame. parent.history.replaceState(undefined, undefined, hash); // Update the address field the user can copy from. input.value = check.checked ? parent.location : ''; input.select(); } }; /** * Show a dialog. * @param {string} contentId ID of dialog's content div. */ Code.Editor.showDialog = function(contentId) { // Clean up and hide existing things that might be visible. clearTimeout(Code.Editor.dialogAnimationPid); Code.Editor.hideButter(); document.getElementById('editorConfirmBox').style.display = 'none'; document.getElementById('editorShareBox').style.display = 'none'; // Show the requested dialog. document.getElementById(contentId).style.display = 'block'; document.getElementById('editorDialog').style.display = 'block'; var mask = document.getElementById('editorDialogMask'); var box = document.getElementById('editorDialogBox'); box.style.display = 'block'; mask.style.transitionDuration = '.4s'; box.style.transitionDuration = '.4s'; // Add a little bounce at the end of the animation. box.style.transitionTimingFunction = 'cubic-bezier(.6,1.36,.75,1)'; Code.Editor.dialogAnimationPid = setTimeout(function() { mask.style.opacity = 0.2; box.style.top = '-10px'; }, 100); // Firefox requires at least 10ms to process this timing function. }; /** * Hide the dialog. */ Code.Editor.hideDialog = function() { clearTimeout(Code.Editor.dialogAnimationPid); var mask = document.getElementById('editorDialogMask'); var box = document.getElementById('editorDialogBox'); mask.style.transitionDuration = '.2s'; box.style.transitionDuration = '.2s'; box.style.transitionTimingFunction = 'ease-in'; mask.style.opacity = 0; box.style.top = '-120px'; Code.Editor.dialogAnimationPid = setTimeout(function() { document.getElementById('editorDialog').style.display = 'none'; box.style.display = 'none'; document.getElementById('editorConfirmBox').style.display = 'none'; document.getElementById('editorShareBox').style.display = 'none'; }, 250); // Resaturate the save button. Code.Editor.saturateSave(true); Code.Editor.isSaveDialogVisible = false; }; /** * Is the save dialog currently visible? */ Code.Editor.isSaveDialogVisible = false; /** * PID of any animation task. Allows animations to be canceled so that two * near-simultaneous actions don't collide. */ Code.Editor.dialogAnimationPid = 0; /** * Saturate or desaturate the editor's save button. * @param {boolean} saturated True if button should be saturated. */ Code.Editor.saturateSave = function(saturated) { var button = document.getElementById('editorSave'); button.className = saturated ? 'jfk-button jfk-button-submit' : 'jfk-button'; }; /** * Show the text in the butter bar for a period of time. * Clobber any existing display. * @param {string} text Text to display. * @param {number} time Number of milliseconds to display butter. */ Code.Editor.showButter = function(text, time) { clearTimeout(Code.Editor.showButter.pid_); var textDiv = document.getElementById('editorButterText'); textDiv.innerHTML = ''; textDiv.appendChild(document.createTextNode(text)); document.getElementById('editorButter').style.display = 'block'; Code.Editor.showButter.pid_ = setTimeout(Code.Editor.hideButter, time); }; Code.Editor.showButter.pid_ = 0; /** * Hide the butter bar. */ Code.Editor.hideButter = function() { document.getElementById('editorButter').style.display = 'none'; }; /** * Create a CodeMirror editor. * @param {!Element} container HTML element to hold the editor. * @param {!Object} extraOptions Editor configuration. * @return {!Object} CodeMirron editor. */ Code.Editor.newCodeMirror = function(container, extraOptions) { var options = { extraKeys: { Tab: function(cm) { if (cm.somethingSelected()) { cm.indentSelection('add'); } else { cm.replaceSelection(' '); } }, 'Shift-Tab': function(cm) { cm.indentSelection('subtract'); } }, gutters: ['CodeMirror-lint-markers'], lineNumbers: true, matchBrackets: true, tabSize: 2, undoDepth: 1024 }; // Merge extraOptions into default options. Object.assign(options, extraOptions); var editor = CodeMirror(container, options); editor.setSize('100%', '100%'); return editor; }; /** * Has the JSHint library loaded yet? */ Code.Editor.JSHintReady = false; /** * Load the JSHint library. * Defer loading until page is loaded and responsive. */ Code.Editor.importJSHint = function() { // var script = document.createElement('script'); script.type = 'text/javascript'; script.src = Code.Editor.mySource.replace('code/editor.js', 'JSHint/jshint.js'); script.onload = function() { Code.Editor.JSHintReady = true; // Activate linting for any editor that's loaded and waiting. for (var i = 0, editor; (editor = Code.Editor.editors[i]); i++) { var cm = editor.getCodeMirror(); if (cm && editor.useJSHint) { cm.setOption('lint', true); } } }; document.head.appendChild(script); }; if (!window.TEST) { window.addEventListener('load', Code.Editor.init); window.addEventListener('message', Code.Editor.receiveMessage, false); window.addEventListener('beforeunload', Code.Editor.beforeUnload); } Code.Editor.editors = []; /** * Base class for editors. * @param {string} name User-facing name of editor (used in tab). * @constructor */ Code.GenericEditor = function(name) { /** * Human-readable name of editor. * @type {string} */ this.name = name; /** * A float from 0 (bad) to 1 (perfect) indicating the editor's fitness to * edit the given content. */ this.confidence = 0; /** * Has the DOM for this editor been created yet? */ this.created = false; /** * Span that forms the tab button. * @type {?Element} */ this.tabElement = null; /** * Div that forms the editor's container. * @type {?Element} */ this.containerElement = null; /** * Plain text representation of this editor's contents as of load or last save. * @type {?string} */ this.unmodifiedSource = null; /** * Should this editor use JSHint for syntax checking? */ this.useJSHint = false; // Register this editor. Code.Editor.editors.push(this); }; /** * Create the DOM for this editor. * @param {!Element} container DOM should be appended to this containing div. */ Code.GenericEditor.prototype.createDom = function(container) { var text = 'TODO: Implement createDom for ' + this.name + ' editor.'; container.appendChild(document.createTextNode(text)); }; /** * Get the contents of the editor. * @return {string} Plain text contents. */ Code.GenericEditor.prototype.getSource = function() { throw new ReferenceError('getSource not implemented on editor'); }; /** * Set the contents of the editor. * @param {string} source Plain text contents. */ Code.GenericEditor.prototype.setSource = function(source) { throw new ReferenceError('setSource not implemented on editor'); }; /** * Is the user's work in this editor saved? * @return {boolean} True if work is saved. */ Code.GenericEditor.prototype.isSaved = function() { return this.getSource() === this.unmodifiedSource; }; /** * Return this editor's CodeMirror instance. * @return {Object} Defaults to null. */ Code.GenericEditor.prototype.getCodeMirror = function() { return null; }; /** * Notification that this editor has just been displayed. * @param {boolean} userAction True if user clicked on a tab. */ Code.GenericEditor.prototype.focus = function(userAction) { }; //////////////////////////////////////////////////////////////////////////////// Code.valueEditor = new Code.GenericEditor('Value'); // The value editor can handle any content, but express a low confidence in // order to defer to more specialized editors. Code.valueEditor.confidence = 0.1; Code.valueEditor.useJSHint = true; /** * CodeMirror editor. Does not exist until tab is selected. * @type {Object} * @private */ Code.valueEditor.editor_ = null; /** * Return this editor's CodeMirror instance. * @return {Object} Defaults to null. */ Code.valueEditor.getCodeMirror = function() { return this.editor_; }; /** * Create the DOM for this editor. * @param {!Element} container DOM should be appended to this containing div. */ Code.valueEditor.createDom = function(container) { container.id = 'valueEditor'; // Use different theme in value editor to distinguish it from other editors. var options = { continueComments: {continueLineComment: false}, lint: Code.Editor.JSHintReady, mode: 'text/javascript', theme: 'default' }; this.editor_ = Code.Editor.newCodeMirror(container, options); }; /** * Get the contents of the editor. * @return {string} Plain text contents. */ Code.valueEditor.getSource = function() { return this.created ? this.editor_.getValue() : Code.Editor.uncreatedEditorSource; }; /** * Set the contents of the editor. * @param {string} source Plain text contents. */ Code.valueEditor.setSource = function(source) { if (this.created) { this.editor_.setValue(source); } }; /** * Notification that this editor has just been displayed. * @param {boolean} userAction True if user clicked on a tab. */ Code.valueEditor.focus = function(userAction) { this.editor_.refresh(); if (userAction) { this.editor_.focus(); } }; //////////////////////////////////////////////////////////////////////////////// Code.functionEditor = new Code.GenericEditor('Function'); Code.functionEditor.useJSHint = true; /** * CodeMirror editor. Does not exist until tab is selected. * @type {Object} * @private */ Code.functionEditor.editor_ = null; /** * Return this editor's CodeMirror instance. * @return {Object} Defaults to null. */ Code.functionEditor.getCodeMirror = function() { return this.editor_; }; /** * Create the DOM for this editor. * @param {!Element} container DOM should be appended to this containing div. */ Code.functionEditor.createDom = function(container) { container.innerHTML = `
`; container.id = 'functionEditor'; var options = { continueComments: {continueLineComment: false}, lint: Code.Editor.JSHintReady, mode: 'text/javascript', rulers: [{color: '#ddd', column: 80, lineStyle: 'dashed'}], theme: 'eclipse' }; this.editor_ = Code.Editor.newCodeMirror(container, options); this.isVerbElement_ = document.getElementById('isVerb'); this.verbElement_ = document.getElementById('verb'); this.dobjElement_ = document.getElementById('dobj'); this.prepElement_ = document.getElementById('prep'); this.iobjElement_ = document.getElementById('iobj'); }; // Matches the signature of a function declaration. // Split the source into leading meta-data comments and function body. Code.functionEditor.functionRegex_ = /^((?:[ \t]*(?:\/\/[^\n]*)?\n)*)\s*(function[\S\s]*)$/; /** * Enable or disable the verb UI elements based on the isVerb checkbox. */ Code.functionEditor.updateDisabled = function() { var disabled = this.isVerbElement_.checked ? '' : 'disabled'; this.verbElement_.disabled = disabled; this.dobjElement_.disabled = disabled; this.prepElement_.disabled = disabled; this.iobjElement_.disabled = disabled; }; /** * Get the contents of the editor. * @return {string} Plain text contents. */ Code.functionEditor.getSource = function() { if (!this.created) { return Code.Editor.uncreatedEditorSource; } var source = this.editor_.getValue(); // Trim trailing whitespace. source = source.replace(/[ \t]+(?=\n)/g, '').replace(/[ \t]+$/, ''); var verb = '@delete_prop verb'; var dobj = '@delete_prop dobj'; var prep = '@delete_prop prep'; var iobj = '@delete_prop iobj'; if (this.isVerbElement_.checked) { verb = '@set_prop verb = ' + JSON.stringify(this.verbElement_.value); dobj = '@set_prop dobj = ' + JSON.stringify(this.dobjElement_.value); prep = '@set_prop prep = ' + JSON.stringify(this.prepElement_.value); iobj = '@set_prop iobj = ' + JSON.stringify(this.iobjElement_.value); } return ` ${this.metaExtra_.join('\n').trim()} // ${verb} // ${dobj} // ${prep} // ${iobj} ${source} `.trim(); }; /** * Set the contents of the editor. * @param {string} source Plain text contents. */ Code.functionEditor.setSource = function(source) { var m = source.match(Code.functionEditor.functionRegex_); this.confidence = m ? 0.5 : 0; if (this.created) { this.metaExtra_ = []; var meta; if (m) { meta = m[1].split(/\n/); source = m[2]; } else { meta = ''; source = 'function() {\n}'; } var props = { 'verb': '', 'dobj': 'none', 'prep': 'none', 'iobj': 'none' }; var isVerb = false; for (var line of meta) { var m = line.match(Code.functionEditor.setSource.metaSetRegex_); if (m) { try { props[m[1]] = JSON.parse(m[2]); isVerb = true; } catch (e) { console.log('Ignoring invalid ' + m[1] + ': ' + m[2]); } } else if (!Code.functionEditor.setSource.metaDeleteRegex_.test(line)) { // Not a meta value we recognize. Preserve it. this.metaExtra_.push(line); } } this.verbElement_.value = props['verb']; this.dobjElement_.value = props['dobj']; this.prepElement_.value = props['prep']; this.iobjElement_.value = props['iobj']; this.isVerbElement_.checked = isVerb; this.updateDisabled(); this.editor_.setValue(source); } }; // Matches one meta-data comment: // @set_prop verb = "foobar" Code.functionEditor.setSource.metaSetRegex_ = /^\s*\/\/\s*@set_prop\s+(verb|dobj|prep|iobj)\s*=\s*(.+)$/; // Matches one meta-data comment: // @delete_prop verb Code.functionEditor.setSource.metaDeleteRegex_ = /^\s*\/\/\s*@delete_prop\s+(verb|dobj|prep|iobj)$/; Code.functionEditor.metaExtra_ = []; /** * Notification that this editor has just been displayed. * @param {boolean} userAction True if user clicked on a tab. */ Code.functionEditor.focus = function(userAction) { this.editor_.refresh(); if (userAction) { this.editor_.focus(); } }; //////////////////////////////////////////////////////////////////////////////// Code.jsspEditor = new Code.GenericEditor('JSSP'); /** * JavaScript Server Page editor. Does not exist until tab is selected. * @type {Object} * @private */ Code.jsspEditor.editor_ = null; /** * Return this editor's CodeMirror instance. * @return {Object} Defaults to null. */ Code.jsspEditor.getCodeMirror = function() { return this.editor_; }; /** * Create the DOM for this editor. * @param {!Element} container DOM should be appended to this containing div. */ Code.jsspEditor.createDom = function(container) { container.id = 'jsspEditor'; var options = { continueComments: 'Enter', lint: false, // CodeMirror doesn't understand <% %>. mode: 'application/x-ejs', theme: 'eclipse' }; this.editor_ = Code.Editor.newCodeMirror(container, options); }; /** * Get the contents of the editor. * @return {string} Plain text contents. */ Code.jsspEditor.getSource = function() { if (!this.created) { return Code.Editor.uncreatedEditorSource; } var source = this.editor_.getValue(); return JSON.stringify(source); }; /** * Set the contents of the editor. * @param {string} source Plain text contents. */ Code.jsspEditor.setSource = function(source) { var str; try { str = JSON.parse(source); } catch (e) {} if (typeof str !== 'string') { str = ''; this.confidence = 0; } else { if (str.includes('<%') && str.includes('%>')) { this.confidence = 0.95; } else { this.confidence = 0.8; } } if (this.created) { this.editor_.setValue(str); } }; /** * Notification that this editor has just been displayed. * @param {boolean} userAction True if user clicked on a tab. */ Code.jsspEditor.focus = function(userAction) { this.editor_.refresh(); if (userAction) { this.editor_.focus(); } }; //////////////////////////////////////////////////////////////////////////////// Code.svgEditor = new Code.GenericEditor('SVG'); /** * DOMParser used to determine if the source is SVG. */ Code.svgEditor.parser = new DOMParser(); /** * Create the DOM for this editor. * @param {!Element} container DOM should be appended to this containing div. */ Code.svgEditor.createDom = function(container) { container.innerHTML = `
`; this.frameWindow_ = container.querySelector('iframe').contentWindow; }; /** * Get the contents of the editor. * @return {string} Plain text contents. */ Code.svgEditor.getSource = function() { if (!this.created) { return Code.Editor.uncreatedEditorSource; } var xmlString = this.frameWindow_.hasOwnProperty('initialSource') ? this.frameWindow_.initialSource : this.frameWindow_.svgEditor.getString(); return JSON.stringify(xmlString); }; /** * Set the contents of the editor. * @param {string} text Plain text contents. */ Code.svgEditor.setSource = function(source) { var str = undefined; this.confidence = 0; try { str = JSON.parse(source); } catch (e) {} if (typeof str === 'string') { // DOMParser needs contents wrapped in a parent SVG node. var dom = Code.svgEditor.parser.parseFromString('' + str + '', 'text/xml'); // Let's see if this DOM contains only SVG tags. var nodes = dom.documentElement.querySelectorAll('*'); var isSvg = nodes.length > 0; for (var node of nodes) { if (!Code.svgEditor.ELEMENT_NAMES.has(node.tagName)) { isSvg = false; break; } } if (isSvg) { this.confidence = 0.95; } else { str = ''; } } else { str = ''; } if (this.created) { if (this.frameWindow_.svgEditor) { this.frameWindow_.svgEditor.setString(str); } else { // The iframe exists, but the editor hasn't loaded yet. // Save the source in a property on the iframe, so it can load when ready. this.frameWindow_.initialSource = str; } } }; /** * Notification that this editor has just been displayed. * @param {boolean} userAction True if user clicked on a tab. */ Code.svgEditor.focus = function(userAction) { if (userAction && this.frameWindow_.svgEditor) { // Window may have resized since this tab was last visible. this.frameWindow_.svgEditor.resize(); } }; /** * Whitelist of all allowed SVG element names. * Try to keep this list in sync with CCC.World.xmlToSvg.ELEMENT_NAMES. */ Code.svgEditor.ELEMENT_NAMES = new Set([ 'circle', 'desc', 'ellipse', 'g', 'line', 'path', 'polygon', 'polyline', 'rect', 'svg', 'text', 'title', 'tspan', ]); //////////////////////////////////////////////////////////////////////////////// Code.stringEditor = new Code.GenericEditor('String'); /** * Create the DOM for this editor. * @param {!Element} container DOM should be appended to this containing div. */ Code.stringEditor.createDom = function(container) { container.innerHTML = `
`; this.textarea_ = container.querySelector('textarea'); }; /** * Get the contents of the editor. * @return {string} Plain text contents. */ Code.stringEditor.getSource = function() { return this.created ? JSON.stringify(this.textarea_.value) : Code.Editor.uncreatedEditorSource; }; /** * Set the contents of the editor. * @param {string} text Plain text contents. */ Code.stringEditor.setSource = function(source) { var str; try { str = Code.stringEditor.parseString(source.trim()); this.confidence = 0.9; } catch (e) { str = ''; this.confidence = 0; } if (this.created) { this.textarea_.value = str; } }; /** * Convert a string representation of a string literal to a string. * Basically does eval(s), but safely and only if s is a string * literal. * Copied from $.utils.code.parseString * @param {string} s Candidate string literal. * @retun {string} String value. */ Code.stringEditor.parseString = function(s) { if (!Code.stringEditor.stringExact_.test(s)) { throw new TypeError('Not a string literal'); } return s.slice(1, -1).replace(Code.stringEditor.stringEscapes_, function(esc) { switch (esc[1]) { case "'": case '"': case '/': case '\\': return esc[1]; case '0': return '\0'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; case 'u': case 'x': return String.fromCharCode(parseInt(esc.slice(2), 16)); default: // RegExp in call to replace has accepted something we // don't know how to decode. throw new Error('unknown escape sequence "' + esc + '"??'); } }); }; /** * Tests if a valid string literal. * Copied from $.utils.code.regexps.stringExact */ Code.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}))*")$/; /** * Finds escape sequences in string literals. * Copied from $.utils.code.regexps.escapes */ Code.stringEditor.stringEscapes_ = /\\(?:["'\\\/0bfnrtv]|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g; /** * Notification that this editor has just been displayed. * @param {boolean} userAction True if user clicked on a tab. */ Code.stringEditor.focus = function(userAction) { if (userAction) { this.textarea_.focus(); } }; //////////////////////////////////////////////////////////////////////////////// //Code.regExpEditor = new Code.GenericEditor('RegExp'); //////////////////////////////////////////////////////////////////////////////// //Code.dateEditor = new Code.GenericEditor('Date'); //////////////////////////////////////////////////////////////////////////////// Code.diffEditor = new Code.GenericEditor('Diff'); /** * Create the DOM for this editor. * @param {!Element} container DOM should be appended to this containing div. */ Code.diffEditor.createDom = function(container) { container.innerHTML = `
`; this.frameWindow_ = container.querySelector('iframe').contentWindow; }; /** * Get the contents of the editor. * @return {string} Plain text contents. */ Code.diffEditor.getSource = function() { if (!this.created) { return Code.Editor.uncreatedEditorSource; } if (this.frameWindow_.hasOwnProperty('initialSource')) { return this.frameWindow_.initialSource; } return this.frameWindow_.diffEditor.getString(); }; /** * Set the contents of the editor. * @param {string} source Plain text contents. */ Code.diffEditor.setSource = function(source) { if (this.created) { if (this.frameWindow_.diffEditor) { this.frameWindow_.diffEditor.setString(source, Code.Editor.originalSource); } else { // The iframe exists, but the editor hasn't loaded yet. // Save the source in a property on the iframe, so it can load when ready. this.frameWindow_.initialSource = source; this.frameWindow_.originalSource = Code.Editor.originalSource; } } }; ================================================ FILE: static/code/explorer.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Integrated Development Environment for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; Code.Explorer = {}; /** * Width in pixels of each monospaced character in the input. * Used to line up the autocomplete menu. * TODO: If the menu starts getting out of alignment, measure the text instead. */ Code.Explorer.SIZE_OF_INPUT_CHARS = 8.8; /** * Offset in pixels of start of first character in the input. * Used to line up the autocomplete menu. * TODO: If the menu starts getting out of alignment, measure the text instead. */ Code.Explorer.LEFT_OF_INPUT_CHARS = 6; /** * Value of the input field last time it was processed. * @type {?string} */ Code.Explorer.oldInputValue = null; /** * JSON-encoded list of complete object selector parts. * @type {string} */ Code.Explorer.partsJSON = '[]'; /** * Final token which may not be complete and isn't included in the parts list. * E.g. '$.foo.bar' the 'bar' might become 'bart' or 'barf'. * @type {?Object} */ Code.Explorer.lastNameToken = null; /** * PID of task polling for changes to the input field. */ Code.Explorer.inputPollPid = 0; /** * Is it ok to normalize the input? False if the user is typing. */ Code.Explorer.inputUpdatable = true; /** * The last set of autocompletion options from Code City. * The 'properties' property is an array of arrays of strings. The first array * contains the properties on the object, the second array contains the * properties on the object's prototype, and so on. * The 'keywords' property is an array of strings. E.g. ['{proto}', '{owner}'] * @type {Object} */ Code.Explorer.autocompleteData = null; /** * The type of the autocomplete menu, 'id' or 'keyword'. * @type {string} */ Code.Explorer.autocompleteType = ''; /** * Got a ping from someone. Something might have changed and need updating. */ Code.Explorer.receiveMessage = function() { var selector = sessionStorage.getItem(Code.Common.SELECTOR); // Propagate the ping down the tree of frames. var parts = Code.Common.selectorToParts(selector); if (parts) { if (Code.Explorer.inputUpdatable) { // Valid parts, set the input to be canonical version. Code.Explorer.setInput(parts); } Code.Explorer.loadPanels(parts); } else { // Invalid parts, set the input to the raw string. // Can be caused by going to: /code?$.foo...bar var input = document.getElementById('input'); input.value = selector; Code.Explorer.inputChange(); input.focus(); } }; /** * Handle any changes to the input field. */ Code.Explorer.inputChange = function() { var input = document.getElementById('input'); if (Code.Explorer.oldInputValue === input.value) { return; // No change. } Code.Explorer.oldInputValue = input.value; var parsed = Code.Explorer.parseInput(input.value); if (Code.Explorer.lastNameToken === null && parsed.lastNameToken) { // Look for cases where a deletion has resulted in a valid parts list. // E.g. $.foo.bar. -> $.foo.bar // Without this check, 'bar' would be considered a lastNameToken fragment // and the object panels would back-slide one step to $.foo var partsCopy = parsed.parts.slice(); partsCopy.push( {type: parsed.lastNameToken.type, value: parsed.lastNameToken.value}); var oldParts = JSON.parse(Code.Explorer.partsJSON); if (oldParts) { oldParts.length = partsCopy.length; } if (JSON.stringify(partsCopy) === JSON.stringify(oldParts)) { // Rewrite the parsed input to be complete. parsed = { lastNameToken: null, lastToken: null, parts: partsCopy, valid: true }; } } Code.Explorer.lastNameToken = parsed.lastNameToken; var partsJSON = JSON.stringify(parsed.parts); if (Code.Explorer.partsJSON === partsJSON) { Code.Explorer.updateAutocompleteMenu(); } else { Code.Explorer.hideAutocompleteMenu(); Code.Explorer.setParts(parsed.parts, false); } input.classList.toggle('invalid', !parsed.valid); }; /** * Parse the input value. * @param {string} inputValue Selector string from input field. * @return {!Object} Object with four fields: * parts: Array of selector parts. * lastNameToken: Last token that was an id, str, num, or keyword. * lastToken: Last token. Null if no tokens. * valid: True if all tokens are valid (or could become valid). */ Code.Explorer.parseInput = function(inputValue) { var tokens = Code.Common.tokenizeSelector(inputValue); var parts = []; var token = null; var lastNameToken = null; var valid = true; for (token of tokens) { if (lastNameToken) { parts.push({type: 'id', value: lastNameToken.value}); lastNameToken = null; } if (!token.valid) { valid = false; break; } if (token.type === 'keyword' && token.complete) { parts.push({type: 'keyword', value: token.value}); } else if (['id', 'str', 'num', 'keyword'].includes(token.type)) { lastNameToken = token; } } return { parts: parts, lastNameToken: lastNameToken, lastToken: token, valid: valid }; }; /** * Check to see if there's any autocomplete data, and if so update the menu. */ Code.Explorer.loadAutocomplete = function() { var parts = JSON.parse(Code.Explorer.partsJSON); var selector = Code.Common.partsToSelector(parts); var data = Code.Explorer.getPanelData(selector); if (data) { Code.Explorer.autocompleteData = {}; // Flatten the data into a sorted list of options. var set = new Set(); if (data.properties) { for (var obj of data.properties) { for (var prop of obj) { set.add(prop.name); } } } if (data.roots) { for (var root of data.roots) { set.add(root.name); } } Code.Explorer.autocompleteData.properties = Array.from(set.keys()).sort(Code.Common.caseInsensitiveComp); set.clear(); if (data.keywords) { for (var word of data.keywords) { set.add(word); } } Code.Explorer.autocompleteData.keywords = Array.from(set.keys()).sort(); } else { Code.Explorer.autocompleteData = null; } // If the input value is unchanged, display the autocompletion menu. var input = document.getElementById('input'); if (Code.Explorer.oldInputValue === input.value) { Code.Explorer.updateAutocompleteMenu(); } }; /** * Given a partial prefix, filter the autocompletion menu and display * all matching options. */ Code.Explorer.updateAutocompleteMenu = function() { if (!Code.Explorer.autocompleteData) return; var parsed = Code.Explorer.parseInput(input.value); var token = parsed.lastToken; // If the lastToken is part of the submitted parts, no menu. if (token) { parsed.parts.push({'type': token.type, 'value': token.value}); } if (JSON.stringify(parsed.parts) === Code.Explorer.partsJSON) { Code.Explorer.hideAutocompleteMenu(); return; } // Otherwise, show a menu filtered on the partial token. var options = []; var index = token ? token.index : 0; if (token.type === 'keyword') { var prefix = token.value; // Filter the keywords. for (var option of Code.Explorer.autocompleteData.keywords) { if (option.substring(0, prefix.length).toLowerCase() === prefix) { options.push(option); } } Code.Explorer.autocompleteType = 'keyword'; } else { // Property. var prefix = ''; if (token) { if (token.type === 'id' || token.type === 'str') { prefix = token.value.toLowerCase(); } if ((token.type === 'num') && !isNaN(token.value)) { prefix = String(token.value); } if (token.type === '.' || token.type === '[') { index += token.raw.length; } } if (!token || token.type === '.' || token.type === 'id' || token.type === '[' || token.type === 'str' || token.type === 'num') { // Filter the properties. for (var option of Code.Explorer.autocompleteData.properties) { if (option.substring(0, prefix.length).toLowerCase() === prefix) { options.push(option); } } } Code.Explorer.autocompleteType = 'id'; } if (!options.length || (options.length === 1 && options[0].length === prefix.length)) { // Length equality above is needed since prefix is lowercased. Code.Explorer.hideAutocompleteMenu(); } else { Code.Explorer.showAutocompleteMenu(options, index); } }; /** * Hide any autocompletions if the cursor isn't at the end. * @return {boolean} True if cursor is not at the end. */ Code.Explorer.autocompleteCursorMonitor = function() { var input = document.getElementById('input'); if (typeof input.selectionStart === 'number' && input.selectionStart !== input.value.length) { Code.Explorer.hideAutocompleteMenu(); return true; } return false; }; /** * Display the autocomplete menu, populated with the provided options. * @param {!Array} options Array of options. * @param {number} index Left offset (in characters) to position menu. */ Code.Explorer.showAutocompleteMenu = function(options, index) { if (Code.Explorer.autocompleteCursorMonitor()) { return; } var scrollDiv = document.getElementById('autocompleteMenuScroll'); scrollDiv.innerHTML = ''; for (var option of options) { var div = document.createElement('div'); div.appendChild(document.createTextNode(option)); div.addEventListener('mouseover', Code.Explorer.autocompleteMouseOver); div.addEventListener('mouseout', Code.Explorer.autocompleteMouseOut); div.setAttribute('data-option', option); scrollDiv.appendChild(div); } var menuDiv = document.getElementById('autocompleteMenu'); menuDiv.style.display = 'block'; menuDiv.scrollTop = 0; var left = Math.round(index * Code.Explorer.SIZE_OF_INPUT_CHARS - Code.Explorer.LEFT_OF_INPUT_CHARS); var maxLeft = window.innerWidth - menuDiv.offsetWidth; menuDiv.style.left = Math.min(left, maxLeft) + 'px'; var maxHeight = window.innerHeight - menuDiv.offsetTop - 12; menuDiv.style.maxHeight = maxHeight + 'px'; }; /** * Stop displaying the autocomplete menu. */ Code.Explorer.hideAutocompleteMenu = function() { document.getElementById('autocompleteMenu').style.display = 'none'; Code.Explorer.autocompleteSelect(null); Code.Explorer.autocompleteType = ''; }; /** * Date/time of last keyboard navigation. * Don't allow mouse movements to change the autocompletion selection * Right after a keyboard navigation. Otherwise an arrow keypress could cause * a scroll which could cause an apparent mouse move, which could cause an * unwanted selection change. */ Code.Explorer.keyNavigationTime = 0; /** * Highlight one autocomplete option. * @param {!Event} e Mouse over event. */ Code.Explorer.autocompleteMouseOver = function(e) { if (Date.now() - Code.Explorer.keyNavigationTime > 250) { Code.Explorer.autocompleteSelect(e.target); } }; /** * Remove highlighting from autocomplete option. * @param {!Event} e Mouse out event. */ Code.Explorer.autocompleteMouseOut = function() { if (Date.now() - Code.Explorer.keyNavigationTime > 250) { Code.Explorer.autocompleteSelect(null); } }; /** * Highlight one option. Unhighlight all other options. * @param {?Element} div Option to highlight or null for none. */ Code.Explorer.autocompleteSelect = function(div) { // There should only be zero or one option selected, but deselect them // all in case there was a UI bug. var selections = document.querySelectorAll('#autocompleteMenuScroll>.selected'); for (var selected of selections) { selected.className = ''; } if (div) { div.className = 'selected'; } }; /** * An autocompletion option has been clicked by the user. * @param {!Event} e Click event. */ Code.Explorer.autocompleteClick = function(e) { var option = e.target.getAttribute('data-option'); var parts = JSON.parse(Code.Explorer.partsJSON); parts.push({type: Code.Explorer.autocompleteType, value: option}); Code.Explorer.setParts(parts, true); }; /** * Set the currently specified path. * Notify the parent frame. * @param {!Array} parts List of parts. * @param {boolean} updateInput Normalize the input if true. */ Code.Explorer.setParts = function(parts, updateInput) { Code.Explorer.partsJSON = JSON.stringify(parts); Code.Explorer.inputUpdatable = updateInput; Code.Explorer.hideAutocompleteMenu(); Code.Explorer.loadAutocomplete(); var selector = Code.Common.partsToSelector(parts); sessionStorage.setItem(Code.Common.SELECTOR, selector); window.parent.postMessage('ping', '*'); }; /** * Set the input to be the specified path. * @param {!Array} parts List of parts. */ Code.Explorer.setInput = function(parts) { Code.Explorer.hideAutocompleteMenu(); var value = Code.Common.partsToSelector(parts); var input = document.getElementById('input'); input.value = value; input.classList.remove('invalid'); input.focus(); Code.Explorer.oldInputValue = value; // Don't autocomplete this value. }; /** * Start polling for changes. */ Code.Explorer.inputFocus = function() { clearInterval(Code.Explorer.inputPollPid); Code.Explorer.inputPollPid = setInterval(Code.Explorer.inputChange, 10); Code.Explorer.inputUpdatable = false; }; /** * Stop polling for changes and hide the autocomplete menu. */ Code.Explorer.inputBlur = function() { if (Code.Explorer.inputBlur.disable_) { Code.Explorer.inputBlur.disable_ = false; return; } clearInterval(Code.Explorer.inputPollPid); Code.Explorer.hideAutocompleteMenu(); Code.Explorer.inputUpdatable = true; }; Code.Explorer.inputBlur.disable_ = false; /** * When clicking on the autocomplete menu, disable the blur * (which would otherwise close the menu). */ Code.Explorer.autocompleteMouseDown = function() { Code.Explorer.inputBlur.disable_ = true; }; /** * Intercept some control keys to control the autocomplete menu. * @param {!Event} e Keypress event. */ Code.Explorer.inputKey = function(e) { var key = { TAB: 9, ENTER: 13, ESC: 27, UP: 38, DOWN: 40 }; if (e.keyCode === key.ESC) { Code.Explorer.hideAutocompleteMenu(); } Code.Explorer.autocompleteCursorMonitor(); var scrollDiv = document.getElementById('autocompleteMenuScroll'); var selected = scrollDiv.querySelector('.selected'); var menuDiv = document.getElementById('autocompleteMenu'); var hasMenu = menuDiv.style.display !== 'none'; if (e.keyCode === key.ENTER) { var parts = JSON.parse(Code.Explorer.partsJSON); if (selected) { // Add the selected autocomplete option to the input. var option = selected.getAttribute('data-option'); parts.push({type: Code.Explorer.autocompleteType, value: option}); } else if (Code.Explorer.lastNameToken && Code.Explorer.lastNameToken.valid) { // The currently typed input should be considered complete. // E.g. $.foo is not waiting to become $.foot parts.push({type: 'id', value: Code.Explorer.lastNameToken.value}); Code.Explorer.lastNameToken = null; } Code.Explorer.setParts(parts, true); e.preventDefault(); } if (e.keyCode === key.TAB) { if (hasMenu) { // Extract all options from the menu. var options = []; for (var i = 0, option; (option = scrollDiv.childNodes[i]); i++) { options[i] = option.getAttribute('data-option'); } var prefix = ''; if (Code.Explorer.lastNameToken && Code.Explorer.lastNameToken.type === 'id') { prefix = Code.Explorer.lastNameToken.value; } var tuple = Code.Explorer.autocompletePrefix(options, prefix); if (tuple.terminal) { // There was only one option. Choose it. var parts = JSON.parse(Code.Explorer.partsJSON); parts.push({type: Code.Explorer.autocompleteType, value: tuple.prefix}); Code.Explorer.setParts(parts, true); } else { // Append the common prefix to the existing input. var input = document.getElementById('input'); if (Code.Explorer.lastNameToken) { input.value = input.value.substring(0, Code.Explorer.lastNameToken.index) + tuple.prefix; } else { input.value += tuple.prefix; } // TODO: Tab-completion of partial strings and numbers. } } e.preventDefault(); } if (hasMenu && (e.keyCode === key.UP || e.keyCode === key.DOWN)) { Code.Explorer.keyNavigationTime = Date.now(); var newSelected; if (e.keyCode === key.UP) { if (!selected) { newSelected = scrollDiv.lastChild; } else if (selected.previousSibling) { newSelected = selected.previousSibling; } } else if (e.keyCode === key.DOWN) { if (!selected) { newSelected = scrollDiv.firstChild; } else if (selected.nextSibling) { newSelected = selected.nextSibling; } } if (newSelected) { Code.Explorer.autocompleteSelect(newSelected); if (newSelected.scrollIntoView) { newSelected.scrollIntoView({block: 'nearest', inline: 'nearest'}); } } e.preventDefault(); } }; /** * Given a list of options, and an existing prefix, return the common prefix. * E.g. (['food', 'foot'], 'f') -> {prefix: 'foo', terminal: false} * @param {!Array} options Array of autocompleted strings. * @param {string} prefix Any existing prefix. * @return {{prefix: string, terminal: boolean}} Tuple with the maximum common * prefix, and whether this completion is terminal (true), or if there's the * option of continuing (false). */ Code.Explorer.autocompletePrefix = function(options, prefix) { // Filter out only those completions that case-sensitively match the prefix. var optionsCase = options.filter( function(option) {return option.startsWith(prefix);}); if (optionsCase.length) { return {prefix: Code.Explorer.getPrefix(optionsCase), terminal: optionsCase.length === 1}; } // Find completions that don't match the prefix's case. var common = Code.Explorer.getPrefix(options); if (common.length > prefix.length) { var optionsCommon = options.filter( function(option) {return option.startsWith(common);}); return {prefix: common, terminal: optionsCommon.length === 1}; } return {prefix: prefix, terminal: false}; }; /** * Compute and return the common prefix of n (relatively short) strings. * @param {!Array} strs Array of string. * @return {string} Common prefix. */ Code.Explorer.getPrefix = function(strs) { if (strs.length === 0) { return ''; } var i = 0; while (true) { var letter = strs[0][i]; for (var j = 0; j < strs.length; j++) { if (strs[j].length <= i) { return strs[j]; } if (strs[j][i] !== letter) { return strs[j].substring(0, i); } } i++; } }; /** * If a mouse-click caused the cursor to move away from the end, * close the autocomplete menu. */ Code.Explorer.inputMouseDown = function() { setTimeout(Code.Explorer.autocompleteCursorMonitor, 1); }; /** * Number of object panels. */ Code.Explorer.panelCount = 0; /** * Size of temporary spacer margin for smooth scrolling after deletion. */ Code.Explorer.panelSpacerMargin = 0; /** * Update the panels with the specified list of parts. * @param {!Array} parts List of parts. */ Code.Explorer.loadPanels = function(parts) { for (var i = 0; i <= parts.length; i++) { var selector = Code.Common.partsToSelector(parts.slice(0, i)); var iframe = document.getElementById('objectPanel' + i); if (iframe) { if (iframe.getAttribute('data-selector') === selector) { // Highlight current item. iframe.contentWindow.postMessage('ping', '*'); continue; } else { while (Code.Explorer.panelCount > i) { Code.Explorer.removePanel(); } } } iframe = Code.Explorer.addPanel(selector); } while (Code.Explorer.panelCount > i) { Code.Explorer.removePanel(); } }; /** * Add an object panel to the right. * @param {string} selector Selector string. */ Code.Explorer.addPanel = function(selector) { var panelsScroll = document.getElementById('panelsScroll'); var iframe = document.createElement('iframe'); iframe.addEventListener('load', Code.Explorer.loadAutocomplete); iframe.id = 'objectPanel' + Code.Explorer.panelCount; iframe.src = 'objectPanel?' + encodeURIComponent(selector); iframe.setAttribute('data-selector', selector); var spacer = document.getElementById('panelSpacer'); panelsScroll.insertBefore(iframe, spacer); Code.Explorer.panelCount++; Code.Explorer.panelSpacerMargin = Math.max(0, Code.Explorer.panelSpacerMargin - iframe.offsetWidth); Code.Explorer.scrollPanel(); }; /** * Remove the right-most panel. */ Code.Explorer.removePanel = function() { Code.Explorer.panelCount--; var iframe = document.getElementById('objectPanel' + Code.Explorer.panelCount); Code.Explorer.panelSpacerMargin += iframe.offsetWidth; iframe.parentNode.removeChild(iframe); Code.Explorer.scrollPanel(); }; /** * After addition, quickly scroll the panels all the way to see the right edge. * After deletion, reduce the spacer so that the panels scroll to the edge. */ Code.Explorer.scrollPanel = function() { var spacer = document.getElementById('panelSpacer'); var speed = 20; clearTimeout(Code.Explorer.scrollPid_); if (Code.Explorer.panelSpacerMargin > 0) { // Reduce spacer. Code.Explorer.panelSpacerMargin = Math.max(0, Code.Explorer.panelSpacerMargin - speed); spacer.style.marginRight = Code.Explorer.panelSpacerMargin + 'px'; if (Code.Explorer.panelSpacerMargin > 0) { Code.Explorer.scrollPid_ = setTimeout(Code.Explorer.scrollPanel, 10); } } else { spacer.style.marginRight = 0; // Scroll right. var panels = document.getElementById('panels'); var oldScroll = panels.scrollLeft; panels.scrollLeft += speed; if (panels.scrollLeft > oldScroll) { Code.Explorer.scrollPid_ = setTimeout(Code.Explorer.scrollPanel, 10); } } }; /** * PID of currently executing scroll animation. * @private */ Code.Explorer.scrollPid_ = 0; /** * Get the data blob from the specified object panel. * @param {string} selector Selector string. * @return {!Object|undefined} Data blob, or undefined if data is not * currently available. */ Code.Explorer.getPanelData = function(selector) { // Find the object panel that contains the needed data. for (var iframe of document.getElementsByTagName('iframe')) { if (iframe.getAttribute('data-selector') === selector) { try { // Risky: Content may not have loaded yet. var data = iframe.contentWindow.Code.ObjectPanel.data; } catch (e) {} break; } } return data; }; /** * Keydown handler for the explorer frame. * @param {!KeyboardEvent} e Keydown event. */ Code.Explorer.keyDown = function(e) { // The editor frame may have strong opinions about key presses. try { parent.frames[1].Code.Editor.keyDown(e); } catch (ex) { // Frame might not be loaded yet. } }; /** * Page has loaded, initialize the explorer. */ Code.Explorer.init = function() { var input = document.getElementById('input'); input.addEventListener('focus', Code.Explorer.inputFocus); input.addEventListener('blur', Code.Explorer.inputBlur); input.addEventListener('keydown', Code.Explorer.inputKey); input.addEventListener('mousedown', Code.Explorer.inputMouseDown); document.addEventListener('keydown', Code.Explorer.keyDown); var scrollDiv = document.getElementById('autocompleteMenuScroll'); scrollDiv.addEventListener('mousedown', Code.Explorer.autocompleteMouseDown); scrollDiv.addEventListener('click', Code.Explorer.autocompleteClick); Code.Explorer.receiveMessage(); }; if (!window.TEST) { window.addEventListener('load', Code.Explorer.init); window.addEventListener('message', Code.Explorer.receiveMessage, false); } ================================================ FILE: static/code/mobwrite/demo/editor.html ================================================ MobWrite as a Collaborative Editor

MobWrite as a Collaborative Editor

================================================ FILE: static/code/mobwrite/demo/form.html ================================================ MobWrite as a Collaborative Form

MobWrite as a Collaborative Form

What
When to
Where


Who
Hidden [get/set]
Password
Description
================================================ FILE: static/code/mobwrite/demo/mobwrite_form.js ================================================ /** * @license * Copyright 2008 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview This client-side code interfaces with form elements. * @author fraser@google.com (Neil Fraser) */ /** * Checks to see if the provided node is still part of the DOM. * @param {Node} node DOM node to verify. * @return {boolean} Is this node part of a DOM? * @private */ mobwrite.validNode_ = function(node) { while (node.parentNode) { node = node.parentNode; } // The topmost node should be type 9, a document. return node.nodeType == 9; }; // FORM /** * Handler to accept forms as elements that can be shared. * Share each of the form's elements. * @param {Object|string} form Form or ID of form to share * @return {Object?} A sharing object or null. */ mobwrite.shareHandlerForm = function(form) { if (typeof form == 'string') { form = document.getElementById(form) || document.forms[form]; } if (form && 'tagName' in form && form.tagName == 'FORM') { for (var x = 0, el; el = form.elements[x]; x++) { mobwrite.share(el); } } return null; }; // Register this shareHandler with MobWrite. mobwrite.shareHandlers.push(mobwrite.shareHandlerForm); // HIDDEN /** * Constructor of shared object representing a hidden input. * @param {Node} node A hidden element. * @constructor */ mobwrite.shareHiddenObj = function(node) { // Call our prototype's constructor. mobwrite.shareObj.apply(this, [node.id]); this.element = node; }; // The hidden input's shared object's parent is a shareObj. mobwrite.shareHiddenObj.prototype = new mobwrite.shareObj(''); /** * Retrieve the user's content. * @return {string} Plaintext content. */ mobwrite.shareHiddenObj.prototype.getClientText = function() { if (!mobwrite.validNode_(this.element)) { mobwrite.unshare(this.file); } // Numeric data should use overwrite mode. this.mergeChanges = !this.element.value.match(/^\s*-?[\d.]+\s*$/); return this.element.value; }; /** * Set the user's content. * @param {string} text New content. */ mobwrite.shareHiddenObj.prototype.setClientText = function(text) { this.element.value = text; }; /** * Handler to accept hidden fields as elements that can be shared. * If the element is a hidden field, create a new sharing object. * @param {*} node Object or ID of object to share. * @return {Object?} A sharing object or null. */ mobwrite.shareHiddenObj.shareHandler = function(node) { if (typeof node == 'string') { node = document.getElementById(node); } if (node && 'type' in node && node.type == 'hidden') { return new mobwrite.shareHiddenObj(node); } return null; }; // Register this shareHandler with MobWrite. mobwrite.shareHandlers.push(mobwrite.shareHiddenObj.shareHandler); // CHECKBOX /** * Constructor of shared object representing a checkbox. * @param {Node} node A checkbox element. * @constructor */ mobwrite.shareCheckboxObj = function(node) { // Call our prototype's constructor. mobwrite.shareObj.apply(this, [node.id]); this.element = node; this.mergeChanges = false; }; // The checkbox shared object's parent is a shareObj. mobwrite.shareCheckboxObj.prototype = new mobwrite.shareObj(''); /** * Retrieve the user's check. * @return {string} Plaintext content. */ mobwrite.shareCheckboxObj.prototype.getClientText = function() { if (!mobwrite.validNode_(this.element)) { mobwrite.unshare(this.file); } return this.element.checked ? this.element.value : ''; }; /** * Set the user's check. * @param {string} text New content. */ mobwrite.shareCheckboxObj.prototype.setClientText = function(text) { // Safari has a blank value if not set, all other browsers have 'on'. var value = this.element.value || 'on'; this.element.checked = (text == value); this.fireChange(this.element); }; /** * Handler to accept checkboxen as elements that can be shared. * If the element is a checkbox, create a new sharing object. * @param {*} node Object or ID of object to share. * @return {Object?} A sharing object or null. */ mobwrite.shareCheckboxObj.shareHandler = function(node) { if (typeof node == 'string') { node = document.getElementById(node); } if (node && 'type' in node && node.type == 'checkbox') { return new mobwrite.shareCheckboxObj(node); } return null; }; // Register this shareHandler with MobWrite. mobwrite.shareHandlers.push(mobwrite.shareCheckboxObj.shareHandler); // SELECT OPTION /** * Constructor of shared object representing a select box. * @param {Node} node A select box element. * @constructor */ mobwrite.shareSelectObj = function(node) { // Call our prototype's constructor. mobwrite.shareObj.apply(this, [node.id]); this.element = node; // If the select box is select-one, use overwrite mode. // If it is select-multiple, use text merge mode. this.mergeChanges = (node.type == 'select-multiple'); }; // The select box shared object's parent is a shareObj. mobwrite.shareSelectObj.prototype = new mobwrite.shareObj(''); /** * Retrieve the user's selection(s). * @return {string} Plaintext content. */ mobwrite.shareSelectObj.prototype.getClientText = function() { if (!mobwrite.validNode_(this.element)) { mobwrite.unshare(this.file); } var selected = []; for (var x = 0, option; option = this.element.options[x]; x++) { if (option.selected) { selected.push(option.value); } } return selected.join('\0'); }; /** * Set the user's selection(s). * @param {string} text New content. */ mobwrite.shareSelectObj.prototype.setClientText = function(text) { text = '\0' + text + '\0'; for (var x = 0, option; option = this.element.options[x]; x++) { option.selected = (text.indexOf('\0' + option.value + '\0') != -1); } this.fireChange(this.element); }; /** * Handler to accept select boxen as elements that can be shared. * If the element is a select box, create a new sharing object. * @param {*} node Object or ID of object to share * @return {Object?} A sharing object or null. */ mobwrite.shareSelectObj.shareHandler = function(node) { if (typeof node == 'string') { node = document.getElementById(node); } if (node && 'type' in node && (node.type == 'select-one' || node.type == 'select-multiple')) { return new mobwrite.shareSelectObj(node); } return null; }; // Register this shareHandler with MobWrite. mobwrite.shareHandlers.push(mobwrite.shareSelectObj.shareHandler); // RADIO BUTTON /** * Constructor of shared object representing a radio button. * @param {Node} node A radio button element. * @constructor */ mobwrite.shareRadioObj = function(node) { // Call our prototype's constructor. mobwrite.shareObj.apply(this, [node.id]); this.elements = [node]; this.form = node.form; this.name = node.name; this.mergeChanges = false; }; // The radio button shared object's parent is a shareObj. mobwrite.shareRadioObj.prototype = new mobwrite.shareObj(''); /** * Retrieve the user's check. * @return {string} Plaintext content. */ mobwrite.shareRadioObj.prototype.getClientText = function() { // TODO: Handle cases where the radio buttons are added or removed. if (!mobwrite.validNode_(this.elements[0])) { mobwrite.unshare(this.file); } // Group of radio buttons for (var x = 0; x < this.elements.length; x++) { if (this.elements[x].checked) { return this.elements[x].value; } } // Nothing checked. return ''; }; /** * Set the user's check. * @param {string} text New content. */ mobwrite.shareRadioObj.prototype.setClientText = function(text) { for (var x = 0; x < this.elements.length; x++) { this.elements[x].checked = (text == this.elements[x].value); this.fireChange(this.elements[x]); } }; /** * Handler to accept radio buttons as elements that can be shared. * If the element is a radio button, create a new sharing object. * @param {*} node Object or ID of object to share. * @return {Object?} A sharing object or null. */ mobwrite.shareRadioObj.shareHandler = function(node) { if (typeof node == 'string') { node = document.getElementById(node); } if (node && 'type' in node && node.type == 'radio') { // Check to see if this is another element of an existing radio button group. for (var id in mobwrite.shared) { if (mobwrite.shared[id].form == node.form && mobwrite.shared[id].name == node.name) { mobwrite.shared[id].elements.push(node); return null; } } // Create new radio button object. return new mobwrite.shareRadioObj(node); } return null; }; // Register this shareHandler with MobWrite. mobwrite.shareHandlers.push(mobwrite.shareRadioObj.shareHandler); // TEXTAREA, TEXT & PASSWORD INPUTS /** * Constructor of shared object representing a text field. * @param {Node} node A textarea, text or password input. * @constructor */ mobwrite.shareTextareaObj = function(node) { // Call our prototype's constructor. mobwrite.shareObj.apply(this, [node.id]); this.element = node; if (node.type == 'password') { // Use overwrite mode for password field, users can't see. this.mergeChanges = false; } }; // The textarea shared object's parent is a shareObj. mobwrite.shareTextareaObj.prototype = new mobwrite.shareObj(''); /** * Retrieve the user's text. * @return {string} Plaintext content. */ mobwrite.shareTextareaObj.prototype.getClientText = function() { if (!mobwrite.validNode_(this.element)) { mobwrite.unshare(this.file); } var text = mobwrite.shareTextareaObj.normalizeLinebreaks_(this.element.value); if (this.element.type == 'text') { // Numeric data should use overwrite mode. this.mergeChanges = !text.match(/^\s*-?[\d.,]+\s*$/); } return text; }; /** * Set the user's text. * @param {string} text New text */ mobwrite.shareTextareaObj.prototype.setClientText = function(text) { this.element.value = text; this.fireChange(this.element); }; /** * Modify the user's plaintext by applying a series of patches against it. * @param {Array.} patches Array of Patch objects. */ mobwrite.shareTextareaObj.prototype.patchClientText = function(patches) { // Set some constants which tweak the matching behaviour. // Maximum distance to search from expected location. this.dmp.Match_Distance = 1000; // At what point is no match declared (0.0 = perfection, 1.0 = very loose) this.dmp.Match_Threshold = 0.6; var oldClientText = this.getClientText(); var cursor = this.captureCursor_(); // Pack the cursor offsets into an array to be adjusted. // See http://neil.fraser.name/writing/cursor/ var offsets = []; if (cursor) { offsets[0] = cursor.startOffset; if ('endOffset' in cursor) { offsets[1] = cursor.endOffset; } } var newClientText = this.patch_apply_(patches, oldClientText, offsets); // Set the new text only if there is a change to be made. if (oldClientText != newClientText) { this.setClientText(newClientText); if (cursor) { // Unpack the offset array. cursor.startOffset = offsets[0]; if (offsets.length > 1) { cursor.endOffset = offsets[1]; if (cursor.startOffset >= cursor.endOffset) { cursor.collapsed = true; } } this.restoreCursor_(cursor); } } }; /** * Merge a set of patches onto the text. Return a patched text. * @param {Array.} patches Array of patch objects. * @param {string} text Old text. * @param {Array.} offsets Offset indices to adjust. * @return {string} New text. */ mobwrite.shareTextareaObj.prototype.patch_apply_ = function(patches, text, offsets) { if (patches.length == 0) { return text; } // Deep copy the patches so that no changes are made to originals. patches = this.dmp.patch_deepCopy(patches); var nullPadding = this.dmp.patch_addPadding(patches); text = nullPadding + text + nullPadding; this.dmp.patch_splitMax(patches); // delta keeps track of the offset between the expected and actual location // of the previous patch. If there are patches expected at positions 10 and // 20, but the first patch was found at 12, delta is 2 and the second patch // has an effective expected position of 22. var delta = 0; for (var x = 0; x < patches.length; x++) { var expected_loc = patches[x].start2 + delta; var text1 = this.dmp.diff_text1(patches[x].diffs); var start_loc; var end_loc = -1; if (text1.length > this.dmp.Match_MaxBits) { // patch_splitMax will only provide an oversized pattern in the case of // a monster delete. start_loc = this.dmp.match_main(text, text1.substring(0, this.dmp.Match_MaxBits), expected_loc); if (start_loc != -1) { end_loc = this.dmp.match_main(text, text1.substring(text1.length - this.dmp.Match_MaxBits), expected_loc + text1.length - this.dmp.Match_MaxBits); if (end_loc == -1 || start_loc >= end_loc) { // Can't find valid trailing context. Drop this patch. start_loc = -1; } } } else { start_loc = this.dmp.match_main(text, text1, expected_loc); } if (start_loc == -1) { // No match found. :( if (mobwrite.debug) { window.console.warn('Patch failed: ' + patches[x]); } // Subtract the delta for this failed patch from subsequent patches. delta -= patches[x].length2 - patches[x].length1; } else { // Found a match. :) if (mobwrite.debug) { window.console.info('Patch OK.'); } delta = start_loc - expected_loc; var text2; if (end_loc == -1) { text2 = text.substring(start_loc, start_loc + text1.length); } else { text2 = text.substring(start_loc, end_loc + this.dmp.Match_MaxBits); } // Run a diff to get a framework of equivalent indices. var diffs = this.dmp.diff_main(text1, text2, false); if (text1.length > this.dmp.Match_MaxBits && this.dmp.diff_levenshtein(diffs) / text1.length > this.dmp.Patch_DeleteThreshold) { // The end points match, but the content is unacceptably bad. if (mobwrite.debug) { window.console.warn('Patch contents mismatch: ' + patches[x]); } } else { var index1 = 0; var index2; for (var y = 0; y < patches[x].diffs.length; y++) { var mod = patches[x].diffs[y]; if (mod[0] !== DIFF_EQUAL) { index2 = this.dmp.diff_xIndex(diffs, index1); } if (mod[0] === DIFF_INSERT) { // Insertion text = text.substring(0, start_loc + index2) + mod[1] + text.substring(start_loc + index2); for (var i = 0; i < offsets.length; i++) { if (offsets[i] + nullPadding.length > start_loc + index2) { offsets[i] += mod[1].length; } } } else if (mod[0] === DIFF_DELETE) { // Deletion var del_start = start_loc + index2; var del_end = start_loc + this.dmp.diff_xIndex(diffs, index1 + mod[1].length); text = text.substring(0, del_start) + text.substring(del_end); for (var i = 0; i < offsets.length; i++) { if (offsets[i] + nullPadding.length > del_start) { if (offsets[i] + nullPadding.length < del_end) { offsets[i] = del_start - nullPadding.length; } else { offsets[i] -= del_end - del_start; } } } } if (mod[0] !== DIFF_DELETE) { index1 += mod[1].length; } } } } } // Strip the padding off. text = text.substring(nullPadding.length, text.length - nullPadding.length); return text; }; /** * Record information regarding the current cursor. * @return {Object?} Context information of the cursor. * @private */ mobwrite.shareTextareaObj.prototype.captureCursor_ = function() { if ('activeElement' in this.element && !this.element.activeElement) { // Safari specific code. // Restoring a cursor in an unfocused element causes the focus to jump. return null; } var padLength = this.dmp.Match_MaxBits / 2; // Normally 16. var text = this.element.value; var cursor = {}; if ('selectionStart' in this.element) { // W3 try { var selectionStart = this.element.selectionStart; var selectionEnd = this.element.selectionEnd; } catch (e) { // No cursor; the element may be "display:none". return null; } cursor.startPrefix = text.substring(selectionStart - padLength, selectionStart); cursor.startSuffix = text.substring(selectionStart, selectionStart + padLength); cursor.startOffset = selectionStart; cursor.collapsed = (selectionStart == selectionEnd); if (!cursor.collapsed) { cursor.endPrefix = text.substring(selectionEnd - padLength, selectionEnd); cursor.endSuffix = text.substring(selectionEnd, selectionEnd + padLength); cursor.endOffset = selectionEnd; } } else { // IE // Walk up the tree looking for this textarea's document node. var doc = this.element; while (doc.parentNode) { doc = doc.parentNode; } if (!doc.selection || !doc.selection.createRange) { // Not IE? return null; } var range = doc.selection.createRange(); if (range.parentElement() != this.element) { // Cursor not in this textarea. return null; } var newRange = doc.body.createTextRange(); cursor.collapsed = (range.text == ''); newRange.moveToElementText(this.element); if (!cursor.collapsed) { newRange.setEndPoint('EndToEnd', range); cursor.endPrefix = newRange.text; cursor.endOffset = cursor.endPrefix.length; cursor.endPrefix = cursor.endPrefix.substring(cursor.endPrefix.length - padLength); } newRange.setEndPoint('EndToStart', range); cursor.startPrefix = newRange.text; cursor.startOffset = cursor.startPrefix.length; cursor.startPrefix = cursor.startPrefix.substring(cursor.startPrefix.length - padLength); newRange.moveToElementText(this.element); newRange.setEndPoint('StartToStart', range); cursor.startSuffix = newRange.text.substring(0, padLength); if (!cursor.collapsed) { newRange.setEndPoint('StartToEnd', range); cursor.endSuffix = newRange.text.substring(0, padLength); } } // Record scrollbar locations if ('scrollTop' in this.element) { cursor.scrollTop = this.element.scrollTop / this.element.scrollHeight; cursor.scrollLeft = this.element.scrollLeft / this.element.scrollWidth; } // alert(cursor.startPrefix + '|' + cursor.startSuffix + ' ' + // cursor.startOffset + '\n' + cursor.endPrefix + '|' + // cursor.endSuffix + ' ' + cursor.endOffset + '\n' + // cursor.scrollTop + ' x ' + cursor.scrollLeft); return cursor; }; /** * Attempt to restore the cursor's location. * @param {Object} cursor Context information of the cursor. * @private */ mobwrite.shareTextareaObj.prototype.restoreCursor_ = function(cursor) { // Set some constants which tweak the matching behaviour. // Maximum distance to search from expected location. this.dmp.Match_Distance = 1000; // At what point is no match declared (0.0 = perfection, 1.0 = very loose) this.dmp.Match_Threshold = 0.9; var padLength = this.dmp.Match_MaxBits / 2; // Normally 16. var newText = this.element.value; // Find the start of the selection in the new text. var pattern1 = cursor.startPrefix + cursor.startSuffix; var pattern2, diff; var cursorStartPoint = this.dmp.match_main(newText, pattern1, cursor.startOffset - padLength); if (cursorStartPoint !== null) { pattern2 = newText.substring(cursorStartPoint, cursorStartPoint + pattern1.length); //alert(pattern1 + '\nvs\n' + pattern2); // Run a diff to get a framework of equivalent indicies. diff = this.dmp.diff_main(pattern1, pattern2, false); cursorStartPoint += this.dmp.diff_xIndex(diff, cursor.startPrefix.length); } var cursorEndPoint = null; if (!cursor.collapsed) { // Find the end of the selection in the new text. pattern1 = cursor.endPrefix + cursor.endSuffix; cursorEndPoint = this.dmp.match_main(newText, pattern1, cursor.endOffset - padLength); if (cursorEndPoint !== null) { pattern2 = newText.substring(cursorEndPoint, cursorEndPoint + pattern1.length); //alert(pattern1 + '\nvs\n' + pattern2); // Run a diff to get a framework of equivalent indicies. diff = this.dmp.diff_main(pattern1, pattern2, false); cursorEndPoint += this.dmp.diff_xIndex(diff, cursor.endPrefix.length); } } // Deal with loose ends if (cursorStartPoint === null && cursorEndPoint !== null) { // Lost the start point of the selection, but we have the end point. // Collapse to end point. cursorStartPoint = cursorEndPoint; } else if (cursorStartPoint === null && cursorEndPoint === null) { // Lost both start and end points. // Jump to the offset of start. cursorStartPoint = cursor.startOffset; } if (cursorEndPoint === null) { // End not known, collapse to start. cursorEndPoint = cursorStartPoint; } // Restore selection. if ('selectionStart' in this.element) { // W3 this.element.selectionStart = cursorStartPoint; this.element.selectionEnd = cursorEndPoint; } else { // IE // Walk up the tree looking for this textarea's document node. var doc = this.element; while (doc.parentNode) { doc = doc.parentNode; } if (!doc.selection || !doc.selection.createRange) { // Not IE? return; } // IE's TextRange.move functions treat '\r\n' as one character. var snippet = this.element.value.substring(0, cursorStartPoint); var ieStartPoint = snippet.replace(/\r\n/g, '\n').length; var newRange = doc.body.createTextRange(); newRange.moveToElementText(this.element); newRange.collapse(true); newRange.moveStart('character', ieStartPoint); if (!cursor.collapsed) { snippet = this.element.value.substring(cursorStartPoint, cursorEndPoint); var ieMidLength = snippet.replace(/\r\n/g, '\n').length; newRange.moveEnd('character', ieMidLength); } newRange.select(); } // Restore scrollbar locations if ('scrollTop' in cursor) { this.element.scrollTop = cursor.scrollTop * this.element.scrollHeight; this.element.scrollLeft = cursor.scrollLeft * this.element.scrollWidth; } }; /** * Ensure that all linebreaks are LF * @param {string} text Text with unknown line breaks * @return {string} Text with normalized linebreaks * @private */ mobwrite.shareTextareaObj.normalizeLinebreaks_ = function(text) { return text.replace(/\r\n/g, '\n').replace(/\r/g, '\n'); }; /** * Handler to accept text fields as elements that can be shared. * If the element is a textarea, text or password input, create a new * sharing object. * @param {*} node Object or ID of object to share. * @return {Object?} A sharing object or null. */ mobwrite.shareTextareaObj.shareHandler = function(node) { if (typeof node == 'string') { node = document.getElementById(node); } if (node && 'value' in node && 'type' in node && (node.type == 'textarea' || node.type == 'text' || node.type == 'password')) { if (mobwrite.UA_webkit) { // Safari needs to track which text element has the focus. node.addEventListener('focus', function() {this.activeElement = true;}, false); node.addEventListener('blur', function() {this.activeElement = false;}, false); node.activeElement = false; } return new mobwrite.shareTextareaObj(node); } return null; }; // Register this shareHandler with MobWrite. mobwrite.shareHandlers.push(mobwrite.shareTextareaObj.shareHandler); ================================================ FILE: static/code/mobwrite/demo/test.html ================================================ Manual test of MobWrite's client-server Protocol

Manual test of MobWrite's client-server Protocol

================================================ FILE: static/code/mobwrite/mobwrite_cc.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Realtime collaboration for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; /** * Constructor of sharing object representing the code editor. * @constructor */ Code.MobwriteShare = function() { // Call our prototype's constructor. mobwrite.shareObj.call(this, Code.MobwriteShare.id); }; /** * Handler to accept the code editor as an element that can be shared. * @param {string} type Type of object to share * ('Code' is currently the only option). * @return {Object?} A sharing object or null. */ Code.MobwriteShare.shareHandler = function(type) { if (type === 'Code') { return new Code.MobwriteShare(); } return null; }; /** * Initialization that happens once DMP, MobWrite, and this file are all loaded. * Called by Code.Editor.waitMobWrite_ */ Code.MobwriteShare.init = function() { // Fetch the sharing ID from the parent frame's URL, or invent a new one. var hash = parent && parent.location && parent.location.hash; if (hash) { hash = hash.substring(1); } Code.MobwriteShare.id = hash || mobwrite.uniqueId(); // The sharing object's parent is a shareObj. Code.MobwriteShare.prototype = new mobwrite.shareObj(); /** * Retrieve the user's content. * @return {string} Plaintext content. */ Code.MobwriteShare.prototype.getClientText = function() { var value = ''; if (Code.Editor.currentEditor) { value = Code.Editor.currentEditor.getSource() || ''; } // Numeric data should use overwrite mode. this.mergeChanges = !value.match(/^\s*-?[\d.]+\s*$/); return value; }; /** * Set the user's content. * @param {string} text New content. */ Code.MobwriteShare.prototype.setClientText = function(text) { Code.Editor.setSourceToAllEditors(text, false); }; // Register this shareHandler with MobWrite. mobwrite.shareHandlers.push(Code.MobwriteShare.shareHandler); // Default max is 10 seconds. Decrease to 5. mobwrite.maxSyncInterval = 5000; }; ================================================ FILE: static/code/mobwrite/mobwrite_core.js ================================================ /** * @license * Copyright 2006 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview This client-side code drives the synchronisation. * @author fraser@google.com (Neil Fraser) */ /** * Namespace containing all MobWrite code. */ var mobwrite = {}; /** * URL of Ajax gateway. * @type {string} */ mobwrite.syncGateway = '/scripts/q.py'; /** * Print diagnostic messages to the browser's console. * @type {boolean} */ mobwrite.debug = true; /** * PID of task which will trigger next Ajax request. * @type {number?} * @private */ mobwrite.syncRunPid_ = null; /** * PID of task which will kill stalled Ajax request. * @type {number?} * @private */ mobwrite.syncKillPid_ = null; /** * Time to wait for a connection before giving up and retrying. * @type {number} */ mobwrite.timeoutInterval = 30000; /** * Shortest interval (in milliseconds) between connections. * @type {number} */ mobwrite.minSyncInterval = 1000; /** * Longest interval (in milliseconds) between connections. * @type {number} */ mobwrite.maxSyncInterval = 4000; /** * Initial interval (in milliseconds) for connections. * This value is modified later as traffic rates are established. * @type {number} */ mobwrite.syncInterval = 2000; /** * Optional prefix to automatically add to all IDs. * @type {string} */ mobwrite.idPrefix = ''; /** * Flag to nullify all shared elements and terminate. * @type {boolean} */ mobwrite.nullifyAll = false; /** * Track whether something changed client-side in each sync. * @type {boolean} * @private */ mobwrite.clientChange_ = false; /** * Track whether something changed server-side in each sync. * @type {boolean} * @private */ mobwrite.serverChange_ = false; /** * Temporary object used while each sync is airborne. * @type {Object?} * @private */ mobwrite.syncAjaxObj_ = null; /** * Return a random ID that's 6 characters long. * 79^6 = 243,087,455,521 * @return {string} Random ID. */ mobwrite.uniqueId = function() { // All the legal characters for a URL 'fragment' (hash) as per RFC 3986. var soup = 'ABCDEFGHIJKLMNOPQUSTPVWXYZabcdefghijklmnopqrstuvwxyz' + '0123456789-._~!$&\'()*+,;=?/'; var id = ''; for (var i = 0; i < 6; i++) { id += soup.charAt(Math.random() * soup.length); } return id; }; /** * Unique ID for this session. * @type {string} */ mobwrite.syncUsername = mobwrite.uniqueId(); /** * Hash of all shared objects. * @type {Object} */ mobwrite.shared = Object.create(null); /** * Array of registered handlers for sharing types. * Modules add their share functions to this list. * @type {Array.} */ mobwrite.shareHandlers = []; /** * Prototype of shared object. * @param {string=} id Unique file ID. * @constructor */ mobwrite.shareObj = function(id) { if (!id) return; // Creating subclass prototype object. this.file = id; this.dmp = new diff_match_patch(); this.dmp.Diff_Timeout = 0.5; // List of unacknowledged edits sent to the server. this.editStack = []; if (mobwrite.debug) { console.info('Creating shareObj: "' + id + '"'); } }; /** * Client's understanding of what the server's text looks like. * @type {string} */ mobwrite.shareObj.prototype.shadowText = ''; /** * The client's version for the shadow (n). * @type {number} */ mobwrite.shareObj.prototype.clientVersion = 0; /** * The server's version for the shadow (m). * @type {number} */ mobwrite.shareObj.prototype.serverVersion = 0; /** * Did the client understand the server's delta in the previous heartbeat? * Initialize false because the server and client are out of sync initially. * @type {boolean} */ mobwrite.shareObj.prototype.deltaOk = false; /** * Synchronization mode. * True: Used for text, attempts to gently merge differences together. * False: Used for numbers, overwrites conflicts, last save wins. * @type {boolean} */ mobwrite.shareObj.prototype.mergeChanges = true; /** * Fetch or compute a plaintext representation of the user's text. * @return {string} Plaintext content. */ mobwrite.shareObj.prototype.getClientText = function() { throw new Error('Defined by subclass'); }; /** * Set the user's text based on the provided plaintext. * @param {string} text New text. */ mobwrite.shareObj.prototype.setClientText = function(text) { throw new Error('Defined by subclass'); }; /** * Modify the user's plaintext by applying a series of patches against it. * @param {Array.} patches Array of Patch objects. */ mobwrite.shareObj.prototype.patchClientText = function(patches) { var oldClientText = this.getClientText(); var result = this.dmp.patch_apply(patches, oldClientText); // Set the new text only if there is a change to be made. if (oldClientText != result[0]) { // The following will probably destroy any cursor or selection. // Widgets with cursors should override and patch more delicately. this.setClientText(result[0]); } }; /** * Notification of when a diff was sent to the server. * @param {Array.>} diffs Array of diff tuples. */ mobwrite.shareObj.prototype.onSentDiff = function(diffs) { // Potential hook for subclass. }; /** * Fire a synthetic 'change' event to a target element. * Notifies an element that its contents have been changed. * @param {Object} target Element to notify. */ mobwrite.shareObj.prototype.fireChange = function(target) { if ('createEvent' in document) { // W3 var e = document.createEvent('HTMLEvents'); e.initEvent('change', false, false); target.dispatchEvent(e); } else if ('fireEvent' in target) { // IE target.fireEvent('onchange'); } }; /** * Return the command to nullify this field. Also unshares this field. * @return {string} Command to be sent to the server. */ mobwrite.shareObj.prototype.nullify = function() { mobwrite.unshare(this.file); return 'N:' + mobwrite.idPrefix + this.file + '\n'; }; /** * Asks the shareObj to synchronize. Computes client-made changes since * previous postback. Return '' to skip this synchronization. * @return {string} Commands to be sent to the server. */ mobwrite.shareObj.prototype.syncText = function() { var clientText = this.getClientText(); if (this.deltaOk) { // The last delta postback from the server to this shareObj was successful. // Send a compressed delta. var diffs = this.dmp.diff_main(this.shadowText, clientText, true); if (diffs.length > 2) { this.dmp.diff_cleanupSemantic(diffs); this.dmp.diff_cleanupEfficiency(diffs); } var changed = diffs.length != 1 || diffs[0][0] != DIFF_EQUAL; if (changed) { mobwrite.clientChange_ = true; this.shadowText = clientText; } // Don't bother appending a no-change diff onto the stack if the stack // already contains something. if (changed || !this.editStack.length) { var action = (this.mergeChanges ? 'd:' : 'D:') + this.clientVersion + ':' + this.dmp.diff_toDelta(diffs); this.editStack.push([this.clientVersion, action]); this.clientVersion++; this.onSentDiff(diffs); } } else { // The last delta postback from the server to this shareObj didn't match. // Send a full text dump to get back in sync. This will result in any // changes since the last postback being wiped out. :( this.shadowText = clientText; this.clientVersion++; var action = 'r:' + this.clientVersion + ':' + encodeURI(clientText).replace(/%20/g, ' '); // Append the action to the edit stack. this.editStack.push([this.clientVersion, action]); // Sending a raw dump will put us back in sync. // Set deltaOk to true in case this sync fails to connect, in which case // the following sync(s) should be a delta, not more raw dumps. this.deltaOk = true; } // Create the output starting with the file statement, followed by the edits. var data = 'F:' + this.serverVersion + ':' + mobwrite.idPrefix + this.file + '\n'; for (var i = 0; i < this.editStack.length; i++) { data += this.editStack[i][1] + '\n'; } return data; }; /** * Collect all client-side changes and send them to the server. * @private */ mobwrite.syncRun1_ = function() { // Initialize clientChange_, to be checked at the end of syncRun2_. mobwrite.clientChange_ = false; var data = []; data[0] = 'u:' + mobwrite.syncUsername + '\n'; var empty = true; // Ask every shared object for their deltas. for (var x in mobwrite.shared) { if (mobwrite.shared[x]) { if (mobwrite.nullifyAll) { data.push(mobwrite.shared[x].nullify()); } else { data.push(mobwrite.shared[x].syncText()); } empty = false; } } if (empty) { // No sync objects. if (mobwrite.debug) { console.info('MobWrite task stopped.'); } return; } if (data.length == 1) { // No sync data. if (mobwrite.debug) { console.info('All objects silent; null sync.'); } mobwrite.syncRun2_('\n\n'); return; } if (mobwrite.debug) { console.info('TO server:\n' + data.join('')); } // Add terminating blank line. data.push('\n'); data = data.join(''); // Schedule a watchdog task to catch us if something horrible happens. mobwrite.syncKillPid_ = setTimeout(mobwrite.syncKill_, mobwrite.timeoutInterval); // Issue Ajax post of client-side changes and request server-side changes. data = 'q=' + encodeURIComponent(data); mobwrite.syncAjaxObj_ = mobwrite.syncLoadAjax_(mobwrite.syncGateway, data, mobwrite.syncCheckAjax_); // Execution will resume in either syncCheckAjax_(), or syncKill_() }; /** * Parse all server-side changes and distribute them to the shared objects. * @param {string} text Raw content from server. * @private */ mobwrite.syncRun2_ = function(text) { // Initialize serverChange_, to be checked at the end of syncRun2_. mobwrite.serverChange_ = false; if (mobwrite.debug) { console.info('FROM server:\n' + text); } // There must be a newline followed by a blank line. if (text.length < 2 || text.substring(text.length - 2) != '\n\n') { text = ''; if (mobwrite.debug) { console.info('Truncated data. Abort.'); } } var lines = text.split('\n'); var file = null; var clientVersion = null; for (var i = 0; i < lines.length; i++) { var line = lines[i]; if (!line) { // Terminate on blank line. break; } // Divide each line into 'N:value' pairs. if (line.charAt(1) != ':') { if (mobwrite.debug) { console.error('Unparsable line: ' + line); } continue; } var name = line.charAt(0); var value = line.substring(2); // Parse out a version number for file, delta or raw. var version; if ('FfDdRr'.indexOf(name) != -1) { var div = value.indexOf(':'); if (div < 1) { if (mobwrite.debug) { console.error('No version number: ' + line); } continue; } version = parseInt(value.substring(0, div), 10); if (isNaN(version)) { if (mobwrite.debug) { console.error('NaN version number: ' + line); } continue; } value = value.substring(div + 1); } if (name == 'F' || name == 'f') { // File indicates which shared object following delta/raw applies to. if (value.substring(0, mobwrite.idPrefix.length) == mobwrite.idPrefix) { // Trim off the ID prefix. value = value.substring(mobwrite.idPrefix.length); } else { // This file does not have our ID prefix. file = null; if (mobwrite.debug) { console.error('File does not have "' + mobwrite.idPrefix + '" prefix: ' + value); } continue; } if (mobwrite.shared[value]) { file = mobwrite.shared[value]; file.deltaOk = true; clientVersion = version; // Remove any elements from the edit stack with low version numbers // which have been acked by the server. for (var j = 0; j < file.editStack.length; j++) { if (file.editStack[j][0] <= clientVersion) { file.editStack.splice(j, 1); j--; } } } else { // This file does not map to a currently shared object. file = null; if (mobwrite.debug) { console.error('Unknown file: ' + value); } } } else if (name == 'R' || name == 'r') { // The server reports it was unable to integrate the previous delta. if (file) { file.shadowText = decodeURI(value); file.clientVersion = clientVersion; file.serverVersion = version; file.editStack = []; if (name == 'R') { // Accept the server's raw text dump and wipe out any user's changes. file.setClientText(file.shadowText); } // Server-side activity. mobwrite.serverChange_ = true; } } else if (name == 'D' || name == 'd') { // The server offers a compressed delta of changes to be applied. if (file) { if (clientVersion != file.clientVersion) { // Can't apply a delta on a mismatched shadow version. file.deltaOk = false; if (mobwrite.debug) { console.error('Client version number mismatch.\n' + 'Expected: ' + file.clientVersion + ' Got: ' + clientVersion); } } else if (version > file.serverVersion) { // Server has a version in the future? file.deltaOk = false; if (mobwrite.debug) { console.error('Server version in future.\n' + 'Expected: ' + file.serverVersion + ' Got: ' + version); } } else if (version < file.serverVersion) { // We've already seen this diff. if (mobwrite.debug) { console.warn('Server version in past.\n' + 'Expected: ' + file.serverVersion + ' Got: ' + version); } } else { // Expand the delta into a diff using the client shadow. var diffs; try { diffs = file.dmp.diff_fromDelta(file.shadowText, value); file.serverVersion++; } catch (ex) { // The delta the server supplied does not fit on our copy of // shadowText. diffs = null; // Set deltaOk to false so that on the next sync we send // a complete dump to get back in sync. file.deltaOk = false; // Do the next sync soon because the user will lose any changes. mobwrite.syncInterval = 0; if (mobwrite.debug) { console.error('Delta mismatch.\n' + encodeURI(file.shadowText)); } } if (diffs && (diffs.length != 1 || diffs[0][0] != DIFF_EQUAL)) { // Compute and apply the patches. if (name == 'D') { // Overwrite text. file.shadowText = file.dmp.diff_text2(diffs); file.setClientText(file.shadowText); } else { // Merge text. var patches = file.dmp.patch_make(file.shadowText, diffs); // First shadowText. Should be guaranteed to work. var serverResult = file.dmp.patch_apply(patches, file.shadowText); file.shadowText = serverResult[0]; // Second the user's text. file.patchClientText(patches); } // Server-side activity. mobwrite.serverChange_ = true; } } } } } mobwrite.computeSyncInterval_(); // Ensure that there is only one sync task. clearTimeout(mobwrite.syncRunPid_); // Schedule the next sync. mobwrite.syncRunPid_ = setTimeout(mobwrite.syncRun1_, mobwrite.syncInterval); // Terminate the watchdog task, everything's ok. clearTimeout(mobwrite.syncKillPid_); mobwrite.syncKillPid_ = null; }; /** * Compute how long to wait until next synchronization. * @private */ mobwrite.computeSyncInterval_ = function() { var range = mobwrite.maxSyncInterval - mobwrite.minSyncInterval; if (mobwrite.clientChange_) { // Client-side activity. // Cut the sync interval by 40% of the min-max range. mobwrite.syncInterval -= range * 0.4; } if (mobwrite.serverChange_) { // Server-side activity. // Cut the sync interval by 20% of the min-max range. mobwrite.syncInterval -= range * 0.2; } if (!mobwrite.clientChange_ && !mobwrite.serverChange_) { // No activity. // Let the sync interval creep up by 10% of the min-max range. mobwrite.syncInterval += range * 0.1; } // Keep the sync interval constrained between min and max. mobwrite.syncInterval = Math.max(mobwrite.minSyncInterval, mobwrite.syncInterval); mobwrite.syncInterval = Math.min(mobwrite.maxSyncInterval, mobwrite.syncInterval); }; /** * If the Ajax call doesn't complete after a timeout period, start over. * @private */ mobwrite.syncKill_ = function() { mobwrite.syncKillPid_ = null; if (mobwrite.syncAjaxObj_) { // Cleanup old Ajax connection. mobwrite.syncAjaxObj_.abort(); mobwrite.syncAjaxObj_ = null; } if (mobwrite.debug) { console.warn('Connection timeout.'); } clearTimeout(mobwrite.syncRunPid_); // Initiate a new sync right now. mobwrite.syncRunPid_ = setTimeout(mobwrite.syncRun1_, 1); }; /** * Initiate an Ajax network connection. * @param {string} url Location to send request. * @param {string} post Data to be sent. * @param {Function} callback Function to be called when response arrives. * @return {!Object} New Ajax object. * @private */ mobwrite.syncLoadAjax_ = function(url, post, callback) { var req = new XMLHttpRequest(); req.onload = callback; req.open('POST', url, true); req.withCredentials = true; req.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); req.send(post); return req; }; /** * Callback function for Ajax request. Checks network response was ok, * then calls mobwrite.syncRun2_. * @private */ mobwrite.syncCheckAjax_ = function() { if (typeof mobwrite == 'undefined' || !mobwrite.syncAjaxObj_) { // This might be a callback after the page has unloaded, // or this might be a callback which we deemed to have timed out. return; } // Only if "OK" if (mobwrite.syncAjaxObj_.status === 200) { var text = mobwrite.syncAjaxObj_.responseText; mobwrite.syncAjaxObj_ = null; mobwrite.syncRun2_(text); } else if (mobwrite.syncAjaxObj_.status === 410) { // Required cookie not found. Stop sharing. console.warn('410: Required cookie not found'); for (var file in mobwrite.shared) { delete mobwrite.shared[file]; } } else { if (mobwrite.debug) { console.warn('Connection error code: ' + mobwrite.syncAjaxObj_.status); } mobwrite.syncAjaxObj_ = null; } }; /** * When unloading, run a sync one last time. * @private */ mobwrite.unload_ = function() { if (!mobwrite.syncKillPid_) { // Turn off debug mode since the console disappears on page unload before // this code does. mobwrite.debug = false; mobwrite.syncRun1_(); } // By the time the callback runs mobwrite.syncRun2_, this page will probably // be gone. But that's ok, we are just sending our last changes out, we // don't care what the server says. }; // Attach unload event to addEventListener('unload', mobwrite.unload_, false); /** * Start sharing the specified object(s). * @param {*} var_args Object(s) or ID(s) of object(s) to share. */ mobwrite.share = function(var_args) { for (var i = 0; i < arguments.length; i++) { var el = arguments[i]; var result = null; // Ask every registered handler if it knows what to do with this object. for (var j = 0; j < mobwrite.shareHandlers.length && !result; j++) { result = mobwrite.shareHandlers[j].call(mobwrite, el); } if (result && result.file) { if (!result.file.match(/^[-.~!$&\'()*+,;=?\/\w]*$/)) { if (mobwrite.debug) { console.error('Illegal id "' + result.file + '".'); } continue; } if (result.file in mobwrite.shared) { // Already exists. // Don't replace, since we don't want to lose state. if (mobwrite.debug) { console.warn('Ignoring duplicate share on "' + el + '".'); } continue; } mobwrite.shared[result.file] = result; if (mobwrite.syncRunPid_ === null) { // Startup the main task if it doesn't already exist. if (mobwrite.debug) { console.info('MobWrite task started.'); } } else { // Bring sync forward in time. clearTimeout(mobwrite.syncRunPid_); } mobwrite.syncRunPid_ = setTimeout(mobwrite.syncRun1_, 10); } else { if (mobwrite.debug) { console.warn('Share: Unknown widget type: ' + el + '.'); } } } }; /** * Stop sharing the specified object(s). * Does not handle forms recursively. * @param {*} var_args Object(s) or ID(s) of object(s) to unshare. */ mobwrite.unshare = function(var_args) { for (var i = 0; i < arguments.length; i++) { var el = arguments[i]; if (typeof el == 'string' && mobwrite.shared[el]) { delete mobwrite.shared[el]; if (mobwrite.debug) { console.info('Unshared: ' + el); } } else { // Pretend to want to share this object, acquire a new shareObj, then use // its ID to locate and kill the existing shareObj that's already shared. var result = null; // Ask every registered handler if it knows what to do with this object. for (var j = 0; j < mobwrite.shareHandlers.length && !result; j++) { result = mobwrite.shareHandlers[j].call(mobwrite, el); } if (result && result.file) { if (mobwrite.shared[result.file]) { delete mobwrite.shared[result.file]; if (mobwrite.debug) { console.info('Unshared: ' + el); } } else { if (mobwrite.debug) { console.warn('Ignoring ' + el + '. Not currently shared.'); } } } else { if (mobwrite.debug) { console.warn('Unshare: Unknown widget type: ' + el + '.'); } } } } }; ================================================ FILE: static/code/objectPanel.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Integrated Development Environment for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; Code.ObjectPanel = {}; /** * List of parts (passed in by the URL hash). * @type {?Array} */ Code.ObjectPanel.parts = null; /** * DOM node containing the list of properties. * @type {?Element} */ Code.ObjectPanel.tableBody = null; /** * Structured data from Code City. * @type {?Object} */ Code.ObjectPanel.data = null; /** * Page has loaded, initialize the panel. Called by Code City with data. */ Code.ObjectPanel.init = function() { Code.ObjectPanel.tableBody = document.getElementById('objectTableBody'); // Clear the '...' Code.ObjectPanel.tableBody.innerHTML = ''; var data = Code.ObjectPanel.data; if (!data) { // Server error. Should not happen. var title = document.getElementById('objectTitle'); title.className = 'objectFailTitle'; var fail = document.getElementById('objectFail'); fail.style.display = 'table-row'; return; } if (data.roots) { // Print all root objects. for (var root of data.roots) { var part = {type: 'id', value: root.name}; Code.ObjectPanel.addLink(part, root.type, false); } } if (data.properties) { Code.ObjectPanel.filterShadowed(data.properties); // Print all properties of this object. for (var i = 0; i < data.properties.length; i++) { var propList = data.properties[i]; propList.sort(Code.ObjectPanel.caseInsensitiveComp_); for (var j = 0; j < propList.length; j++) { var part = {type: 'id', value: propList[j].name}; Code.ObjectPanel.addLink(part, propList[j].type, i && !j); } } } if (data.keywords) { var first = true; for (var keyword of data.keywords) { var part = {type: 'keyword', value: keyword}; Code.ObjectPanel.addLink(part, 'object', first); first = false; } } // Position the type symbols, and monitor for layout changes. Code.ObjectPanel.positionTypes(); window.addEventListener('scroll', Code.ObjectPanel.positionTypes, false); window.addEventListener('resize', Code.ObjectPanel.positionTypes, false); // Highlight current item, and monitor for path changes. Code.ObjectPanel.highlight(); window.addEventListener('message', Code.ObjectPanel.highlight, false); }; /** * Create the DOM elements to add one property link to the list. * @param {!Object} part Single selector part. * @param {string} type Type of the property value. * @param {boolean} section Flag indicating a new section. */ Code.ObjectPanel.addLink = function(part, type, section) { var newParts = Code.ObjectPanel.parts.concat(part); var selector = Code.Common.partsToSelector(newParts); var a = document.createElement('a'); var query = encodeURIComponent(selector).replace(/%24/g, '$'); a.href = './?' + query; a.target = '_blank'; a.setAttribute('data-link', JSON.stringify(part)); a.addEventListener('click', Code.ObjectPanel.click); var text = document.createTextNode(Code.Common.partsToSelector([part])); a.appendChild(text); var td = document.createElement('td'); if (section) { td.className = 'section'; } var typeSymbol = Code.ObjectPanel.TYPES[type]; if (typeSymbol) { var div = document.createElement('div'); div.className = 'objectType'; div.appendChild(document.createTextNode(typeSymbol)); div.title = type; td.appendChild(div); } td.appendChild(a); var tr = document.createElement('tr'); tr.appendChild(td); Code.ObjectPanel.tableBody.appendChild(tr); }; /** * Symbols to print next to properties. */ Code.ObjectPanel.TYPES = { 'array': '[]', 'boolean': '⏼', 'function': '𝑓', 'null': '␀', 'number': '#', 'object': '{}', 'string': '”', 'symbol': '☆', 'verb': '𝑣𝑓' }; /** * When scrollbar is moved or size changes reposition the floating types. */ Code.ObjectPanel.positionTypes = function() { var left = (document.body.clientWidth + window.scrollX - 18) + 'px'; var types = document.getElementsByClassName('objectType'); for (var t of types) { t.style.left = left; } }; /** * When a property is clicked, trigger an update. * @param {!Event} e Click event. */ Code.ObjectPanel.click = function(e) { if (e.metaKey || e.ctrlKey) { return; } var part = JSON.parse(e.currentTarget.getAttribute('data-link')); var newParts = Code.ObjectPanel.parts.concat(part); var selector = Code.Common.partsToSelector(newParts); // Store the new selector in sessionStorage for all frames to see. sessionStorage.setItem(Code.Common.SELECTOR, selector); // Alert the top "/code" frameset that there's been a selector change. window.parent.parent.postMessage('ping', '*'); // Don't navigate to this link. e.preventDefault(); }; /** * Currently selected property, or null if none. * @type {?Element} */ Code.ObjectPanel.highlighted = null; /** * Highlight the currently selected property (if any). * The current selection is based on a value in sessionStorage. */ Code.ObjectPanel.highlight = function() { var selector = sessionStorage.getItem(Code.Common.SELECTOR); var parts = Code.Common.selectorToParts(selector); var part = parts ? parts[Code.ObjectPanel.parts.length] : null; var jsonPart = JSON.stringify(part); var newHighlighted = null; for (var tr of Code.ObjectPanel.tableBody.childNodes) { var td = tr.firstChild; var link = td.lastChild; // There might be an objectType div first. if (link.getAttribute('data-link') === jsonPart) { newHighlighted = td; } } if (newHighlighted !== Code.ObjectPanel.highlighted) { if (Code.ObjectPanel.highlighted) { Code.ObjectPanel.highlighted.classList.remove('highlighted'); } if (newHighlighted) { newHighlighted.classList.add('highlighted'); if (newHighlighted.scrollIntoView) { newHighlighted.scrollIntoView({block: 'nearest', inline: 'nearest'}); } } Code.ObjectPanel.highlighted = newHighlighted; } }; /** * Remove any properties that are shadowed by objects higher on the inheritance * chain. * @param {Array>} data Property names from Code City. */ Code.ObjectPanel.filterShadowed = function(data) { if (!data || data.length < 2) return; var seen = Object.create(null); for (var datum of data) { var cursorInsert = 0; var cursorRead = 0; while (cursorRead < datum.length) { var prop = datum[cursorRead++]; if (!seen[prop.name]) { seen[prop.name] = true; datum[cursorInsert++] = prop; } } datum.length = cursorInsert; } }; /** * Comparison function to sort named objects A-Z without regard to case. * @param {!Object} a One named object. * @param {!Object} b Another named object. * @return {number} -1/0/1 comparator value. * @private */ Code.ObjectPanel.caseInsensitiveComp_ = function(a, b) { return Code.Common.caseInsensitiveComp(a.name, b.name); }; if (!window.TEST) { (function() { // Fill in the object name. var query = decodeURIComponent(location.search.substring(1)); Code.ObjectPanel.parts = Code.Common.selectorToParts(query); var div = document.getElementById('objectTitle'); var lastPart = Code.ObjectPanel.parts[Code.ObjectPanel.parts.length - 1]; var name; if (!lastPart) { name = 'Globals'; } else if (Code.ObjectPanel.parts.length === 1) { // Render as 'foo' or '[42]' or '["???"]' or '{xyz}'. name = Code.Common.partsToSelector([lastPart]); } else { // Render as '.foo' or '[42]' or '["???"]' or '{xyz}'. var mockParts = [{type: 'id', value: 'X'}, lastPart]; name = Code.Common.partsToSelector(mockParts).substring(1); } div.innerHTML = ''; div.appendChild(document.createTextNode(name)); })(); window.addEventListener('load', Code.ObjectPanel.init); } ================================================ FILE: static/code/style.css ================================================ body { background: #fff; color: #444; font-family: "Roboto Mono", monospace; font-size: 11pt; } input, textarea { font-family: "Roboto Mono", monospace; font-size: 11pt; } #input { box-sizing: border-box; margin-left: -2px; width: 100%; } #input.invalid { color: red; } #autocompleteMenu { background: #fff; border-color: #ccc #666 #666 #ccc; border-style: solid; border-width: 1px; display: none; max-width: 20em; overflow-y: auto; padding: 4px 0; position: absolute; z-index: 1; } #autocompleteMenuScroll { } #autocompleteMenuScroll>div { cursor: default; overflow-x: hidden; padding: 0 1em; text-overflow: ellipsis; white-space: nowrap; } #autocompleteMenuScroll>div.selected { background-color: #def; } #panels { bottom: 5px; left: 0; overflow-x: auto; overflow-y: hidden; position: absolute; right: 0; top: 42px; width: 100%; } #panelsScroll { height: 100%; padding-left: 5px; white-space: nowrap; } #panelsScroll>iframe { border: 2px solid #444; border-radius: 2px; box-sizing: border-box; height: 100%; margin: 0 5px 0 0; padding: 0; width: 300px; } #panelsScroll>iframe:last-of-type { width: 500px; } #objectPanel { margin: 0; } #objectFail { display: none; } #objectFail>tr>td { padding: 8px; } .objectFailTitle { background-color: #d00; color: #fff; } #objectPanel { margin: 0; } #objectTitle { border-bottom: 2px solid #444; padding: 8px; } #objectTable { border-collapse: collapse; width: 100%; } #objectTableBody>tr>td { padding: 0 2ex 0 8px; } #objectTableBody>tr>td>a { color: #444; display: block; text-decoration: none; } #objectTableBody>tr>td:hover { background-color: #d6e9f8; } #objectTableBody>tr>td.highlighted { background-color: #ccc; } #objectTableBody>tr>td.section { border-top: 1px solid #444; } .objectType { color: #888; font-family: monospace; font-size: medium; padding-top: 2px; position: absolute; text-align: center; width: 3ex; } .loading:after { animation: ellipsis steps(5, end) 1000ms infinite; content: "..."; display: inline-block; overflow: hidden; vertical-align: bottom; width: 0; } @keyframes ellipsis { to { width: 3.2em; } } #editorButtons { float: right; margin-right: 3px; } #editorHeader { margin-top: 5px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } #editorTabs { font-family: "Arial", "Helvetica", sans-serif; font-size: 11px; margin-top: -2px; } #editorTabs>.spacer { border-bottom: 1px solid rgba(0,0,0,.1); padding: 4px 5px; } #editorTabs>.jfk-button { border-bottom-color: #f1f1f1; border-bottom-left-radius: 0; border-bottom-right-radius: 0; height: auto; line-height: normal; margin-right: 0; padding-bottom: 4px; padding-top: 4px; } #editorTabs.disabled>.jfk-button { color: #ccc; } #editorTabs>.highlighted { background-color: #ccc; background-image: none; } #editorContainers>div { display: none; } #editorDialog, #editorDialogBox, #editorConfirmBox, #editorShareBox { display: none; } #editorDialogMask, #editorSavingMask { background-color: #000; bottom: 0; left: 0; opacity: 0; position: absolute; right: 0; top: 0; transition-property: opacity; z-index: 998; } #editorSavingMask { cursor: wait; display: none; transition-duration: 1s; } #editorDialogBox { background-color: #fff; border: 2px solid #444; border-radius: 2px; border-top: none; left: 0; margin: 0 auto; padding: 1em; position: absolute; right: 0; text-align: center; top: -120px; transition-property: top; width: 20em; z-index: 999; } #editorConfirmDiscard { float: left; margin-left: 25px; } #editorConfirmCancel { float: right; } #editorConfirmSave, #editorShareOk { float: right; margin-right: 25px; } #editorShareBox.disabled { color: #ccc; } #editorShareAddress { width: 18em; } .CodeMirror { border: 1px solid #ddd; } ================================================ FILE: static/code/svg.css ================================================ body { margin: 0; padding: 0; overflow: hidden; } #editorContainer { position: absolute; } #toolbox { padding-left: 2px; } #svgroot { border: 1px solid #ccc; box-sizing: border-box; overflow: hidden; } #canvasBackground { display: none; } #toolboxColumn1 { left: 3px; position: absolute; top: 0; } #toolboxColumn2 { left: 40px; position: absolute; top: 0; } #toolbox button { background: #eee; border-radius: 3px; box-shadow: inset 1px 1px 2px white, 1px 1px 1px rgba(0,0,0,0.3); margin: 4px; padding: 1px; display: block; } #toolbox button:hover { background: #d6e9f8; } #toolbox button.selected { background: #ccc; box-shadow: inset 1px 1px 2px rgba(0,0,0,0.4), 1px 1px 0 #fff; } #toolbox button:focus { outline: 0; } #menu { background: #fff; border-color: #ccc #666 #666 #ccc; border-radius: 4px; border-style: solid; border-width: 1px; cursor: default; display: none; font: normal 13px Arial, sans-serif; margin: 0; max-height: 100%; outline: none; padding: 4px 0; position: absolute; user-select: none; z-index: 100; } .menuitem { color: #444; margin: 0; padding: 4px 1em; white-space: nowrap; } .menuitem:hover:not(.menuItemDisabled) { background-color: #d6e9f8; border-color: #d6e9f8; border-style: dotted; border-width: 1px 0; padding-bottom: 3px; padding-top: 3px; } .menuItemDisabled { color: #ccc; } .menudiv { border-top: 1px solid #ccc; margin-top: 4px; padding-top: 4px; } ================================================ FILE: static/code/svg.js ================================================ /** * @license * Copyright 2018 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview SVG Editor using SvgCanvas from SVG-Edit. * @author fraser@google.com (Neil Fraser) */ 'use strict'; import Canvas from './SVG-Edit/svgcanvas.js'; var svgEditor = {}; // Export namespace variable to window (would normally happen automatically, // but this file is being loaded as a module). // Used to for the parent frame to communicate with us. window.svgEditor = svgEditor; svgEditor.init = function() { var container = document.getElementById('editorContainer'); var config = { initFill: {color: 'FFFFFF', opacity: 1}, initStroke: {color: '000000', opacity: 1, width: 1}, text: {stroke_width: 0, font_size: 24, font_family: 'serif'}, initOpacity: 1, imgPath: 'SVG-Edit/images/', baseUnit: 'px', }; svgEditor.canvas = new Canvas(container, config); // Check to see if the parent window left us an initial source to render. var source = window.initialSource; if (source !== undefined) { svgEditor.setString(source); delete window.initialSource; } svgEditor.resize(); // Update the toolbox whenever a button is clicked. // Don't wait for up to a quarter second until the next scheduled call. // Also force a heavier update to catch changes such as open-close path. var update = svgEditor.updateToolbox.bind(svgEditor, true); for (var button of document.querySelectorAll('#toolbox button')) { button.addEventListener('click', update, false); } document.addEventListener('keydown', svgEditor.keypress); document.addEventListener('contextmenu', svgEditor.openMenu, false); document.addEventListener('mousedown', svgEditor.mousedown, false); document.getElementById('menu').addEventListener('click', svgEditor.menuClick); // Don't undo beyond initialization. svgEditor.canvas.undoMgr.resetUndoStack(); }; /** * Resize and reposition the SVG canvas when the window has changed shape. * Zoom so that a 100 unit tall image fills the screen. */ svgEditor.resize = function() { var top = 0; var left = 80; var height = window.innerHeight; var width = window.innerWidth - left; var container = document.getElementById('editorContainer'); container.style.top = top + 'px'; container.style.left = left + 'px'; // Code City sprites are 100 units tall. var FIXED_HEIGHT = 100; var zoom = height / FIXED_HEIGHT; svgEditor.canvas.setZoom(zoom); svgEditor.canvas.setResolution(width / height * FIXED_HEIGHT, FIXED_HEIGHT); svgEditor.canvas.updateCanvas(width, height); // Recenter the origin to be the middle of the screen. svgEditor.canvas.getRootElem().setAttribute('viewBox', (-width / 2) + ' 0 ' + width + ' ' + height); }; /** * Handle mouse down actions. */ svgEditor.mousedown = function(e) { // Control-clicking on Mac OS X is treated as a right-click. // WebKit on Mac OS X fails to change button to 2 (but Gecko does). if (e.ctrlKey || e.button === 2) { svgEditor.openMenu(e); } else if (!document.getElementById('menu').contains(e.target)) { svgEditor.closeMenu(); } }; /** * Handle keyboard commands. */ svgEditor.keypress = function(e) { if (e.key === 'Delete' || e.key === 'Backspace') { svgEditor.delete(); e.preventDefault(); } else if (e.ctrlKey || e.metaKey) { if (e.key === 'z') { if (e.shiftKey) { svgEditor.redo(); } else { svgEditor.undo(); } e.preventDefault(); } else if (e.key === 'x') { svgEditor.cut(); e.preventDefault(); } else if (e.key === 'c') { svgEditor.copy(); e.preventDefault(); } else if (e.key === 'v') { svgEditor.paste(); e.preventDefault(); } } }; /** * Redo one action. */ svgEditor.redo = function() { var undoMgr = svgEditor.canvas.undoMgr; if (undoMgr.getRedoStackSize() > 0) { undoMgr.redo(); } }; /** * Undo one action. */ svgEditor.undo = function() { var undoMgr = svgEditor.canvas.undoMgr; if (undoMgr.getUndoStackSize() > 0) { undoMgr.undo(); } }; /** * Cut selected element(s). */ svgEditor.cut = function() { svgEditor.copy(); svgEditor.canvas.deleteSelectedElements(); }; /** * Copy selected element(s). */ svgEditor.copy = function() { svgEditor.canvas.copySelectedElements(); }; /** * Delete selected element(s). */ svgEditor.delete = function() { svgEditor.canvas.deleteSelectedElements(); }; /** * Paste clipboard to middle of editor. */ svgEditor.paste = function() { var svgCanvas = svgEditor.canvas; var workarea = document.getElementById('editorContainer'); var zoom = svgCanvas.getZoom(); var y = (workarea.scrollTop + workarea.offsetHeight / 2) / zoom - svgCanvas.contentH; svgCanvas.pasteElements('point', 0, -y); }; /** * Inject SVG to the editor. * @param {string} xmlString SVG rendered as text. */ svgEditor.setString = function(xmlString) { // SvgCanvas needs contents wrapped in a throw-away SVG node. if (xmlString) { var svgString = '' + xmlString + ''; svgEditor.canvas.setSvgString(svgString); } else { svgEditor.canvas.clear(); } svgEditor.resize(); // Preserve the original input, alongside its round-tripped output. svgEditor.inputString = xmlString; svgEditor.outputString = svgEditor.getString(); }; svgEditor.inputString = undefined; svgEditor.outputString = undefined; /** * Extract the SVG from the editor. * @return {string} SVG rendered as text. */ svgEditor.getString = function() { var rootSvg = svgEditor.canvas.getContentElem(); // The user's image is the wrapped in the first group. var contentSvg = rootSvg.querySelector('svg g').cloneNode(true); // Remove the layer title. var title = contentSvg.querySelector('g>title'); title.parentNode.removeChild(title); // Walk the tree removing unused properties. var tw = document.createTreeWalker(contentSvg, NodeFilter.SHOW_ELEMENT); do { var node = tw.currentNode; node.removeAttribute('id'); node.removeAttribute('fill'); node.removeAttribute('stroke'); } while (tw.nextNode()); var source = svgEditor.canvas.svgToString(contentSvg, -1); // Remove the wrapping . source = source.replace(/^\s*]*>\s*/i, ''); source = source.replace(/\s*<\/g>\s*$/i, ''); // If the output is the same as the original input's round-tripped value, // then return the original input. // Otherwise changes may be claimed when none were made by the user. if (source === svgEditor.outputString) { return svgEditor.inputString; } return source; }; /** * Update the toolbox visualization in response to the editor state. * This function is called four times a second, and when a button is clicked. * @param {boolean=} force If true, force a redraw. */ svgEditor.updateToolbox = function(force) { // Highlight the current mode button. var mode = svgEditor.canvas.getMode(); if (force || (mode !== 'resize' && mode !== 'rotate' && mode !== svgEditor.updateToolbox.oldMode_)) { var stylePathEdit = document.getElementById('mode-pathedit').style; var styleSelect = document.getElementById('mode-select').style; var styleNodeActions = document.getElementById('node-actions').style; if (mode === 'pathedit') { styleSelect.display = 'none'; stylePathEdit.display = 'block'; styleNodeActions.display = 'block'; // Show or hide the appropriate open/close path button. var styleCloseAction = document.getElementById('close-action').style; var styleOpenAction = document.getElementById('open-action').style; if (svgEditor.canvas.pathActions.closed_subpath) { styleCloseAction.display = 'none'; styleOpenAction.display = 'block'; } else { styleOpenAction.display = 'none'; styleCloseAction.display = 'block'; } } else { stylePathEdit.display = 'none'; styleSelect.display = 'block'; styleNodeActions.display = 'none'; } var button = document.getElementById('mode-' + svgEditor.updateToolbox.oldMode_); if (button) { button.classList.remove('selected'); } svgEditor.updateToolbox.oldMode_ = mode; button = document.getElementById('mode-' + mode); if (button) { button.classList.add('selected'); } } // Show or hide action buttons that apply to one or more selected elements. var selected = svgEditor.canvas.getSelectedElems(); if (selected.length !== svgEditor.updateToolbox.oldSelectedCount_) { var actions = document.getElementById('selected-actions'); var singleActions = document.getElementById('selected-single-actions'); actions.style.display = selected.length > 0 ? 'block' : 'none'; singleActions.style.display = selected.length === 1 ? 'block' : 'none'; svgEditor.updateToolbox.oldSelectedCount_ = selected.length; document.getElementById('menuCut').classList .toggle('menuItemDisabled', selected.length === 0); document.getElementById('menuCopy').classList .toggle('menuItemDisabled', selected.length === 0); document.getElementById('menuDelete').classList .toggle('menuItemDisabled', selected.length === 0); } if (selected.length === 1) { var element = selected[0]; document.getElementById('convertpath-action').style.display = element.tagName === 'path' ? 'none' : 'block'; var fillStroke = svgEditor.getFillStroke(element); var fill = fillStroke[0]; var stroke = fillStroke[1]; var fillRect = document.getElementById('fillRect'); var fillNoneStyle = document.getElementById('fillNone').style; if (fill === 'fillNone') { fillNoneStyle.display = 'inline'; fillRect.setAttribute('class', 'fillWhite'); } else { fillNoneStyle.display = 'none'; fillRect.setAttribute('class', fill); } var strokeRect = document.getElementById('strokeRect'); if (stroke === 'strokeNone') { strokeRect.setAttribute('stroke-width', '1'); strokeRect.setAttribute('stroke', '#d40000'); strokeRect.setAttribute('class', ''); } else { strokeRect.setAttribute('stroke-width', '4'); strokeRect.setAttribute('stroke', ''); strokeRect.setAttribute('class', stroke); } } }; svgEditor.updateToolbox.oldMode_ = ''; svgEditor.updateToolbox.oldSelectedCount_ = NaN; /** * Find the fill and stroke for an element. * @param {!Element} element Element with style. * @return {!Array} Array with normalized fill and stroke strings. */ svgEditor.getFillStroke = function(element) { if (!element) throw new TypeError('Element not provided'); var classes = element.getAttribute('class') || ''; classes = classes.replace(/Gray/g, 'Grey'); var fill = classes.match(/\b(fill(None|White|Black|Grey))\b/); fill = fill ? fill[1] : 'fillNone'; var stroke = classes.match(/\b(stroke(None|White|Black|Grey))\b/); stroke = stroke ? stroke[1] : 'strokeBlack'; return [fill, stroke]; }; /** * Rotate the fill in the currently selected object between allowed options. */ svgEditor.changeFill = function() { var element = svgEditor.canvas.getSelectedElems()[0]; var fill = svgEditor.getFillStroke(element)[0]; var fillOptions = ['fillNone', 'fillBlack', 'fillGrey', 'fillWhite']; var fillIndex = Math.max(fillOptions.indexOf(fill), 0); fillIndex++; fillIndex %= fillOptions.length; var classes = element.getAttribute('class') || ''; classes = classes.replace(/\bfill\w+\b/g, ''); classes += ' ' + fillOptions[fillIndex]; classes = classes.replace(/\s+/g, ' ').trim(); element.setAttribute('class', classes); }; /** * Rotate the stroke in the currently selected object between allowed options. */ svgEditor.changeStroke = function() { var element = svgEditor.canvas.getSelectedElems()[0]; var stroke = svgEditor.getFillStroke(element)[1]; var strokeOptions = ['strokeBlack', 'strokeGrey', 'strokeWhite', 'strokeNone']; var strokeIndex = Math.max(strokeOptions.indexOf(stroke), 0); strokeIndex++; strokeIndex %= strokeOptions.length; var classes = element.getAttribute('class') || ''; classes = classes.replace(/\bstroke\w+\b/g, ''); classes += ' ' + strokeOptions[strokeIndex]; classes = classes.replace(/\s+/g, ' ').trim(); element.setAttribute('class', classes); }; /** * Open the context menu command menu at the mouse location. * @param {!Event} e Mouse event. */ svgEditor.openMenu = function(e) { svgEditor.closeMenu(); var menu = document.getElementById('menu'); var pageHeight = window.innerHeight; var pageWidth = window.innerWidth; var top = e.y; var left = e.x; menu.style.display = 'block'; // Don't go off the bottom of the page (hug the bottom). if (top + menu.offsetHeight > pageHeight) { top = Math.max(pageHeight - menu.offsetHeight, 0); } // Don't go off the right of the page (flip menu). if (left + menu.offsetWidth > pageWidth) { left = Math.max(left - menu.offsetWidth, 0); } menu.style.top = top + 'px'; menu.style.left = left + 'px'; // Don't open the system context menu. e.preventDefault(); }; /** * If there is a menu open, close it. */ svgEditor.closeMenu = function() { document.getElementById('menu').style.display = 'none'; }; /** * Handle mouse clicking on a context menu option. * @param {!Event} e Mouse event. */ svgEditor.menuClick = function(e) { if (!e.target.classList.contains('menuItemDisabled')) { switch (e.target.id) { case 'menuCut': svgEditor.cut(); break; case 'menuCopy': svgEditor.copy(); break; case 'menuPaste': svgEditor.paste(); break; case 'menuDelete': svgEditor.delete(); break; } } svgEditor.closeMenu(); }; window.addEventListener('load', svgEditor.init); window.addEventListener('resize', svgEditor.resize); window.addEventListener('mousedown', window.focus); setInterval(svgEditor.updateToolbox, 250); ================================================ FILE: static/code/tests/test.html ================================================ Test harness for Code City: Code

Test harness for Code City: Code

================================================ FILE: static/code/tests/test.js ================================================ /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Tests for Integrated Development Environment for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; function testCommonSelectorToParts() { // Join a list of parts into a path selector. assertEquals('[{"type":"id","value":"$"},{"type":"keyword","value":"{proto}"},{"type":"id","value":"foo"}]', JSON.stringify(Code.Common.selectorToParts('${proto}.foo'))); } function testCommonPartsToSelector() { // Join a list of parts into a path selector. assertEquals('${proto}.foo', Code.Common.partsToSelector([{type: 'id', value: '$'}, {type: 'keyword', value: '{proto}'}, {type: 'id', value: 'foo'}])); } function testCommonSelectorToReference() { // No substitution. assertEquals('$.foo', Code.Common.selectorToReference('$.foo')); // Parent substitution. assertEquals("$('${proto}.foo')", Code.Common.selectorToReference('${proto}.foo')); } function testGetPrefix() { // No string. assertEquals('', Code.Explorer.getPrefix([])); // One string. assertEquals('foo', Code.Explorer.getPrefix(['foo'])); // No prefix. assertEquals('', Code.Explorer.getPrefix(['foo', 'bar', 'baz'])); // Some prefix. assertEquals('ba', Code.Explorer.getPrefix(['bar', 'baz'])); // Whole prefix. assertEquals('foo', Code.Explorer.getPrefix(['foo', 'foot', 'food'])); // Case-sensitive. assertEquals('foo', Code.Explorer.getPrefix(['foot', 'fooT'])); } function testAutocompletePrefix() { // No options. assertEquals('{"prefix":"foo","terminal":false}', JSON.stringify(Code.Explorer.autocompletePrefix([], 'foo'))); // One option. assertEquals('{"prefix":"FOOT","terminal":true}', JSON.stringify(Code.Explorer.autocompletePrefix(['FOOT'], 'foo'))); // No prefix, one option. assertEquals('{"prefix":"foot","terminal":true}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot'], ''))); // No prefix, two options. assertEquals('{"prefix":"foo","terminal":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['food', 'foot'], ''))); // Case-sensitive prefix. assertEquals('{"prefix":"foo","terminal":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot', 'fool', 'FORK'], 'f'))); // Case-sensitive prefix. assertEquals('{"prefix":"FORK","terminal":true}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot', 'fool', 'FORK'], 'F'))); // Case-insensitive prefix. assertEquals('{"prefix":"foo","terminal":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['foot', 'fool'], 'F'))); // Case-insensitive no match. assertEquals('{"prefix":"Fo","terminal":false}', JSON.stringify(Code.Explorer.autocompletePrefix(['FOOT', 'fool'], 'Fo'))); } ================================================ FILE: static/connect/common.css ================================================ body { color: #444; } a { color: #00e; } a:hover { color: #d00; } a.command { cursor: pointer; text-decoration: underline dotted; } body.disconnected a.command, body.disconnected a.command:hover { cursor: not-allowed; color: #444; text-decoration-color: #444; } #scrollDiv { bottom: 0; left: 0; max-height: 100%; overflow-y: auto; position: absolute; right: 0; } svg.menuIcon { cursor: pointer; display: inline; fill: #444; height: 10px; stroke: #fff; vertical-align: top; width: 11px; } body.disconnected svg.menuIcon { cursor: not-allowed; fill: #ccc; } svg.menuIcon:hover { fill: #d00; } body.disconnected svg.menuIcon:hover { fill: #aaa; } #menu { background: #fff; border-color: #ccc #666 #666 #ccc; border-radius: 4px; border-style: solid; border-width: 1px; cursor: default; font: normal 13px Arial, sans-serif; margin: 0; max-height: 100%; outline: none; padding: 4px 0; position: absolute; z-index: 100; } .menuitem { color: #444; margin: 0; padding: 4px 1em; white-space: nowrap; } body.disconnected .menuitem { color: #ccc; cursor: not-allowed; } .menuitem:hover { background-color: #d6e9f8; border-color: #d6e9f8; border-style: dotted; border-width: 1px 0; padding-bottom: 3px; padding-top: 3px; } ================================================ FILE: static/connect/common.js ================================================ /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Functions common across log/world frames of Code City's client. * @author fraser@google.com (Neil Fraser) */ 'use strict'; var CCC = {}; CCC.Common = {}; /** * Namespace for SVG elements. * @constant */ CCC.Common.NS = 'http://www.w3.org/2000/svg'; /** * Is the client currently connected to the server? */ CCC.Common.isConnected = false; /** * Enum for message types to the log/world frames. * Should be identical to CCC.MessageTypes * @enum {string} */ CCC.Common.MessageTypes = { // Messages that may be paused: COMMAND: 'command', // User-generated command echoed. MEMO: 'memo', // Block of text from Code City. CONNECT_MSG: 'connect msg', // User-visible connection message. DISCONNECT_MSG: 'disconnect msg', // User-visible disconnection message. // Messages that may be sent while paused: CONNECTION: 'connection', // Signal change of connection state. CLEAR: 'clear', // Signal tho clear history. BLUR: 'blur' // Signal to close pop-up menus. }; /** * Initialization code called on startup. */ CCC.Common.init = function() { CCC.Common.parser = new DOMParser(); CCC.Common.serializer = new XMLSerializer(); document.body.addEventListener('click', CCC.Common.closeMenu, true); document.body.addEventListener('keydown', CCC.Common.keyDown, true); document.body.addEventListener('keypress', CCC.Common.keyPress, true); // Report back to the parent frame that we're fully loaded and ready to go. parent.postMessage('init', location.origin); }; /** * Verify that a received message is from our parent frame. * @param {!Event} e Incoming message event. * @return {*} Value from message. */ CCC.Common.verifyMessage = function(e) { var origin = e.origin || e.originalEvent.origin; if (origin !== location.origin) { throw new Error('Message received by frame from unknown origin: ' + origin); } return e.data; }; /** * Change the connection status between being connected or disconnected. * @param {boolean} newConnected New status. */ CCC.Common.setConnected = function(newConnected) { if (newConnected === CCC.Common.isConnected) { return; // No change. } CCC.Common.isConnected = newConnected; // Add/remove a classname on body, so that links and menus can change style. if (CCC.Common.isConnected) { document.body.classList.remove('disconnected'); } else { document.body.classList.add('disconnected'); } }; /** * Create a command menu icon. Attach the menu commands to the icon. * @param {!Array|!Element} cmds Array of menu commands, * or root DOM element describing the menu commands. * @return {SVGSVGElement} Root element of icon. */ CCC.Common.newMenuIcon = function(cmds) { if (cmds.querySelectorAll) { // HTML frames provide commands as XML. // Convert the command DOM into an array. // look Bob -> ['look Bob'] var nodes = cmds.querySelectorAll('cmd'); cmds = []; for (var i = 0; i < nodes.length; i++) { cmds[i] = CCC.Common.innerText(nodes[i]); } } if (!cmds.length) { return null; } var svg = CCC.Common.createSvgElement('svg', {'class': 'menuIcon', 'data-cmds': JSON.stringify(cmds)}); CCC.Common.createSvgElement('path', {'d': 'm 0.5,2.5 5,5 5,-5 z'}, svg); return svg; }; /** * Concatenate all the text element in a DOM tree. * 123456789 -> '123456789' * @param {!Element} node Root DOM element. * @return {string} Plain text. */ CCC.Common.innerText = function(node) { var text = ''; if (node.nodeType === Node.TEXT_NODE) { text = node.data; } else if (node.nodeType === Node.ELEMENT_NODE) { for (var child of node.childNodes) { text += CCC.Common.innerText(child); } } return text; }; /** * Open the command menu for the clicked menu icon. * @param {!Event} e Click event. * @this {!SVGSVGElement} Root element of icon. */ CCC.Common.openMenu = function(e) { CCC.Common.closeMenu(); // Should be already closed, but let's make sure. var cmds = JSON.parse(this.getAttribute('data-cmds')); var menu = document.createElement('div'); menu.id = 'menu'; for (var cmd of cmds) { var menuItem = document.createElement('div'); menuItem.className = 'menuitem'; menuItem.appendChild(document.createTextNode(cmd)); menuItem.addEventListener('click', CCC.Common.commandFunction, false); menu.appendChild(menuItem); } var scrollDiv = document.getElementById('scrollDiv'); var pageHeight = scrollDiv.scrollHeight; var pageWidth = scrollDiv.scrollWidth; scrollDiv.appendChild(menu); var iconRect = this.getBoundingClientRect(); // Calculate preferred location of below and right of icon. var top = iconRect.top + scrollDiv.scrollTop + iconRect.height - scrollDiv.offsetTop; var left = iconRect.left + scrollDiv.scrollLeft; // Flip up if below page. if (top + menu.offsetHeight > pageHeight) { top -= menu.offsetHeight + iconRect.height; // Don't go off the top of the page. top = Math.max(top, 0); } // Don't go off the right of the page. if (left + menu.offsetWidth > pageWidth) { left = pageWidth - menu.offsetWidth; // Don't go off the right of the page. left = Math.max(left, 0); } menu.style.top = top + 'px'; menu.style.left = left + 'px'; }; /** * If there is a menu open, close it. */ CCC.Common.closeMenu = function() { var menu = document.getElementById('menu'); if (menu) { menu.parentNode.removeChild(menu); CCC.Common.parentFocus(); } }; /** * When clicked, execute the printed command. * @this {!Element} Clicked element. */ CCC.Common.commandFunction = function() { var command = this.innerText; // Menu commands should never be multi-line. // This should never happen and be caught earlier. // But if it does, fail here rather than be a security hole. if (command.split(/[\r\n]/).length !== 1) { throw new Error('Multi-line command: ' + command); } if (CCC.Common.isConnected) { parent.postMessage({'commands': [command]}, location.origin); } CCC.Common.parentFocus(); }; /** * The user pressed a key with the focus in the world/log frame. * Move focus back to the parent frame and inject the keystroke into the * command area. * @param {!KeyboardEvent} e Keyboard down event. */ CCC.Common.keyDown = function(e) { if (e.key === 'Alt' || e.key === 'Control' || e.key === 'Meta') { // Don't steal focus if the user is pressing a modifier key in preparation // for a cut/copy operation. return; } if (e.ctrlKey || e.altKey || e.metaKey) { // Allow Chrome time to complete a copy before moving focus. setTimeout(CCC.Common.parentFocus, 0); } else { CCC.Common.parentFocus(e); } }; /** * The user pressed a key with the focus in the world/log frame. * Move focus back to the parent frame and inject the keystroke into the * command area. * @param {!KeyboardEvent} e Keyboard press event. */ CCC.Common.keyPress = function(e) { // Allow Firefox time to complete a copy before moving focus. setTimeout(CCC.Common.parentFocus, 0); }; /** * Move focus back to the parent frame. If specified, inject the keystroke * into the command area. * @param {KeyboardEvent} e Optional keyboard event. */ CCC.Common.parentFocus = function(e) { try { var ct = parent.document.getElementById('commandTextarea'); ct.focus(); // Chrome won't type the character in the textarea after a focus change. // For the easy case where the field is empty, just add the character. // TODO: Handle cases where the field is not empty. if (e && e.key.length === 1 && !ct.value.length) { ct.value = e.key; // Firefox will type the character a second time, prevent this. e.preventDefault(); } } catch (e) { // Cross-frame is risky in some browsers. Fallback method. parent.focus(); } }; /** * Helper method for creating SVG elements. * @param {string} name Element's tag name. * @param {!Object} attrs Dictionary of attribute names and values. * @param {!Element=} opt_parent Optional parent on which to append the element. * @return {!SVGElement} Newly created SVG element. */ CCC.Common.createSvgElement = function(name, attrs, opt_parent) { var el = document.createElementNS(CCC.Common.NS, name); for (var key in attrs) { el.setAttribute(key, attrs[key]); } if (opt_parent) { opt_parent.appendChild(el); } return el; }; /** * Given plain text, encode spaces and tabs such that HTML won't crush it. * Does not handle line breaks in any way. * @param {string} text Plain text. * @return {string} HTML with any runs of spaces encoded. */ CCC.Common.escapeSpaces = function(text) { return text.replace(/\t/g, '\u00A0 \u00A0 \u00A0 \u00A0 ') .replace(/ /g, '\u00A0 ').replace(/ /g, '\u00A0 ') .replace(/^ /gm, '\u00A0'); }; /** * Detect URLs in the provided document fragment and replace with links. * @param {!Element} el A DOM element to scan and modify. */ CCC.Common.autoHyperlink = function(el) { var isSvg = el.namespaceURI === CCC.Common.NS; var children = el.childNodes; // This is a live NodeList. for (var i = children.length - 1, child; (child = children[i]); i--) { if (child.nodeType !== Node.TEXT_NODE) { CCC.Common.autoHyperlink(child); continue; } var text = child.nodeValue; var parts = text.split(CCC.Common.autoHyperlink.urlRegex); if (parts.length <= 1) { // No hyperlinks found. continue; } for (var j = 0; j < parts.length; j++) { var part = parts[j]; var m = part.match(CCC.Common.autoHyperlink.urlRegex); // Look up the previous character (if it exists), to weed out: $.www.bar var prevChar = j ? parts[j - 1].substr(-1) : ''; if (prevChar !== '.' && m && m[0] === part) { // This part is a URL. var n = part.match(/[.,!)\]?']+$/); if (n) { // Move any trailing punctuation out of URL. part = part.substring(0, part.length - n[0].length); parts[j + 1] = n[0] + (parts[j + 1] || ''); } var href = part; if (!/^https?:\/\//.test(href)) { href = 'http://' + href; } var link = isSvg ? document.createElementNS(CCC.Common.NS, 'a') : document.createElement('a'); link.setAttribute('href', href); link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); link.appendChild(document.createTextNode(part)); newNode = link; } else { // This part is plain text. var newNode = document.createTextNode(part); } el.insertBefore(newNode, child); } el.removeChild(child); } }; CCC.Common.autoHyperlink.urlRegex = /(\b(?:https?:\/\/|www\.)[-\w.~:\/?#\[\]@!$&'()*+,;=%]+)/i; // Set background colour to differentiate server vs local copy. if (location.hostname === 'localhost') { window.addEventListener('load', function() { document.body.style.backgroundColor = '#ffe'; }); } ================================================ FILE: static/connect/connect.css ================================================ html { height: 100%; } body { color: #444; background-color: #fff; border-left: 2px dashed #fff; border-right: 2px dashed #fff; font-family: 'Roboto Mono', monospace; height: 100%; margin: 0; overflow: hidden; padding: 0; transition: border 0.5s; } body.paused { border-left: 2px dashed #d00; border-right: 2px dashed #d00; } #worldFrame, #logFrame { position: absolute; width: 100%; z-index: -1; border: none; } #mainTable { height: 100%; width: 100%; background: #fff; } tfoot { height: 1%; } #displayCell { text-align: center; } #commandTextarea { color: #000; box-sizing: border-box; background-color: #f8f8f8; font-size: 12pt; height: 42pt; margin-top: 2px; resize: none; width: 100%; } #optionsDiv { background: rgba(255,255,255, 0.8); margin-right: 25px; /* Leave room for the scrollbar. */ position: fixed; right: 0; top: 0; z-index: 9; /* On top of the iframes. */ padding: 0 2px 2px 2px; } .icon { height: 8px; width: 8px; fill: #444; } .jfk-button { border-top-left-radius: 0; border-top-right-radius: 0; border-top: none !important; } #playIcon { fill: #fff; } #worldButton { border-bottom-right-radius: 0; margin-right: 0; } #logButton { border-bottom-left-radius: 0; margin-left: -1px; } #clearButton { margin-right: 0; /* This is the right-most button. */ } ================================================ FILE: static/connect/connect.js ================================================ /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Code City's client. * @author fraser@google.com (Neil Fraser) */ 'use strict'; var CCC = {}; /** * Smallest interval in milliseconds between pings. * @constant */ CCC.MIN_PING_INTERVAL = 1000; /** * Largest interval in milliseconds between pings. * @constant */ CCC.MAX_PING_INTERVAL = 4000; /** * Maximum number of commands saved in history. * @constant */ CCC.MAX_HISTORY_SIZE = 1000; /** * Location to send pings to. * @constant */ CCC.PING_URL = 'ping'; // Properties below this point are not configurable. /** * All the commands the user has sent. */ CCC.commandHistory = []; /** * When browsing the command history, save the current command here. */ CCC.commandTemp = ''; /** * Where in the command history are we browsing? */ CCC.commandHistoryPointer = -1; /** * When was the last time we saw the user? * @type {number} */ CCC.lastActiveTime = Date.now(); /** * Number of lines we think the user has not seen. */ CCC.unreadLines = 0; /** * The index number of the most recent command added to the command buffer. */ CCC.commandNum = 0; /** * Buffer of commands being sent, awaiting acks from server. */ CCC.commandBuffer = []; /** * Bit to switch off local echo when typing passwords. */ CCC.localEcho = true; /** * The index number of the most recent memo received from the server. */ CCC.memoNum = 0; /** * Number of calls to countdown required before launching. */ CCC.countdownValue = 3; /** * XMLHttpRequest currently in flight, or null. * @type {XMLHttpRequest} */ CCC.xhrObject = null; /** * Current length of time between pings. */ CCC.pingInterval = CCC.MIN_PING_INTERVAL; /** * Process ID of next ping to the server. */ CCC.nextPingPid = -1; /** * Flag for only acknowledging new memos after a new memo has arrived. * Saves bandwidth. */ CCC.ackMemoNextPing = true; /** * Buffer to accumulate incoming messages when paused. */ CCC.pauseBuffer = null; /** * Number of consecutive ping errors that have occurred. */ CCC.xhrErrorCounter = 0; /** * Sequence of possible connection states. * @enum {number} */ CCC.ConnectionStates = { NEVER_CONNECTED: 0, CONNECTED: 1, DISCONNECTED: 2 }; /** * Is the client currently connected to the server? * @type {CCC.ConnectionStates} */ CCC.connectionState = CCC.ConnectionStates.NEVER_CONNECTED; /** * Enum for message types to the log/world frames. * Should be identical to CCC.Common.MessageTypes * @enum {string} */ CCC.MessageTypes = { // Messages that may be paused: COMMAND: 'command', // User-generated command echoed. MEMO: 'memo', // Block of text from Code City. CONNECT_MSG: 'connect msg', // User-visible connection message. DISCONNECT_MSG: 'disconnect msg', // User-visible disconnection message. // Messages that may be sent while paused: CONNECTION: 'connection', // Signal change of connection state. CLEAR: 'clear', // Signal to clear history. BLUR: 'blur' // Signal to close pop-up menus. }; /** * Unique queue ID. Identifies this client to the connectServer across * polling connections. Set by the server at startup. * @private */ CCC.queueId_ = SESSION_ID; /** * After every iframe has reported ready, call the initialization. */ CCC.countdown = function() { CCC.countdownValue--; if (!CCC.countdownValue) { CCC.init(); } }; /** * Initialization code called on startup. */ CCC.init = function() { CCC.worldFrame = document.getElementById('worldFrame'); CCC.logFrame = document.getElementById('logFrame'); CCC.displayCell = document.getElementById('displayCell'); CCC.commandTextarea = document.getElementById('commandTextarea'); // When the user closes the tab/window, tell connect server to logout. window.addEventListener('unload', function() { CCC.abortPing(); clearTimeout(CCC.nextPingPid); var sendingJson = { 'q': CCC.queueId_, 'logout': true }; navigator.sendBeacon(CCC.PING_URL, JSON.stringify(sendingJson)); }, false); // When focus returns to this frame from an iframe, go to the command area. // This happens whenever a command link is clicked in an iframe. window.addEventListener('focus', function() { CCC.commandTextarea.focus(); }, false); window.addEventListener('resize', CCC.resize, false); // Firefox needs a 0ms delay before first resize, Chrome does not care. setTimeout(CCC.resize, 0); CCC.commandTextarea.addEventListener('keydown', CCC.keydown, false); CCC.commandTextarea.addEventListener('click', CCC.userActive, false); CCC.commandTextarea.value = ''; // Restore command history from sessionStorage. var sessionHistory = sessionStorage.getItem('commandHistory'); if (sessionHistory) { CCC.commandHistory = JSON.parse(sessionHistory); } var clearButton = document.getElementById('clearButton'); clearButton.addEventListener('click', CCC.clear, false); var pauseButton = document.getElementById('pauseButton'); pauseButton.addEventListener('click', CCC.pause, false); var worldButton = document.getElementById('worldButton'); worldButton.addEventListener('click', CCC.tab.bind(null, 'world'), false); var logButton = document.getElementById('logButton'); logButton.addEventListener('click', CCC.tab.bind(null, 'log'), false); document.body.addEventListener('click', function() { CCC.postToAllFrames({'mode': 'blur'}); }, true); CCC.tab(); CCC.schedulePing(0); // Firefox sometimes caches the disabled value on reload. CCC.commandTextarea.disabled = false; }; /** * Switch between world and log views. * @param {string=} mode Either 'world' or 'log', or undefined. */ CCC.tab = function(mode) { if (!mode) { // Check for a cookie preference. var m = document.cookie.match(/(?:^|;\s*)TAB=(\w+)(?:;|$)/); mode = m ? m[1] : 'world'; } CCC.userActive(); var worldButton = document.getElementById('worldButton'); var logButton = document.getElementById('logButton'); if (mode === 'world') { CCC.worldFrame.style.zIndex = 1; CCC.logFrame.style.zIndex = -1; CCC.commandTextarea.style.fontFamily = '"Patrick Hand", "Comic Sans MS"'; worldButton.classList.add('jfk-checked'); logButton.classList.remove('jfk-checked'); } else { CCC.logFrame.style.zIndex = 1; CCC.worldFrame.style.zIndex = -1; CCC.commandTextarea.style.fontFamily = '"Roboto Mono", monospace'; worldButton.classList.remove('jfk-checked'); logButton.classList.add('jfk-checked'); } // Set a session cookie to preserve this setting. document.cookie = 'TAB=' + mode; CCC.commandTextarea.focus(); }; /** * Clear all history. */ CCC.clear = function() { CCC.userActive(); CCC.commandHistory.length = 0; CCC.commandTemp = ''; CCC.commandHistoryPointer = -1; sessionStorage.removeItem('commandHistory'); if (CCC.pauseBuffer) { var datum; while ((datum = CCC.pauseBuffer[0]) && datum[0] !== CCC.MessageTypes.DISCONNECT_MSG) { CCC.pauseBuffer.shift(); } // Clear the date/time on the 'Reconnect?' line (if it exists). if (datum) { datum[1] = '...'; } } CCC.postToAllFrames({'mode': 'clear'}); CCC.commandTextarea.focus(); }; /** * Toggle pausing of incoming messages. */ CCC.pause = function() { CCC.userActive(); var paused = CCC.pauseBuffer === null; var pauseButton = document.getElementById('pauseButton'); var pauseIcon = document.getElementById('pauseIcon'); var playIcon = document.getElementById('playIcon'); if (paused) { document.body.classList.add('paused'); pauseButton.classList.add('jfk-button-action'); pauseIcon.style.display = 'none'; playIcon.style.display = ''; // Initialize the pause buffer. CCC.pauseBuffer = []; } else { document.body.classList.remove('paused'); pauseButton.classList.remove('jfk-button-action'); pauseIcon.style.display = ''; playIcon.style.display = 'none'; // Fire off all accumulated messages. var buffer = CCC.pauseBuffer; CCC.pauseBuffer = null; for (var args of buffer) { CCC.distributeMessage.apply(null, args); } } CCC.commandTextarea.focus(); }; /** * Reposition the iframes over the placeholder displayCell. * Called when the window changes size. */ CCC.resize = function() { // Compute the absolute coordinates and dimensions of displayCell. var element = CCC.displayCell; var x = 0; var y = 0; do { x += element.offsetLeft; y += element.offsetTop; element = element.offsetParent; } while (element); // Position both iframes over displayCell. CCC.worldFrame.style.left = x + 'px'; CCC.worldFrame.style.top = y + 'px'; CCC.worldFrame.style.width = CCC.displayCell.offsetWidth + 'px'; CCC.worldFrame.style.height = CCC.displayCell.offsetHeight + 'px'; CCC.logFrame.style.left = x + 'px'; CCC.logFrame.style.top = y + 'px'; CCC.logFrame.style.width = CCC.displayCell.offsetWidth + 'px'; CCC.logFrame.style.height = CCC.displayCell.offsetHeight + 'px'; }; /** * Receive messages from our child frames. * @param {!Event} e Incoming message event. */ CCC.receiveMessage = function(e) { var origin = e.origin || e.originalEvent.origin; if (origin !== location.origin) { console.error('Message received by client frame from unknown origin: ' + origin); return; } if (!e.data) { // Shouldn't happen, but harmless. } else if (e.data === 'init') { // A frame is notifying us that it has fully loaded. CCC.countdown(); } else if (e.data['commands'] && e.data['commands'].length) { // User has clicked a command link or command menu. for (var command of e.data['commands']) { CCC.sendCommand(command, true); } } else { console.log('Unknown message received by client frame: ' + e.data); } }; /** * Distribute a line of text to all frames. If paused, hold this message back. * @param {!CCC.MessageTypes} mode Message type. * @param {string} text Text to or from Code City. */ CCC.distributeMessage = function(mode, text) { if (CCC.pauseBuffer) { CCC.pauseBuffer.push(arguments); return; } CCC.postToAllFrames({'mode': mode, 'text': text}); }; /** * Distribute an encoded message to all sub-frames. * @param {!Object} json Encoded message. */ CCC.postToAllFrames = function(json) { CCC.worldFrame.contentWindow.postMessage(json, location.origin); CCC.logFrame.contentWindow.postMessage(json, location.origin); }; /** * Add one command to the outbound queue. * @param {string} commands Text of user's command. May be more than one line. * @param {boolean} echo True if command to be saved in history. */ CCC.sendCommand = function(commands, echo) { CCC.userActive(); commands = commands.split('\n'); // A blank line at the end of a multi-line command is usually accidental. if (commands.length > 1 && !commands[commands.length - 1]) { commands.pop(); } for (var command of commands) { // Add command to list of commands to send to server. CCC.commandBuffer.push(command + '\n'); CCC.commandNum++; // Add command to history. if (echo) { if (!CCC.commandHistory.length || CCC.commandHistory[CCC.commandHistory.length - 1] !== command) { CCC.commandHistory.push(command); } } while (CCC.commandHistory.length > CCC.MAX_HISTORY_SIZE) { CCC.commandHistory.shift(); } // Echo command onscreen. if (echo) { CCC.distributeMessage(CCC.MessageTypes.COMMAND, command); } } CCC.commandTemp = ''; CCC.commandHistoryPointer = -1; sessionStorage.setItem('commandHistory', JSON.stringify(CCC.commandHistory)); // User is sending command, reset the ping to be frequent. CCC.pingInterval = CCC.MIN_PING_INTERVAL; CCC.abortPing(); CCC.doPing(); }; /** * Interrupt any in-flight ping. */ CCC.abortPing = function() { if (CCC.xhrObject) { CCC.xhrObject.abort(); CCC.xhrObject = null; } }; /** * Initiate an XHR network connection. */ CCC.doPing = function() { if (CCC.xhrObject) { // Another ping is currently in progress. return; } // Next ping will be scheduled when this ping completes, // but schedule a contingency ping in case of some thrown error. CCC.schedulePing(CCC.MAX_PING_INTERVAL + 1); var sendingJson = { 'q': CCC.queueId_ }; if (CCC.ackMemoNextPing) { sendingJson['ackMemoNum'] = CCC.memoNum; } if (CCC.commandBuffer.length) { sendingJson['cmdNum'] = CCC.commandNum; sendingJson['cmds'] = CCC.commandBuffer; } // XMLHttpRequest with timeout works in IE8 or better. var req = new XMLHttpRequest(); req.onload = CCC.xhrLoaded; req.ontimeout = CCC.xhrError; req.onerror = CCC.xhrError; req.open('POST', CCC.PING_URL, true); req.timeout = CCC.MAX_PING_INTERVAL; // Time in milliseconds. req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); req.send(JSON.stringify(sendingJson)); CCC.xhrObject = req; // Let the ping interval creep up. CCC.pingInterval = Math.min(CCC.MAX_PING_INTERVAL, CCC.pingInterval * 1.1); }; /** * Error handler for XHR request. * @this {!XMLHttpRequest} */ CCC.xhrError = function() { CCC.xhrErrorCounter++; console.warn('Connection error: ' + CCC.xhrErrorCounter); CCC.xhrObject = null; if (CCC.xhrErrorCounter >= 8) { // Too many errors. Drop the connection. CCC.terminate(); return; } else { CCC.schedulePing(CCC.pingInterval); } }; /** * Callback function for XHR request. * Check network response was ok, then call CCC.parse. * @this {!XMLHttpRequest} */ CCC.xhrLoaded = function() { CCC.xhrObject = null; // Only if "OK". if (this.status === 200) { try { var json = JSON.parse(this.responseText); } catch (e) { console.warn('Invalid JSON: ' + this.responseText); CCC.xhrError(); return; } CCC.xhrErrorCounter = 0; CCC.parse(json); } else if (this.status === 410) { console.warn('Session closed.'); CCC.terminate(); return; } else if (this.status) { console.warn('Connection error code: ' + this.status); CCC.xhrError(); return; } CCC.schedulePing(CCC.pingInterval); }; /** * Received an error from the server, indicating that our connection is closed. */ CCC.terminate = function() { CCC.connectionState = CCC.ConnectionStates.DISCONNECTED; clearTimeout(CCC.nextPingPid); // Send immediate signal to enter readonly-mode for all frames. CCC.postToAllFrames({'mode': CCC.MessageTypes.CONNECTION, 'state': false}); // Send user-visible message (which might be delayed due to pause). CCC.distributeMessage(CCC.MessageTypes.DISCONNECT_MSG, CCC.currentDateString()); }; /** * Parse the response from the server. * @param {!Object} receivedJson Server data. */ CCC.parse = function(receivedJson) { if (CCC.connectionState === CCC.ConnectionStates.DISCONNECTED) { throw new Error('JSON received after disconnection: ' + receivedJson); } else if (CCC.connectionState === CCC.ConnectionStates.NEVER_CONNECTED) { CCC.postToAllFrames({'mode': CCC.MessageTypes.CONNECTION, 'state': true}); CCC.distributeMessage(CCC.MessageTypes.CONNECT_MSG, CCC.currentDateString()); CCC.connectionState = CCC.ConnectionStates.CONNECTED; } var ackCmdNum = receivedJson['ackCmdNum']; var memoNum = receivedJson['memoNum']; var memos = receivedJson['memos']; if (typeof ackCmdNum === 'number') { if (ackCmdNum > CCC.commandNum) { console.error('Server acks ' + ackCmdNum + ', but CCC.commandNum is only ' + CCC.commandNum); CCC.terminate(); } // Server acknowledges receipt of commands. // Remove them from the output list. CCC.commandBuffer.splice(0, CCC.commandBuffer.length + ackCmdNum - CCC.commandNum); } if (typeof memoNum === 'number') { // Server sent messages. Increase client's index for acknowledgment. var currentIndex = memoNum - memos.length + 1; for (var memo of memos) { if (currentIndex > CCC.memoNum) { CCC.memoNum = currentIndex; CCC.distributeMessage(CCC.MessageTypes.MEMO, memo); // Reduce ping interval. CCC.pingInterval = Math.max(CCC.MIN_PING_INTERVAL, CCC.pingInterval * 0.8); } currentIndex++; } CCC.setUnreadLines(CCC.unreadLines + memos.length); CCC.ackMemoNextPing = true; } else { CCC.ackMemoNextPing = false; } }; /** * Schedule the next ping. * @param {number} ms Milliseconds. */ CCC.schedulePing = function(ms) { clearTimeout(CCC.nextPingPid); CCC.nextPingPid = setTimeout(CCC.doPing, ms); }; /** * Monitor the user's keystrokes in the command text area. * @param {!Event} e Keydown event. */ CCC.keydown = function(e) { CCC.userActive(); if (!e.shiftKey && e.key === 'Enter') { // Enter if (CCC.connectionState === CCC.ConnectionStates.CONNECTED) { CCC.sendCommand(CCC.commandTextarea.value, CCC.localEcho); // Clear the textarea. CCC.commandTextarea.value = ''; CCC.commandHistoryPointer = -1; CCC.commandTemp = ''; } else { // Pulse the command text area to indicate disconnection. CCC.commandTextarea.style.transition = ''; CCC.commandTextarea.style.backgroundColor = '#f88'; // Wait 0.1 seconds for the browser to process the above style changes. setTimeout(function() { CCC.commandTextarea.style.transition = 'background-color 1s'; CCC.commandTextarea.style.backgroundColor = ''; }, 100); } e.preventDefault(); // Don't add an enter after the clear. } else if ((!e.shiftKey && e.key === 'ArrowUp') || (e.ctrlKey && e.key === 'p')) { // Up or Ctrl-P if (!CCC.commandHistory.length) { return; } if (CCC.commandHistoryPointer === -1) { CCC.commandTemp = CCC.commandTextarea.value; CCC.commandHistoryPointer = CCC.commandHistory.length - 1; CCC.commandTextarea.value = CCC.commandHistory[CCC.commandHistoryPointer]; } else if (CCC.commandHistoryPointer > 0) { CCC.commandHistoryPointer--; CCC.commandTextarea.value = CCC.commandHistory[CCC.commandHistoryPointer]; } e.preventDefault(); // Don't move the cursor to start after change. } else if ((!e.shiftKey && e.key === 'ArrowDown') || (e.ctrlKey && e.key === 'n')) { // Down or Ctrl-N if (!CCC.commandHistory.length) { return; } if (CCC.commandHistoryPointer === CCC.commandHistory.length - 1) { CCC.commandHistoryPointer = -1; CCC.commandTextarea.value = CCC.commandTemp; CCC.commandTemp = ''; } else if (CCC.commandHistoryPointer >= 0) { CCC.commandHistoryPointer++; CCC.commandTextarea.value = CCC.commandHistory[CCC.commandHistoryPointer]; } } else if (e.key === 'Tab') { // Tab e.preventDefault(); // Don't change the focus. if (!CCC.commandHistory.length) { return; } var chp = CCC.commandHistoryPointer; if (chp === -1) { // Save the current value. CCC.commandTemp = CCC.commandTextarea.value; } var reverse = e.shiftKey; for (var i = 0; i <= CCC.commandHistory.length; i++) { // Loop through the entire history, and the current value. chp += reverse ? 1 : -1; if (chp < -1) { // Wrap up. chp = CCC.commandHistory.length - 1; } else if (chp >= CCC.commandHistory.length) { // Wrap down. chp = -1; } if (chp === -1) { // The current value is always a match. CCC.commandHistoryPointer = -1; CCC.commandTextarea.value = CCC.commandTemp; CCC.commandTemp = ''; break; } else if (CCC.commandHistory[chp].toLowerCase() .startsWith(CCC.commandTemp.toLowerCase())) { CCC.commandHistoryPointer = chp; CCC.commandTextarea.value = CCC.commandHistory[chp]; break; } } } else if (e.key.length === 1) { CCC.commandHistoryPointer = -1; CCC.commandTemp = ''; } // Delete the placeholder text as soon as the user types anything. CCC.commandTextarea.placeholder = ''; }; /** * The user is active. * Reset the last active time, and clear the notification of unread lines. */ CCC.userActive = function() { CCC.lastActiveTime = Date.now(); CCC.setUnreadLines(0); }; /** * Change the number of unread lines, as notified in the title. * @param {number} n Number of unread lines. */ CCC.setUnreadLines = function(n) { CCC.unreadLines = n; var title = document.title; // Strip off old number. title = title.replace(/ \(\d+\)$/, ''); // Add new number if user hasn't been seen in 10 seconds. if (n && CCC.lastActiveTime + 10000 < Date.now()) { title += ' (' + n + ')'; } document.title = title; }; /** * Return a local date/time in 'yyyy-mm-dd hh:mm:ss' format. * @return {string} Current date/time. */ CCC.currentDateString = function() { var now = new Date(); var dy = now.getFullYear(); var dm = ('0' + (now.getMonth() + 1)).slice(-2); var dd = ('0' + now.getDate()).slice(-2); var th = ('0' + now.getHours()).slice(-2); var tm = ('0' + now.getMinutes()).slice(-2); var ts = ('0' + now.getSeconds()).slice(-2); return dy + '-' + dm + '-' + dd + ' ' + th + ':' + tm + ':' + ts; }; window.addEventListener('message', CCC.receiveMessage, false); window.addEventListener('load', CCC.countdown, false); ================================================ FILE: static/connect/log.css ================================================ body { font-family: 'Roboto Mono', monospace; } #scrollDiv { padding-left: 15px; } #scrollDiv>div:first-child { /* Add whitespace above the first line so that the client buttons don't obscure any content. */ margin-top: 2em; } .zippySpan { cursor: pointer; margin-left: -15px; position: absolute; } .zippySpan::before { content: '▸ '; } .zippySpan.open::before { content: '▾ '; } .zippySpan:hover { color: #d00; } pre { font-family: 'Roboto Mono', monospace; margin-bottom: 0; margin-top: 0; } .commandDiv { background: #ffc; } .sceneTitle { font-weight: bold; } .openIcon { fill: #444; width: 1.5ex; } .openIcon:hover { fill: #d00; } .connectDiv { background-color: #0a0; } .disconnectDiv { background-color: #d00; } .connectDiv, .disconnectDiv { color: #fff; padding: 0 15px; margin-left: -15px; } .connectDiv>.date, .disconnectDiv>.date { float: right; } a.reconnect { color: #fff; cursor: pointer; margin-left: 1em; text-decoration: underline dotted; user-select: none; } a.reconnect:hover { opacity: .9; } ================================================ FILE: static/connect/log.js ================================================ /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Log frame of Code City's client. * @author fraser@google.com (Neil Fraser) */ 'use strict'; CCC.Log = {}; /** * Maximum number of lines saved in history. */ CCC.Log.maxHistorySize = 10000; /** * Allowed protocols for iframe links. * Probably best not to allow 'javascript:' URIs due to security reasons. */ CCC.Log.protocolRegex = /^((https?|ftp|gopher|data|irc|telnet|news|wais|file|nntp|mailto):|\/)/; /** * Record of the user's name. Used for displaying 2nd person vs 3rd person * messages. E.g.: You say, "Hello." -vs- Max says, "Hello." * @type {string=} */ CCC.Log.userName = undefined; /** * Initialization code called on startup. */ CCC.Log.init = function() { CCC.Common.init(); CCC.Log.scrollDiv = document.getElementById('scrollDiv'); window.addEventListener('resize', CCC.Log.scrollToBottom, false); // Lazy-load prettify library. setTimeout(CCC.Log.importPrettify, 1); }; /** * Load the Prettify CSS and JavaScript. */ CCC.Log.importPrettify = function() { // // var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = STATIC_URL + 'connect/prettify.css'; document.head.appendChild(link); var script = document.createElement('script'); script.src = STATIC_URL + 'connect/prettify.js'; document.head.appendChild(script); }; /** * Receive messages from our parent frame. * @param {!Event} e Incoming message event. */ CCC.Log.receiveMessage = function(e) { var data = CCC.Common.verifyMessage(e); if (!data) { return; } var mode = data['mode']; if (mode === CCC.Common.MessageTypes.CLEAR) { // Clear all lines, except for the 'Reconnect?' line (if it exists). var div; while ((div = CCC.Log.scrollDiv.firstChild) && div.className !== 'disconnectDiv') { CCC.Log.scrollDiv.removeChild(div); } // Clear the date/time on the 'Reconnect?' line (if it exists). if (div) { var dates = div.getElementsByClassName('date'); if (dates[0]) { dates[0].textContent = '...'; } } } else if (mode === CCC.Common.MessageTypes.BLUR) { CCC.Common.closeMenu(); } else if (mode === CCC.Common.MessageTypes.COMMAND) { var text = data['text']; var div = CCC.Log.textToHtml(text); div.className = 'commandDiv'; CCC.Log.appendRow(div); } else if (mode === CCC.Common.MessageTypes.CONNECTION) { CCC.Common.setConnected(data['state']); } else if (mode === CCC.Common.MessageTypes.CONNECT_MSG) { // Notify the user of the connection. var div = CCC.Log.connectDiv(true, data['text']); CCC.Log.appendRow(div); } else if (mode === CCC.Common.MessageTypes.DISCONNECT_MSG) { // Notify the user of the disconnection. var div = CCC.Log.connectDiv(false, data['text']); CCC.Log.appendRow(div); } else if (mode === CCC.Common.MessageTypes.MEMO) { var text = data['text']; try { var json = JSON.parse(text); } catch (e) { // Not valid JSON, treat as string literal. var div = CCC.Log.textToHtml(text); CCC.Log.appendRow(div); return; } CCC.Log.addJson(json); } }; /** * Create a div notifying the user of connection or disconnection. * @param {boolean} isConnected New connection state. * @param {string} date Date/time of connection/disconnection. * @return {!Element} HTML div element. */ CCC.Log.connectDiv = function(isConnected, date) { var div = document.createElement('div'); div.className = (isConnected ? 'connectDiv' : 'disconnectDiv'); var span = document.createElement('span'); span.className = 'date'; span.appendChild(document.createTextNode(date)); div.appendChild(span); div.appendChild(CCC.Log.getTemplate(isConnected ? 'connectedTemplate' : 'disconnectedTemplate')); if (!isConnected) { var link = document.createElement('a'); link.className = 'reconnect'; link.appendChild(CCC.Log.getTemplate('reconnectTemplate')); div.appendChild(link); link.addEventListener('click', parent.location.reload.bind(parent.location)); } return div; }; /** * Convert plain text to HTML. Preserve spaces and line breaks. * @param {string} text Line of text. * @return {!Element} HTML div element. */ CCC.Log.textToHtml = function(text) { text = CCC.Common.escapeSpaces(text); var lines = text.split('\n'); var div = document.createElement('div'); for (var i = 0; i < lines.length; i++) { if (i !== 0) { div.appendChild(document.createElement('br')); } div.appendChild(document.createTextNode(lines[i])); } return div; }; /** * Add one row of JSON to the log. * @param {!Object} json JSON structure. */ CCC.Log.addJson = function(json) { var rendered = CCC.Log.renderJson(json); if (rendered === null) { return; // Unrequested scene. } var pre = document.createElement('pre'); pre.textContent = JSON.stringify(json, null, 2); if (typeof prettyPrint === 'function') { pre.className = 'prettyprint lang-js'; var div = document.createElement('div'); div.appendChild(pre); prettyPrint(null, div); } if (rendered) { if (typeof rendered === 'string') { var div = CCC.Log.textToHtml(rendered); } else { var div = rendered; } div.className = 'zippyDiv'; var span = document.createElement('span'); span.className = 'zippySpan'; span.addEventListener('click', CCC.Log.toggleZippy); div.insertBefore(span, div.firstChild); pre.style.display = 'none'; div.appendChild(pre); CCC.Log.appendRow(div); } else { CCC.Log.appendRow(pre); } }; CCC.Log.toggleZippy = function(e) { var zippy = e.target; var pre = zippy.parentNode.lastChild; if (!zippy.className.includes(' open')) { zippy.className += ' open'; pre.style.display = 'block'; if (!zippy.parentNode.nextSibling) { // Opening a zippy at the bottom of the page. Scroll down. CCC.Log.scrollToBottom(); } } else { zippy.className = zippy.className.replace(' open', ''); pre.style.display = 'none'; } }; /** * Attempt to render the JSON as a plain text version. * @param {!Object} json JSON object. * @return {Element} Div of text, or null if not to be visualized, * or undefined if unknown/corrupt format. */ CCC.Log.renderJson = function(json) { switch (json.type) { case 'iframe': // {type: "iframe", url: "https://example.com/foo", alt: "Alt text"} var src = json.url; var m = src.match(CCC.Log.protocolRegex); if (!m) { return undefined; // Invalid src attribute. } var div = document.createElement('div'); var text = json.alt || src; div.appendChild(document.createTextNode(text)); div.appendChild(CCC.Log.openIcon(src)); return div; case 'html': // {type: "html", htmlText: "
Arbitrary HTML
"} var dom = CCC.Common.parser.parseFromString(json.htmlText, 'text/html'); if (dom.body) { var div = document.createElement('div'); CCC.Log.renderHtmltext(div, dom.body); CCC.Common.autoHyperlink(div); return div; } return undefined; // Illegal HTML. case 'scene': //{ // type: "scene", // requested: true, // user: "Max", // where: "Hangout", // description: "The lights are dim and blah blah blah...", // svgText: "...", // contents: [ // { // type: "user", // what: "Max", // svgText: "...", // cmds: ["look Max", "kick Max"] // }, // { // type: "thing", // what: "clock", // svgText: "...", // cmds: ["look clock"] // } // ] //} if (!json.requested) { return null; // Do not display this scene update in the log. } if (json.user) { // Record the user name if present. CCC.Log.userName = json.user; } var objects = []; var users = []; if (json.contents) { for (var content of json.contents) { if (content.type === 'user' && CCC.Log.userName === content.what) { continue; // Don't show the current user. } var df = document.createDocumentFragment(); df.appendChild(document.createTextNode(content.what)); if (content.cmds) { var icon = CCC.Common.newMenuIcon(content.cmds); if (icon) { icon.addEventListener('click', CCC.Common.openMenu); df.appendChild(icon); } } (content.type === 'user' ? users : objects).push(df); } } var div = document.createElement('div'); if (json.where) { var titleDiv = document.createElement('div'); titleDiv.className = 'sceneTitle'; titleDiv.appendChild(document.createTextNode(json.where)); div.appendChild(titleDiv); } if (json.description) { var descriptionDiv = CCC.Log.textToHtml(json.description); CCC.Common.autoHyperlink(descriptionDiv); div.appendChild(descriptionDiv); } if (objects.length) { var objectsDiv = document.createElement('div'); if (objects.length === 1) { objectsDiv.appendChild(CCC.Log.getTemplate( 'roomObjectTemplate', objects[0])); } else if (objects.length > 1) { objectsDiv.appendChild(CCC.Log.getTemplate( 'roomObjectsTemplate', CCC.Log.naturalList(objects))); } div.appendChild(objectsDiv); } if (users.length) { var usersDiv = document.createElement('div'); if (users.length === 1) { usersDiv.appendChild(CCC.Log.getTemplate( 'roomUserTemplate', users[0])); } else if (users.length > 1) { usersDiv.appendChild(CCC.Log.getTemplate( 'roomUsersTemplate', CCC.Log.naturalList(users))); } div.appendChild(usersDiv); } return div; case 'say': // {type: "say", text: "Welcome"} // {type: "say", source: "Max", where: "Hangout", text: "Hello world."} // {type: "say", source: "Cat", where: "Hangout", text: "Meow."} // Fall through. case 'think': // {type: "think", text: "Don't be evil."} // {type: "think", source: "Max", where: "Hangout", text: "I'm hungry."} // {type: "think", source: "Cat", where: "Hangout", text: "I'm evil."} var text = CCC.Common.escapeSpaces(json.text); if (json.type === 'think') { var type = 'think'; } else { var lastLetter = text.trim().slice(-1); var type = (lastLetter === '?') ? 'ask' : ((lastLetter === '!') ? 'exclaim' : 'say'); } if (json.source && CCC.Log.userName === json.source) { var fragment = CCC.Log.getTemplate(type + 'SelfTemplate', text); } else { var who = json.source || CCC.Log.getTemplate('unknownTemplate'); var fragment = CCC.Log.getTemplate(type + 'Template', who, text); } CCC.Common.autoHyperlink(fragment); var div = document.createElement('div'); div.appendChild(fragment); return div; case 'narrate': // {type: "narrate", text: "Command not recognized."} // {type: "narrate", where: "Hangout", text: "Hangout is dark."} // {type: "narrate", source: "Max", where: "Hangout", text: "Max smiles."} // {type: "narrate", source: "Cat", where: "Hangout", text: "Cat meows."} var div = document.createElement('div'); var text = json.text; if (json.source) { text = json.source + ': ' + text; } div.appendChild(document.createTextNode(text)); CCC.Common.autoHyperlink(div); return div; case 'link': // {type: "link", href: "https://example.com/"} var div = document.createElement('div'); var a = document.createElement('a'); a.href = json.href; a.target = '_blank'; a.appendChild(document.createTextNode(json.href)); div.appendChild(a); // Note: this opens the link in a new tab regardless of whether the user // is in world or log view. var success = window.open(json.href); if (!success) { alert('Your browser has blocked the opening of the page you requested.\n' + 'Please allow pop-ups on this domain. ✓️'); } return div; } // Unknown XML. return undefined; }; /** * Create an icon that links to a page in a new window. * @param {string} src URL of link to open. * @return {!Element} DOM element of newly-created link and icon. */ CCC.Log.openIcon = function(src) { // // // // // // Icon artwork sourced from https://icons.googleplex.com/ var link = document.createElement('a'); link.href = src; link.target = '_blank'; link.rel = 'noopener noreferrer'; var svg = CCC.Common.createSvgElement('svg', {'class': 'openIcon', 'viewBox': '0 3 24 24'}, link); CCC.Common.createSvgElement('path', {'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); return link; }; /** * Create a mostly text-based representation of the provided DOM. * @param {!Element} div Div element to append content to. * @param {!Node} node DOM to walk. */ CCC.Log.renderHtmltext = function(div, node) { if (node.nodeType === Node.ELEMENT_NODE) { // Element. if (node.tagName === 'svg') { // XML tagNames are lowercase. return; // No text content of this tag should be rendered. } if (node.tagName === 'CMDS') { // HTML tagNames are uppercase. var icon = CCC.Common.newMenuIcon(node); if (icon) { icon.addEventListener('click', CCC.Common.openMenu); div.appendChild(icon); } return; } if (node.tagName === 'CMD') { // HTML tagNames are uppercase. var cmdText = node.innerText; var a = document.createElement('a'); a.className = 'command'; a.appendChild(document.createTextNode(cmdText)); a.addEventListener('click', CCC.Common.commandFunction, false); div.appendChild(a); return; } for (var child of node.childNodes) { CCC.Log.renderHtmltext(div, child); } if (CCC.Log.renderHtmltext.BLOCK_NAMES.has(node.tagName)) { // Add a
tag, but not if there's already one. var lastTag = div.lastChild; while (lastTag && lastTag.nodeType !== Node.ELEMENT_NODE) { if (lastTag.nodeType === Node.TEXT_NODE && lastTag.nodeValue.trim()) { // Found text that's not whitespace. Bail. lastTag = null; } else { // Nothing printable found so far, keep walking up looking for a
. lastTag = lastTag.previousSibling; } } if (div.hasChildNodes() && (!lastTag || lastTag.tagName !== 'BR')) { div.appendChild(document.createElement('br')); } } } else if (node.nodeType === Node.TEXT_NODE) { // Text node. div.appendChild(document.createTextNode(node.data)); } }; /** * List of elements that are blocks, rather than inline. */ CCC.Log.renderHtmltext.BLOCK_NAMES = new Set([ 'ADDRESS', 'BLOCKQUOTE', 'BR', 'DIV', 'DL', 'DT', 'FIELDSET', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HR', 'LI', 'OL', 'P', 'PRE', 'TABLE', 'TR', 'UL', ]); /** * Gets the template with the given key from the document. * @param {string} key The key of the document element. * @param {...string|DocumentFragment} var_args Optional substitutions for %1... * @return {!DocumentFragment} A document fragment containing the text. */ CCC.Log.getTemplate = function(key, var_args) { var element = document.getElementById(key); if (!element) { throw new Error('Unknown template ' + key); } var text = element.textContent; var parts = text.split(/(%\d)/); var df = document.createDocumentFragment(); // Inject any substitutions. for (var part of parts) { var m = part.match(/^%(\d)$/); if (m) { var inject = arguments[m[1]]; if (typeof inject === 'string') { inject = document.createTextNode(inject); } df.appendChild(inject); } else if (part) { df.appendChild(document.createTextNode(part)); } } return df; }; /** * Make a natural language list. Don't use Oxford comma due to lack of plurals. * ['apple', 'banana', 'cherry'] -> 'apple, banana and cherry' * @param {!Array.} list List of items to concatenate. * @return {!DocumentFragment} A document fragment containing the text. */ CCC.Log.naturalList = function(list) { if (list.length === 1) { return list[0]; } var df = document.createDocumentFragment(); for (var i = 0; i < list.length - 1; i++) { if (i) { df.appendChild(document.createTextNode(', ')); } df.appendChild(list[i]); } df.appendChild(document.createTextNode(' ')); df.appendChild(CCC.Log.getTemplate('andTemplate')); df.appendChild(document.createTextNode(' ')); df.appendChild(list[list.length - 1]); return df; }; /** * Add one row to the log. Scroll page to the bottom. * @param {!Element} element HTML element to add. */ CCC.Log.appendRow = function(element) { var div = CCC.Log.scrollDiv; div.appendChild(element); if (div.childNodes.length > CCC.Log.maxHistorySize) { div.removeChild(document.body.firstChild); } CCC.Log.scrollToBottom(); }; /** * Scroll the log to the bottom. */ CCC.Log.scrollToBottom = function() { CCC.Log.scrollDiv.scrollTop = CCC.Log.scrollDiv.scrollHeight; CCC.Log.scrollDiv.scrollLeft = 0; }; if (!window.TEST) { window.addEventListener('message', CCC.Log.receiveMessage, false); window.addEventListener('load', CCC.Log.init, false); } ================================================ FILE: static/connect/prettify.css ================================================ .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} ================================================ FILE: static/connect/prettify.js ================================================ !function(){/* Copyright 2006 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ window.PR_SHOULD_USE_CONTINUATION=!0; (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= [];var a="^"===b[0],c=["["];a&&c.push("^");for(var a=a?1:0,g=b.length;ak||122k||90k||122h[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/,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|\\/=?|::?|<>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*("+ ("/(?=[^/*"+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, null],["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))&& a.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); for(var c=[m],p=0;p=+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=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"], F=[[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"], O=[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"], F=[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"], S=/^(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",/^[^]*(?:>|$)/],["com",/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\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, "\"'"]],[["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, hashComments:!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", hashComments:!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, regexLiterals:!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="
"+a+"
"; b=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 Test harness for Code City: Client

Test harness for Code City: Connect

================================================ FILE: static/connect/tests/test.js ================================================ /** * @license * Copyright 2019 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Tests for Integrated Development Environment for Code City. * @author fraser@google.com (Neil Fraser) */ 'use strict'; // common.js function testCommonEscapeSpaces() { // Escape strings with whitespace into non-collapsable HTML strings. assertEquals('a\u00A0 \u00A0 b', CCC.Common.escapeSpaces('a b')); assertEquals('\u00A0a\u00A0 \u00A0 \u00A0 \u00A0 b', CCC.Common.escapeSpaces(' a\tb')); } // log.js function testLogGetTemplate() { // Fetch a template string from HTML // %1 kicks %2. var span = document.createElement('span'); span.id = 'testTemplate'; span.innerHTML = '%1 kicks %2.'; document.body.appendChild(span); try { var df = CCC.Log.getTemplate(span.id, 'Max', 'Fido'); } finally { document.body.removeChild(span); } // Render the DocumentFragment. var div = document.createElement('div'); div.appendChild(df); assertEquals('Max kicks Fido.', div.innerHTML); } // world.js function testWorldGetTemplate() { // Fetch a template string from HTML // Today is a good day to die. var span = document.createElement('span'); span.id = 'testTemplate'; span.innerHTML = 'Today is a good day to die.'; document.body.appendChild(span); try { var text = CCC.World.getTemplate(span.id); } finally { document.body.removeChild(span); } assertEquals('Today is a good day to die.', text); } function testWorldWrap() { var svg = CCC.Common.createSvgElement('svg', {'xmlns:xlink': 'http://www.w3.org/1999/xlink'}, document.body); svg.scaledHeight_ = 100; svg.scaledWidth_ = 200; try { var wrapped = CCC.World.wrap(svg, 'Alpha Bravo Charlie Delta Echo', 10, 100000); } finally { document.body.removeChild(svg); } assertEquals('Alpha \nBravo \nCharlie \nDelta \nEcho', wrapped); } ================================================ FILE: static/connect/world.css ================================================ body { font-family: 'Patrick Hand', 'Comic Sans MS'; margin: 0; overflow: hidden; } .historyPanel { border: 2px solid #444; border-radius: 2px; display: inline-block; margin: 5px 5px 0 5px; overflow: hidden; } #panoramaDiv { border: 2px solid #444; border-radius: 2px; height: 295px; margin: 5px 6px 0 5px; overflow: hidden; } #iframeStorage>iframe { border: none; left: 0; position: absolute; top: 0; } .iframeClose:hover { opacity: 1; } .iframeClose { cursor: pointer; position: absolute; margin-left: -16px; margin-top: -5px; opacity: .7; z-index: 1; } .iframeRelaunch { cursor: pointer; } .iframeRelaunch:hover>text { fill: #f00; } .iframeRelaunch>rect { fill: #222; } .iframeRelaunch>text { fill: #ccc; text-anchor: middle; alignment-baseline: middle; } .iframeRelaunch:hover>text { fill: #fff; } .iframeRelaunch:hover>rect { fill: #000; } .htmlPanel { height: 100%; overflow: auto; } .connectDiv { background-color: #0a0; } .disconnectDiv { background-color: #d00; } .connectDiv, .disconnectDiv { color: #fff; text-align: center; } .connectionIcon { display: block; height: 48px; margin-left: auto; margin-top: 80px; margin-right: auto; opacity: .7; width: 48px; } .connectionIcon[src$="#reload"]:hover { cursor: pointer; opacity: 1; } .systemTime { margin-top: 60px; text-align: center; } .sceneBackground { stroke: #888; } .bubbleBG { fill: #000; stroke: none; } .bubbleFG { fill: #fff; stroke: none; } .bubbleArrow { fill: #fff; } g.say { text-anchor: middle; } a.disabled { color: #444; cursor: no-drop; text-decoration: underline dotted #444; } ================================================ FILE: static/connect/world.js ================================================ /** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview World frame of Code City's client. * @author fraser@google.com (Neil Fraser) */ 'use strict'; CCC.World = {}; /** * Maximum number of messages saved in history. */ CCC.World.maxHistorySize = 10000; /** * Messages in the history panels. */ CCC.World.historyMessages = []; /** * Messages in the panorama panel. */ CCC.World.panoramaMessages = []; /** * Height of history panels. * @constant */ CCC.World.panelHeight = 256; /** * Width of planned history panels. */ CCC.World.panelWidths = []; /** * Width of panel borders (must match CSS). * @constant */ CCC.World.panelBorder = 2; /** * Div containing a partial row of history panels (null if new row needed). * @type {Element} */ CCC.World.historyRow = null; /** * PID of rate-limiter for resize events. */ CCC.World.resizePid = 0; /** * The last recorded screen width. Used to determine if a resize event resulted * in a change of width. */ CCC.World.lastWidth = NaN; /** * SVG scratchpad for rendering potential history panels. * @type {Element} */ CCC.World.scratchHistory = null; /** * SVG scratchpad for rendering potential panorama panels. * @type {Element} */ CCC.World.scratchPanorama = null; /** * Width of a scrollbar. Computed once at startup. */ CCC.World.scrollBarWidth = NaN; /** * Record of the current scene. * @type {Object} */ CCC.World.scene = null; /** * Initialization code called on startup. */ CCC.World.init = function() { CCC.Common.init(); CCC.World.scrollDiv = document.getElementById('scrollDiv'); CCC.World.panoramaDiv = document.getElementById('panoramaDiv'); CCC.World.scrollBarWidth = CCC.World.getScrollBarWidth(); CCC.World.scene = {}; // Blank scene. delete CCC.World.getScrollBarWidth; // Free memory. window.addEventListener('resize', CCC.World.resizeSoon, false); }; /** * Receive messages from our parent frame. * @param {!Event} e Incoming message event. */ CCC.World.receiveMessage = function(e) { var data = CCC.Common.verifyMessage(e); if (!data) { return; } var mode = data['mode']; var text = data['text']; if (mode === CCC.Common.MessageTypes.CLEAR) { // Clear all content, except for the 'Reconnect?' panel (if it exists). document.getElementById('iframeStorage').innerHTML = ''; CCC.World.historyMessages.length = 0; var firstPanoramaMessage = CCC.World.panoramaMessages[0]; if (firstPanoramaMessage && firstPanoramaMessage.type === 'connected' && !firstPanoramaMessage.isConnected) { // Clear the date/time on the 'Reconnect?' panel (if it exists). firstPanoramaMessage.time = '...'; } else { CCC.World.panoramaMessages.length = 0; } CCC.World.removeNode(CCC.World.scratchHistory); CCC.World.removeNode(CCC.World.scratchPanorama); var scene = CCC.World.scene; // Save the scene. CCC.World.renderHistory(); CCC.World.scene = scene; // Restore the scene. } else if (mode === CCC.Common.MessageTypes.BLUR) { CCC.Common.closeMenu(); } else if (mode === CCC.Common.MessageTypes.CONNECTION) { CCC.Common.setConnected(data['state']); } else if (mode === CCC.Common.MessageTypes.CONNECT_MSG) { // Notify the user of the connection. CCC.World.renderMessage({type: 'connected', isConnected: true, time: data['text']}); } else if (mode === CCC.Common.MessageTypes.DISCONNECT_MSG) { // Notify the user of the disconnection. CCC.World.renderMessage({type: 'connected', isConnected: false, time: data['text']}); } else if (mode === CCC.Common.MessageTypes.MEMO) { try { var msg = JSON.parse(text); } catch (e) { // Not valid JSON, treat as string literal. msg = {type: 'narrate', text: text}; } CCC.World.preprocessMessage(msg); CCC.World.renderMessage(msg); } }; /** * Parse the message and deal with any chunks that need one-time processing. * @param {*} msg JSON structure, or component thereof. */ CCC.World.preprocessMessage = function(msg) { if (Array.isArray(msg)) { for (var singleMsg of msg) { CCC.World.preprocessMessage(singleMsg); } return; } if (typeof msg === 'object' && msg !== null) { for (var prop in msg) { CCC.World.preprocessMessage(msg[prop]); } // Text too large for a bubble should be in an HTML frame. if ((msg.type === 'say' || msg.type === 'think' || msg.type === 'narrate') && msg.text.length > 800) { // TODO: Render say/think text in log form: Bob says, "Blah blah..." var text = msg.text; // Transform this memo into an HTML frame. for (prop in msg) { delete msg[prop]; } msg.type = 'html'; text = CCC.Common.escapeSpaces(text.replace(/&/g, '&') .replace(//g, '>').replace(/\n/g, '
')); msg.htmlText = text; } // Find all stringified SVG props and replace them with actual SVG props. if ('svgText' in msg) { var svgDom = CCC.World.stringToSvg(msg.svgText); if (svgDom) { msg.svgDom = svgDom; } delete msg.svgText; } // Find all stringified HTML props and replace them with actual HTML props. if ('htmlText' in msg) { var htmlDom = CCC.World.stringToHtml(msg.htmlText); if (htmlDom) { msg.htmlDom = htmlDom; } delete msg.htmlText; } // Find all iframes and create DOM elements for them. if (msg.type === 'iframe') { // {type: "iframe", url: "https://example.com/foo", alt: "Alt text"} msg.iframeId = CCC.World.createIframe(msg.url); } // Move the current user to the start of the room contents list. if (msg.type === 'scene' && msg.user && msg.contents) { for (var i = 1, content; (content = msg.contents[i]); i++) { if (content.type === 'user' && content.what === msg.user) { msg.contents.unshift(msg.contents.splice(i, 1)[0]); } } } } }; /** * Render a message to the panorama panel, optionally triggering a history push. * @param {!Object} memo JSON structure. */ CCC.World.renderMessage = function(memo) { if (memo.type === 'link') { // {type: "link", href: "https://example.com/"} // Link is opened by log. No visualization in world. return; } if (isNaN(CCC.World.lastWidth)) { // Race condition, message has arrived before world is ready to render. // Just add to the panorama queue, it will be rendered later. CCC.World.panoramaMessages.push(memo); return; } if (memo.type === 'scene' && memo.user) { // This is the user's current location. Save this environment data. CCC.World.scene = memo; } // Unrequested scenes should only show if either there is no immediately // following message (within half a second), or the following message is // something other than say/think/narrate. if (memo.type === 'scene' && !memo.requested) { memo.requested = true; CCC.World.renderMessage.pendingSceneMsg_ = memo; clearTimeout(CCC.World.renderMessage.pendingScenePid_); CCC.World.renderMessage.pendingScenePid_ = setTimeout(function() { // No following message arrived. Render scene change. CCC.World.renderMessage(memo); }, 500); return; } if (memo.type === 'say' || memo.type === 'think' || memo.type === 'narrate' || memo.type === 'scene') { // Throw away any pending scene change since say/think/narrate will show // the updated scene. CCC.World.renderMessage.pendingSceneMsg_ = null; clearTimeout(CCC.World.renderMessage.pendingScenePid_); } if (CCC.World.renderMessage.pendingSceneMsg_) { // Show any pending scene before the current message. CCC.World.renderMessage(CCC.World.renderMessage.pendingSceneMsg_); CCC.World.renderMessage.pendingSceneMsg_ = null; clearTimeout(CCC.World.renderMessage.pendingScenePid_); } if (!CCC.World.panelWidths.length) { CCC.World.panelWidths = CCC.World.rowWidths(); } var backupScratchHistory = CCC.World.scratchHistory && CCC.World.scratchHistory.cloneNode(true); if (CCC.World.prerenderHistory(memo) && CCC.World.prerenderPanorama(memo)) { // Rendering successful in both panorama and pending history panel. CCC.World.panoramaMessages.push(memo); CCC.World.publishPanorama(); } else { // Failure to render. Publish the previous history, and start fresh. CCC.World.removeNode(CCC.World.scratchHistory); CCC.World.removeNode(CCC.World.scratchPanorama); CCC.World.scratchHistory = null; CCC.World.scratchPanorama = null; // Publish one panel to the history. CCC.World.publishHistory(backupScratchHistory); // Move all panorama messages into history. Array.prototype.push.apply(CCC.World.historyMessages, CCC.World.panoramaMessages); CCC.World.panoramaMessages.length = 0; // Try again. CCC.World.renderMessage(memo); } }; CCC.World.renderMessage.pendingSceneMsg_ = null; CCC.World.renderMessage.pendingScenePid_ = 0; /** * Experimentally render a new message onto the most recent history frame. * @param {!Object} memo JSON structure. * @return {boolean} True if the message fit. False if overflow. */ CCC.World.prerenderHistory = function(memo) { if (memo.type === 'iframe') { if (CCC.World.scratchHistory) { return false; // Every iframe needs to be in its own panel. } // Create relaunch button if iframe is closed. var svg = CCC.World.createHiddenSvg(CCC.World.panelWidths[0], CCC.World.panelHeight); svg.style.backgroundColor = '#696969'; svg.setAttribute('data-iframe-id', memo.iframeId); var g = CCC.Common.createSvgElement('g', {'class': 'iframeRelaunch', 'transform': 'translate(0, 50)', 'data-iframe-src': memo.url}, svg); // Add relaunch button. var rect = document.createElementNS(CCC.Common.NS, 'rect'); var text = document.createElementNS(CCC.Common.NS, 'text'); text.appendChild(document.createTextNode( CCC.World.getTemplate('relaunchIframeTemplate'))); g.appendChild(rect); g.appendChild(text); // Size the rectangle to match the text size. var bBox = text.getBBox(); var r = Math.min(bBox.height, bBox.width) / 2; rect.setAttribute('height', bBox.height); rect.setAttribute('width', bBox.width + 2 * r); rect.setAttribute('x', bBox.x - r); rect.setAttribute('y', bBox.y); rect.setAttribute('rx', r); rect.setAttribute('ry', r); CCC.World.scratchHistory = svg; return true; } if (memo.type === 'html') { if (CCC.World.scratchHistory) { return false; // Every htmlframe needs to be in its own panel. } var div = CCC.World.createHiddenDiv(); CCC.World.cloneAndAppend(div, memo.htmlDom); CCC.World.scratchHistory = div; return true; } if (memo.type === 'connected') { if (CCC.World.scratchHistory) { return false; // Every connect/disconnect needs to be in its own panel. } var div = CCC.World.createHiddenDiv(); div.appendChild(CCC.World.connectPanel(memo)); CCC.World.scratchHistory = div; return true; } if (memo.type === 'scene') { //{ // type: "scene", // requested: true, // user: "Max", // where: "Hangout", // description: "The lights are dim and blah blah blah...", // svgText: "...", // contents: [ // { // type: "user", // what: "Max", // svgText: "...", // cmds: ["look Max", "kick Max"] // }, // { // type: "thing", // what: "clock", // svgText: "...", // cmds: ["look clock"] // } // ] //} // Each scene message needs its own frame. if (CCC.World.scratchHistory) { return false; } memo = CCC.World.sceneDescription(memo); } // If bubbles can be merged, attempt to do so. var merge = CCC.World.mergeBubbles(CCC.World.scratchHistory, memo); if (merge !== undefined) { return merge; } // For now every message needs its own frame. if (CCC.World.scratchHistory) { return false; } var svg = CCC.World.scratchHistory; if (!svg) { svg = CCC.World.createHiddenSvg(CCC.World.panelWidths[0], CCC.World.panelHeight); CCC.World.drawScene(svg); } if (memo.type === 'say' || memo.type === 'think' || memo.type === 'narrate') { CCC.World.createBubble(memo, svg); } CCC.World.scratchHistory = svg; return true; }; /** * Experimentally render a new message onto the panorama frame. * @param {!Object} memo JSON structure. * @return {boolean} True if the message fit. False if overflow. */ CCC.World.prerenderPanorama = function(memo) { if (memo.type === 'iframe') { if (CCC.World.scratchPanorama) { return false; // Every iframe needs to be in its own panel. } var svg = CCC.World.createHiddenSvg(CCC.World.panoramaDiv.offsetWidth, CCC.World.panoramaDiv.offsetHeight); svg.setAttribute('data-iframe-id', memo.iframeId); CCC.World.scratchPanorama = svg; return true; } if (memo.type === 'html') { if (CCC.World.scratchPanorama) { return false; // Every htmlframe needs to be in its own panel. } var div = CCC.World.createHiddenDiv(); CCC.World.cloneAndAppend(div, memo.htmlDom); CCC.World.scratchPanorama = div; return true; } if (memo.type === 'connected') { if (CCC.World.scratchPanorama) { return false; // Every connect/disconnect needs to be in its own panel. } var div = CCC.World.createHiddenDiv(); div.appendChild(CCC.World.connectPanel(memo)); CCC.World.scratchPanorama = div; return true; } if (memo.type === 'scene') { memo = CCC.World.sceneDescription(memo); } // If bubbles can be merged, attempt to do so. var merge = CCC.World.mergeBubbles(CCC.World.scratchPanorama, memo); if (merge !== undefined) { return merge; } // For now every message needs its own frame. if (CCC.World.scratchPanorama) { return false; } var svg = CCC.World.scratchPanorama; if (!svg) { var svg = CCC.World.createHiddenSvg(CCC.World.panoramaDiv.offsetWidth, CCC.World.panoramaDiv.offsetHeight); CCC.World.drawScene(svg); } if (memo.type === 'say' || memo.type === 'think' || memo.type === 'narrate') { CCC.World.createBubble(memo, svg); } CCC.World.scratchPanorama = svg; return true; }; /** * Create a panel for a connection/disconnection event. * @param {!Object} memo Object containing connection/disconnection mode and * date/time of event. * @return {!DocumentFragment} Document fragment containing rendered panel. */ CCC.World.connectPanel = function(memo) { var isConnected = memo.isConnected; var df = document.createDocumentFragment(); var div = document.createElement('div'); div.className = isConnected ? 'connectDiv' : 'disconnectDiv'; var text = CCC.World.getTemplate( isConnected ? 'connectedTemplate' : 'disconnectedTemplate'); div.appendChild(document.createTextNode(text)); df.appendChild(div); var img = document.createElement('img'); img.className = 'connectionIcon'; img.src = STATIC_URL + 'connect/connectionIcons.svg' + (isConnected ? '#connect' : '#reload'); df.appendChild(img); div = document.createElement('div'); div.className = 'systemTime'; div.appendChild(document.createTextNode(memo.time)); df.appendChild(div); return df; }; /** * * @param {!SVGElement} svg SVG element in which to draw the background. * @param {!Object} memo JSON structure. * @return {?boolean} True if merged, false if overflow, undefined if no match. */ CCC.World.mergeBubbles = function(svg, memo) { var previousMessage = CCC.World.panoramaMessages[CCC.World.panoramaMessages.length - 1]; if (!svg || !previousMessage || previousMessage.type !== memo.type || previousMessage.source !== memo.source || previousMessage.where !== memo.where) { return undefined; // Current message not a match with previous message. } // Remove previous bubble. svg.removeChild(svg.lastBubbleText_); svg.removeChild(svg.lastBubbleGroup_); // Try to add a merged bubble. var mergedNode = {}; for (var prop in memo) { mergedNode[prop] = memo[prop]; } mergedNode.text = svg.lastPlainText_ + '\n' + memo.text; CCC.World.createBubble(mergedNode, svg); // If the merged bubble is too big, reject the merge. var bBox = CCC.World.getBBoxWithTransform(svg.lastBubbleText_); var bottom = bBox.y + bBox.height - 2; // -2 for the border. var anchor = CCC.World.getAnchor(memo, svg); var limitY = anchor ? 100 - anchor.headY - anchor.headR : 100; return bottom < limitY; }; /** * Forge a text message with the room name and description. * @param {!Object} memo JSON structure. * @return {Object} Text message to render, or empty object if no message. */ CCC.World.sceneDescription = function(memo) { var title = memo.where; if (typeof title !== 'string') { return {}; } // Render title with HTML collapsing space rules. title = title.replace(/\s+/g, ' '); var text = [title]; var description = memo.description; if (description) { text.push(description); } text = text.join('\n'); return {type: 'narrate', text: text, where: title}; }; /** * Draw the currently recorded scene background into the provided SVG. * @param {!SVGElement} svg SVG element in which to draw the background. */ CCC.World.drawSceneBackground = function(svg) { var svgDom = CCC.World.scene.svgDom; if (svgDom) { var g = CCC.Common.createSvgElement('g', {'class': 'sceneBackground'}, svg); CCC.World.cloneAndAppend(g, svgDom); } }; /** * Draw the users and objects in the currently recorded scene. * @param {!SVGElement} svg SVG element in which to draw the users and objects. */ CCC.World.drawScene = function(svg) { CCC.World.drawSceneBackground(svg); // Obtain an ordered list of contents. var contentsArray = CCC.World.scene.contents; if (contentsArray) { var userTotal = 0; for (var i = 0; i < contentsArray.length; i++) { userTotal += contentsArray[i].type === 'user'; } svg.sceneUserLocations = Object.create(null); svg.sceneObjectLocations = Object.create(null); // Draw each item. var icons = []; var userCount = 0; for (var i = 0, thing; (thing = contentsArray[i]); i++) { var cursorX = (i + 1) / (contentsArray.length + 1) * svg.scaledWidth_ - svg.scaledWidth_ / 2; var bBox = null; var isUser = thing.type === 'user'; var svgDom = thing.svgDom; if (svgDom && svgDom.firstChild) { var name = thing.what; var g = CCC.Common.createSvgElement('g', {'class': thing.type}, svg); var title = CCC.Common.createSvgElement('title', {}, g); title.appendChild(document.createTextNode(name)); // TODO: Reenable whiteShadow. // whiteShadow disabled due to clipping bugs. //g.setAttribute('filter', 'url(#' + svg.whiteShadowId_ + ')'); CCC.World.cloneAndAppend(g, svgDom); // Users should face the majority of other users. // If user is alone, should face majority of objects. if (isUser && (userTotal === 1 ? (i > 0 && i >= Math.floor(contentsArray.length / 2)) : (userCount > 0 && userCount >= Math.floor(userTotal / 2)))) { // Wrap mirrored users in an extra group. var g2 = CCC.Common.createSvgElement('g', {}, svg); g.setAttribute('transform', 'scale(-1,1)'); g2.appendChild(g); g = g2; } // Move the sprite into position. bBox = g.getBBox(); var dx = cursorX - bBox.x - (bBox.width / 2); g.setAttribute('transform', 'translate(' + dx + ', 0)'); // Record location of each user for positioning of speech bubbles. var radius = Math.min(bBox.height, bBox.width) / 2; var location = { headX: cursorX, headY: bBox.y + radius, headR: radius }; if (isUser) { svg.sceneUserLocations[name] = location; } else { svg.sceneObjectLocations[name] = location; } } var cmds = thing.cmds; if (cmds) { var iconSize = 6; var x = cursorX - iconSize / 2; var y = isUser ? 40 : 60; if (bBox) { // Align menu icon with top-right corner of user's sprite. x = Math.min(cursorX + bBox.width / 2, svg.scaledWidth_ / 2 - iconSize); y = Math.max(0, bBox.y); } var icon = CCC.Common.newMenuIcon(cmds); icon.setAttribute('width', iconSize); icon.setAttribute('height', iconSize); icon.setAttribute('viewBox', '0 0 10 10'); icon.setAttribute('x', x); icon.setAttribute('y', y); icons.push(icon); } if (isUser) { userCount++; } } // Menu icons should be added after all the sprites so that they aren't // occluded by user content. for (var icon of icons) { svg.appendChild(icon); } } }; /** * Write text in a bubble. * @param {!Object} memo JSON structure. * @param {!SVGElement} svg SVG Element to place the text and bubble. */ CCC.World.createBubble = function(memo, svg) { // {type: "say", text: "Welcome"} // {type: "say", source: "Max", where: "Hangout", text: "Hello world."} // {type: "say", source: "Cat", where: "Hangout", text: "Meow."} // {type: "think", text: "Don't be evil."} // {type: "think", source: "Max", where: "Hangout", text: "I'm hungry."} // {type: "think", source: "Cat", where: "Hangout", text: "I'm evil."} // {type: "narrate", text: "Command not recognized."} // {type: "narrate", where: "Hangout", text: "Hangout is dark."} // {type: "narrate", source: "Max", where: "Hangout", text: "Max smiles."} // {type: "narrate", source: "Cat", where: "Hangout", text: "Cat meows."} var source = memo.source; var where = memo.where; var text = memo.text || ''; var width = memo.type === 'narrate' ? 150 : 100; width = Math.min(svg.scaledWidth_, width); var textGroup = CCC.World.createTextArea(svg, text, width, 30); textGroup.setAttribute('class', memo.type); var bubbleGroup = CCC.Common.createSvgElement('g', {'class': 'bubble'}, svg); if (source) { var title = CCC.Common.createSvgElement('title', {}, bubbleGroup); title.appendChild(document.createTextNode(source)); var title = CCC.Common.createSvgElement('title', {}, textGroup); title.appendChild(document.createTextNode(source)); } svg.appendChild(textGroup); var textBBox = textGroup.getBBox(); var anchor = CCC.World.getAnchor(memo, svg); if (!anchor && where && where === CCC.World.scene.where) { // This text box is coming from the room, not a user or object. // A bit of a hack: place anchor under box. anchor = {headX: 1 - svg.scaledWidth_ / 2, headY: 2, headR: 0}; } // Align the text above the user. var cursorX = anchor ? anchor.headX : 0; // Don't overflow the right edge. cursorX = Math.min(cursorX, svg.scaledWidth_ / 2 - textBBox.width / 2 - 1); // Don't overflow the left edge. cursorX = Math.max(cursorX, textBBox.width / 2 - svg.scaledWidth_ / 2 + 1); cursorX -= textBBox.x + textBBox.width / 2; textGroup.setAttribute('transform', 'translate(' + cursorX + ', 2)'); CCC.World.drawBubble(memo.type, bubbleGroup, textGroup, anchor); // Record the appended DOM elements so that they may be removed if more // text needs to be appended. svg.lastBubbleGroup_ = bubbleGroup; svg.lastBubbleText_ = textGroup; svg.lastPlainText_ = text; }; /** * Find the location of the actor who is initiating a bubble. * @param {!Object} memo JSON structure. * @param {!SVGElement} svg SVG Element to place the text and bubble. * @return {Object} Provides headX, headY, and headR properties. */ CCC.World.getAnchor = function(memo, svg) { var anchor = null; try { if ((memo.where && memo.where === CCC.World.scene.where) || memo.source) { anchor = svg.sceneUserLocations[memo.source] || svg.sceneObjectLocations[memo.source]; } } catch (e) { // No anchor. Simpler to try/catch than to check every step. } return anchor; }; /** * Return the object's bounding box, compensating for any transform-translate. * @param {!Element} element Element to measure. * @return {!Object} Height, width, x and y. */ CCC.World.getBBoxWithTransform = function(element) { var bBox = element.getBBox(); // getBBox doesn't look at element's transform="translate(...)". var transform = element.getAttribute('transform'); var r = transform && transform.match( /translate\(\s*([-+\d.e]+)([ ,]\s*([-+\d.e]+)\s*\))?/); if (r) { bBox.x += parseFloat(r[1]); if (r[3]) { bBox.y += parseFloat(r[3]); } } return bBox; }; /** * Draw a bubble around some content. * @param {!string} type Type of bubble: 'say' or 'text'. * @param {!SVGElement} bubbleGroup Empty group to render the bubble in. * @param {!SVGElement} contentGroup Group to surround. * @param {Object} opt_anchor Optional anchor location for arrow tip. */ CCC.World.drawBubble = function(type, bubbleGroup, contentGroup, opt_anchor) { // Find coordinates of the contents. var contentBBox = CCC.World.getBBoxWithTransform(contentGroup); // Draw a solid black bubble, then the arrow (with border), then a slightly // smaller solid white bubble, resulting in a clean border. if (type === 'think') { var strokeWidth = 0.7; // Matches with CSS. var radiusXAverage = 4; // Target size of cloud puffs. var radiusYAverage = 3; // Target size of cloud puffs. var radiusVariation = 0.5; // Cloud puffs can be + or - this amount. var inflateRadius = 1; // Expand the radii a bit to make less jagged. // Pick a radius that's within the standard variation. var randomRadius = function(r) { return r + (Math.random() - 0.5) * radiusVariation * 2; }; // Create a horizontal or vertical line of puff descriptors. var puffLine = function(x, y, dx, dy) { var d = Math.max(dx, dy); var radiusAverage = (d === dx) ? radiusXAverage : radiusYAverage; var line = new Array(Math.round(d / radiusAverage / 2)); radiusAverage = d / line.length / 2; for (var i = 0; i < line.length - 1; i += 2) { line[i] = randomRadius(radiusAverage); line[i + 1] = radiusAverage * 2 - line[i]; } if (line[line.length - 1] === undefined) { // There was an odd number of puffs. Add the remaining orphan. line[line.length - 1] = radiusAverage; } CCC.World.shuffle(line); var cursor = (d === dx) ? x : y; for (var i = 0; i < line.length; i++) { var r = line[i]; var puff; if (d === dx) { puff = { rx: r, ry: randomRadius(radiusYAverage), cx: cursor + r, cy: y }; cursor += puff.rx * 2; } else { puff = { rx: randomRadius(radiusXAverage), ry: r, cx: x, cy: cursor + r }; cursor += puff.ry * 2; } line[i] = puff; } return line; }; var puffs = []; // Top edge. puffs = puffs.concat(puffLine(inflateRadius, inflateRadius, contentBBox.width - 2 * inflateRadius, 0)); // Right edge. puffs = puffs.concat(puffLine(contentBBox.width - inflateRadius, inflateRadius, 0, contentBBox.height - 2 * inflateRadius)); // Bottom edge. puffs = puffs.concat(puffLine(inflateRadius, contentBBox.height - inflateRadius, contentBBox.width - 2 * inflateRadius, 0)); // Left edge. puffs = puffs.concat(puffLine(inflateRadius, inflateRadius, 0, contentBBox.height - 2 * inflateRadius)); if (!puffs.length) { // Empty thought bubble. Add one puff. puffs[0] = {rx: radiusXAverage, ry: radiusYAverage, cx: 0, cy: 0}; } if (contentBBox.height > 2 * inflateRadius && contentBBox.width > 2 * inflateRadius) { CCC.Common.createSvgElement('rect', {'class': 'bubbleBG', 'x': inflateRadius - strokeWidth, 'y': inflateRadius - strokeWidth, 'height': contentBBox.height + 2 * strokeWidth - 2 * inflateRadius, 'width': contentBBox.width + 2 * strokeWidth - 2 * inflateRadius}, bubbleGroup); } for (var puff of puffs) { CCC.Common.createSvgElement('ellipse', {'class': 'bubbleBG', 'cx': puff.cx, 'cy': puff.cy, 'rx': puff.rx + inflateRadius + strokeWidth, 'ry': puff.ry + inflateRadius + strokeWidth}, bubbleGroup); } if (contentBBox.height > 2 * inflateRadius && contentBBox.width > 2 * inflateRadius) { CCC.Common.createSvgElement('rect', {'class': 'bubbleFG', 'x': inflateRadius, 'y': inflateRadius, 'height': contentBBox.height - 2 * inflateRadius, 'width': contentBBox.width - 2 * inflateRadius}, bubbleGroup); } for (var puff of puffs) { CCC.Common.createSvgElement('ellipse', {'class': 'bubbleFG', 'cx': puff.cx, 'cy': puff.cy, 'rx': puff.rx + inflateRadius, 'ry': puff.ry + inflateRadius}, bubbleGroup); } if (opt_anchor) { bubbleGroup.appendChild( CCC.World.drawArrow_(contentBBox, opt_anchor, true)); } } else { if (type === 'say') { var strokeWidth = 0.7; // Matches with CSS. var marginV = 2; var marginH = 6; var radius = 15; } else { var strokeWidth = 0.4; var marginV = 1; var marginH = 2; var radius = 0.5; } CCC.Common.createSvgElement('rect', {'class': 'bubbleBG', 'x': -marginH - strokeWidth, 'y': -marginV - strokeWidth, 'rx': radius + strokeWidth, 'ry': radius + strokeWidth, 'height': contentBBox.height + 2 * (marginV + strokeWidth), 'width': contentBBox.width + 2 * (marginH + strokeWidth)}, bubbleGroup); if (opt_anchor) { bubbleGroup.appendChild( CCC.World.drawArrow_(contentBBox, opt_anchor, false)); } CCC.Common.createSvgElement('rect', {'class': 'bubbleFG', 'x': -marginH, 'y': -marginV, 'rx': radius, 'ry': radius, 'height': contentBBox.height + 2 * marginV, 'width': contentBBox.width + 2 * marginH}, bubbleGroup); } bubbleGroup.setAttribute('transform', 'translate(' + contentBBox.x + ', ' + contentBBox.y + ')'); }; /** * Draw the arrow between the bubble and the origin. * @param {!Object} contentBBox Dimensions of the bubble's contents. * @param {!Object} anchor Anchor location for arrow tip. * @param {boolean} thought True if a thought bubble, false for solid arrow. * @return {!Element} Path for arrow. * @private */ CCC.World.drawArrow_ = function(contentBBox, anchor, thought) { // Find the relative coordinates of the center of the bubble. var relBubbleX = contentBBox.width / 2; var relBubbleY = contentBBox.height / 2; // Find the relative coordinates of the center of the anchor. var relAnchorX = anchor.headX - contentBBox.x; var relAnchorY = anchor.headY - contentBBox.y; if (relBubbleX === relAnchorX && relBubbleY === relAnchorY) { // Null case. Bubble is directly on top of the anchor. // Short circuit this rather than wade through divide by zeros. return CCC.Common.createSvgElement('g', {}, null); } // Compute the angle of the arrow's line. var rise = relAnchorY - relBubbleY; var run = relAnchorX - relBubbleX; var hypotenuse = Math.sqrt(rise * rise + run * run); var angle = Math.acos(run / hypotenuse); if (rise < 0) { angle = 2 * Math.PI - angle; } // Compute a line perpendicular to the arrow. var rightAngle = angle + Math.PI / 2; if (rightAngle > Math.PI * 2) { rightAngle -= Math.PI * 2; } var rightRise = Math.sin(rightAngle); var rightRun = Math.cos(rightAngle); // Calculate the thickness of the base of the arrow. var thickness = (contentBBox.width + contentBBox.height) / CCC.World.ARROW_THICKNESS; thickness = Math.min(thickness, contentBBox.width, contentBBox.height) / 4; // Back the tip of the arrow off of the anchor. var backoffRatio = 1 - (anchor.headR + 5) / hypotenuse; relAnchorX = relBubbleX + backoffRatio * run; relAnchorY = relBubbleY + backoffRatio * rise; // Distortion to curve the arrow. var swirlAngle = angle + Math.random() - 0.5; if (swirlAngle > Math.PI * 2) { swirlAngle -= Math.PI * 2; } var swirlRise = Math.sin(swirlAngle) * hypotenuse / CCC.World.ARROW_BEND; var swirlRun = Math.cos(swirlAngle) * hypotenuse / CCC.World.ARROW_BEND; if (thought) { var group = CCC.Common.createSvgElement('g', {class: 'fillWhite'}, null); // The commented out code below is a guide path to verify the placement of // the thought bubbles which make up the arrow. //var d = 'M' + relBubbleX + ',' + relBubbleY + // ' Q' + (relBubbleX + swirlRun) + ',' + (relBubbleY + swirlRise) + // ' ' + relAnchorX + ',' + relAnchorY; //CCC.Common.createSvgElement('path', {'d': d}, group); /** * Given two x/y points, find the point at the specified distance between. * @param {number} x1 Horizontal position of first point. * @param {number} y1 Vertical position of first point. * @param {number} x2 Horizontal position of second point. * @param {number} y2 Vertical position of second point. * @param {number} t Interpolation distance (0.0 - 1.0). * @return {!Object} Contains x and y properties. */ var interpolate = function(x1, y1, x2, y2, t) { var x = t * (x2 - x1) + x1; var y = t * (y2 - y1) + y1; return {x: x, y: y}; }; // Pythagorean theorem for approximate length of arrow // (doesn't count the added length caused by the bend). var length = Math.sqrt(Math.pow(relBubbleX - relAnchorX, 2) + Math.pow(relBubbleY - relAnchorY, 2)); var t = 0; while (t < 1) { // Add a little bubble on the arrow's path. // Compute point on a quadratic curve. var q1 = interpolate(relBubbleX, relBubbleY, relBubbleX + swirlRun, relBubbleY + swirlRise, t); var q2 = interpolate(relBubbleX + swirlRun, relBubbleY + swirlRise, relAnchorX, relAnchorY, t); var p = interpolate(q1.x, q1.y, q2.x, q2.y, t); // The bubble's radius gets smaller as one gets closer to the anchor. var ry = (1 - t) * 2 + 1; if (p.y > contentBBox.height + ry) { CCC.Common.createSvgElement('ellipse', {'rx': ry * 1.5, 'ry': ry, 'cx': p.x, 'cy': p.y}, group); // Place next bubble three radii away from this bubble. t += 3 * ry / length; } else { // Skip this bubble, since it is over the main thought bubble. t += 0.1; } } return group; } else { // Coordinates for the base of the arrow. var baseX1 = relBubbleX + thickness * rightRun; var baseY1 = relBubbleY + thickness * rightRise; var baseX2 = relBubbleX - thickness * rightRun; var baseY2 = relBubbleY - thickness * rightRise; var steps = ['M' + baseX1 + ',' + baseY1]; steps.push('C' + (baseX1 + swirlRun) + ',' + (baseY1 + swirlRise) + ' ' + relAnchorX + ',' + relAnchorY + ' ' + relAnchorX + ',' + relAnchorY); steps.push('C' + relAnchorX + ',' + relAnchorY + ' ' + (baseX2 + swirlRun) + ',' + (baseY2 + swirlRise) + ' ' + baseX2 + ',' + baseY2); steps.push('z'); return CCC.Common.createSvgElement('path', {'class': 'bubbleArrow', 'd': steps.join(' ')}, null); } }; /** * Determines the thickness of the base of the arrow in relation to the size * of the bubble. Higher numbers result in thinner arrows. */ CCC.World.ARROW_THICKNESS = 5; /** * The sharpness of the arrow's bend. Higher numbers result in smoother arrows. */ CCC.World.ARROW_BEND = 4; /** * Publish the previously experimentally rendered history frame to the user. * @param {!Element} historyElement Rendered history panel. */ CCC.World.publishHistory = function(historyElement) { if (!CCC.World.historyRow) { var rowDiv = document.createElement('div'); rowDiv.className = 'historyRow'; CCC.World.scrollDiv.insertBefore(rowDiv, CCC.World.panoramaDiv); CCC.World.historyRow = rowDiv; } var width = CCC.World.panelWidths.shift(); var panelDiv = document.createElement('div'); panelDiv.className = 'historyPanel'; panelDiv.style.height = CCC.World.panelHeight + 'px'; panelDiv.style.width = width + 'px'; CCC.World.historyRow.appendChild(panelDiv); panelDiv.appendChild(historyElement); CCC.World.stripActions(panelDiv); var iframeId = historyElement.getAttribute('data-iframe-id'); if (iframeId) { var iframe = document.getElementById(iframeId); CCC.World.positionIframe(iframe, panelDiv); // Add var closeImg = new Image(21, 21); closeImg.className = 'iframeClose'; closeImg.src = STATIC_URL + 'connect/close.png'; closeImg.title = CCC.World.getTemplate('closeIframeTemplate'); closeImg.addEventListener('click', function() { closeImg.style.display = 'none'; panelDiv.firstChild.style.visibility = 'visible'; // SVG. CCC.World.removeNode(iframe); }, false); // Add event handler on element. var group = panelDiv.querySelector('g.iframeRelaunch'); group.addEventListener('click', function() { var iframeSrc = group.getAttribute('data-iframe-src'); iframeId = CCC.World.createIframe(iframeSrc); iframe = document.getElementById(iframeId); var div = historyElement.parentNode; CCC.World.positionIframe(iframe, div); div.firstChild.style.visibility = 'hidden'; // SVG. div.lastChild.style.display = 'inline'; // Close button. }, false); panelDiv.appendChild(closeImg); } else { CCC.World.svgZoom(historyElement); // The occasional (non-iframe) panel should lack a border. var connectDiv = historyElement.firstChild && historyElement.firstChild.className === 'connectDiv'; if (!connectDiv && (Math.random() < 1 / 16)) { panelDiv.style.borderColor = '#fff'; } // While being built, the SVG was hidden. // Make it visible, unless there is an iframe displayed on top of it. historyElement.style.visibility = 'visible'; } CCC.World.scrollDiv.scrollTop = CCC.World.scrollDiv.scrollHeight; if (!CCC.World.panelWidths.length) { CCC.World.historyRow = null; // Next row. } }; /** * Publish the previously experimentally rendered panorama frame to the user. */ CCC.World.publishPanorama = function() { // Destroy any existing content. while (CCC.World.panoramaDiv.firstChild) { CCC.World.panoramaDiv.removeChild(CCC.World.panoramaDiv.firstChild); } // Insert new content. var content = CCC.World.scratchPanorama.cloneNode(true); CCC.World.panoramaDiv.appendChild(content); var iframeId = content.getAttribute('data-iframe-id'); if (iframeId) { var iframe = document.getElementById(iframeId); CCC.World.positionIframe(iframe, CCC.World.panoramaDiv); } else { content.style.visibility = 'visible'; CCC.World.svgZoom(content); // Add event handlers on all links. var commands = content.querySelectorAll('a.command'); for (var command of commands) { command.addEventListener('click', CCC.Common.commandFunction, false); } // Add event handlers on all menus. var menus = content.querySelectorAll('svg.menuIcon'); for (var menu of menus) { menu.addEventListener('click', CCC.Common.openMenu, false); } // Add an event handler to a reload icon. var icon = content.querySelector('.connectionIcon[src$="#reload"]'); if (icon) { icon.addEventListener('click', parent.location.reload.bind(parent.location)); icon.title = CCC.World.getTemplate('reconnectTemplate'); } } }; /** * Find all SVG images with viewBox="0 0 0 0" attribute and resize them to fit. * @param {!Element} container DOM node for panel. */ CCC.World.svgZoom = function(container) { var svgNodes = container.getElementsByTagName('svg'); for (var svg of svgNodes) { var viewBox = svg.getAttribute('viewBox'); if (viewBox && viewBox.match(/^\s*0\s+0\s+0\s+0\s*$/)) { //var outerSize = svg.getBoundingClientRect(); var bBox = svg.getBBox(); var height = bBox.height + 1; // Add half the stroke width to each side. var width = bBox.width + 1; var x = bBox.x - 0.5; var y = bBox.y - 0.5; svg.setAttribute('viewBox', x + ' ' + y + ' ' + width + ' ' + height); } } }; /** * Absolutely position an iframe so that it fits exactly inside a comic panel. * @param {!Element} iframe DOM node for iframe. * @param {!Element} container DOM node for panel. */ CCC.World.positionIframe = function(iframe, container) { var borderWidth = 2; iframe.style.width = (container.offsetWidth - borderWidth * 2) + 'px'; iframe.style.height = (container.offsetHeight - borderWidth * 2) + 'px'; var x = 0; var y = 0; do { x += container.offsetLeft; y += container.offsetTop; } while ((container = container.offsetParent) && (container !== CCC.World.scrollDiv)); iframe.style.top = (y + borderWidth) + 'px'; iframe.style.left = (x + borderWidth) + 'px'; }; /** * Strip all command links and menus. History panels should not be interactive. * @param {!Element} div History panel div. */ CCC.World.stripActions = function(div) { var menus = div.querySelectorAll('svg.menuIcon'); for (var menu of menus) { menu.parentNode.removeChild(menu); } var commands = div.querySelectorAll('a.command'); for (var command of commands) { command.className = 'disabled'; } }; /** * Create a blank, hidden SVG. * @param {number} width Width of panel in pixels. * @param {number} height Height of panel in pixels. * @return {!SVGElement} SVG element. */ CCC.World.createHiddenSvg = function(width, height) { var svg = CCC.Common.createSvgElement('svg', {'xmlns:xlink': 'http://www.w3.org/1999/xlink'}, document.body); svg.style.visibility = 'hidden'; // Compute the scaled height and width and save on private properties. width -= CCC.World.panelBorder * 2; height -= CCC.World.panelBorder * 2; svg.scaledHeight_ = 100; svg.scaledWidth_ = width / height * svg.scaledHeight_; svg.setAttribute('viewBox', [-svg.scaledWidth_ / 2, 0, svg.scaledWidth_, svg.scaledHeight_].join(' ')); /* */ // Filters cannot be shared between SVGs, doing so can even crash browsers. // https://bugs.webkit.org/show_bug.cgi?id=149613 var id = 'whiteShadow' + String(Math.random()).substring(2); svg.whiteShadowId_ = id; var filter = CCC.Common.createSvgElement('filter', {'id': id, 'filterUnits': 'userSpaceOnUse'}, svg); CCC.Common.createSvgElement('feFlood', {'result': 'flood', 'flood-color': '#fff', 'flood-opacity': 1}, filter); CCC.Common.createSvgElement('feComposite', {'in': 'flood', 'result': 'mask', 'in2': 'SourceGraphic', 'operator': 'in'}, filter); CCC.Common.createSvgElement('feMorphology', {'in': 'mask', 'result': 'dilated', 'operator': 'dilate', 'radius': 1}, filter); CCC.Common.createSvgElement('feGaussianBlur', {'in': 'dilated', 'result': 'blurred', 'stdDeviation': 5}, filter); var feMerge = CCC.Common.createSvgElement('feMerge', {}, filter); CCC.Common.createSvgElement('feMergeNode', {'in': 'blurred'}, feMerge); CCC.Common.createSvgElement('feMergeNode', {'in': 'SourceGraphic'}, feMerge); return svg; }; /** * Create a blank, hidden div. * @return {!Element} Div element. */ CCC.World.createHiddenDiv = function() { var div = document.createElement('div'); div.className = 'htmlPanel'; div.style.visibility = 'hidden'; document.body.appendChild(div); return div; }; /** * Instantiate an iframe based on a message. * @param {string} src URL of target. * @return {string} The iframe's UUID. */ CCC.World.createIframe = function(src) { var iframe = document.createElement('iframe'); iframe.id = 'iframe' + (Math.random() + '').substring(2); iframe.sandbox = 'allow-forms allow-scripts allow-same-origin'; iframe.src = src; document.getElementById('iframeStorage').appendChild(iframe); return iframe.id; }; /** * Buffer temporally close resize events. * Called when the window changes size. */ CCC.World.resizeSoon = function() { // First resize should call function immediately, // subsequent ones should throttle resizing reflows. if (CCC.World.resizePid) { clearTimeout(CCC.World.resizePid); CCC.World.resizePid = setTimeout(CCC.World.resizeNow, 1000); } else { CCC.World.resizeNow(); CCC.World.resizePid = -1; } }; /** * Rerender the history and the panorama panels. * Called when the window changes size. */ CCC.World.resizeNow = function() { var width = CCC.World.scrollDiv.offsetWidth; if (width === CCC.World.lastWidth) { // Width hasn't changed. Maybe just the height changed. Snap to bottom. CCC.World.scrollDiv.scrollTop = CCC.World.scrollDiv.scrollHeight; return; } CCC.World.lastWidth = width; CCC.World.renderHistory(); }; /** * Rerender entire history. * Called when the window changes size. */ CCC.World.renderHistory = function() { // Destroy all existing history. var historyRows = document.getElementsByClassName('historyRow'); while (historyRows[0]) { CCC.World.removeNode(historyRows[0]); } while (CCC.World.panoramaDiv.firstChild) { CCC.World.panoramaDiv.removeChild(CCC.World.panoramaDiv.firstChild); } CCC.World.panelWidths.length = 0; CCC.World.historyRow = null; CCC.World.scratchHistory = null; CCC.World.scratchPanorama = null; CCC.World.scene = {}; // Create new history. var msgs = CCC.World.historyMessages.concat(CCC.World.panoramaMessages); CCC.World.historyMessages.length = 0; CCC.World.panoramaMessages.length = 0; for (var msg of msgs) { CCC.World.renderMessage(msg); } CCC.World.scrollDiv.scrollTop = CCC.World.scrollDiv.scrollHeight; }; /** * Given the current window width, assign the number and widths of panels on * one history row. * @return {!Array.} Array of lengths. */ CCC.World.rowWidths = function() { // Margin and border widths must match the CSS. var panelBloat = 2 * (5 + CCC.World.panelBorder); var windowWidth = CCC.World.lastWidth - CCC.World.scrollBarWidth - 1; var idealWidth = CCC.World.panelHeight * 5 / 4; // Standard TV ratio. var panelCount = Math.round(windowWidth / idealWidth); var averageWidth = Math.floor(windowWidth / panelCount); var smallWidth = Math.round(averageWidth * 0.9); var largeWidth = averageWidth * 2 - smallWidth; averageWidth -= panelBloat; smallWidth -= panelBloat; largeWidth -= panelBloat; // Build an array of lengths. Add in matching pairs. var panels = []; for (var i = 0; i < Math.floor(panelCount / 2); i++) { if (Math.random() > 0.5) { panels.push(averageWidth, averageWidth); } else { panels.push(smallWidth, largeWidth); } } // Odd number of panels has one in the middle. if (panels.length < panelCount) { panels.push(averageWidth); } CCC.World.shuffle(panels); return panels; }; /** * Shuffles the values in the specified array using the Fisher-Yates in-place * shuffle (also known as the Knuth Shuffle). * Copied from Google Closure's goog.array.shuffle * @param {!Array} arr The array to be shuffled. */ CCC.World.shuffle = function(arr) { for (var i = arr.length - 1; i > 0; i--) { // Choose a random array index in [0, i] (inclusive with i). var j = Math.floor(Math.random() * (i + 1)); var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }; /** * Unserialize stringified HTML. Wrap the HTML elements in a body. * @param {string} svgText '

Hello

' * @return {Element}

Hello

*/ CCC.World.stringToHtml = function(htmlText) { var dom = CCC.Common.parser.parseFromString(htmlText, 'text/html'); if (!dom.body) { // Not valid XML. console.log('Syntax error in HTML: ' + htmlText); return null; } var body = CCC.World.xmlToHtml(dom.body); CCC.Common.autoHyperlink(body); return body; }; /** * Convert an XML tree into an HTML tree. * Whitelist used for all elements and properties. * @param {!Element} dom XML tree. * @return {Element} HTML tree. */ CCC.World.xmlToHtml = function(dom) { if (!dom) { return null; } switch (dom.nodeType) { case Node.ELEMENT_NODE: if (dom.tagName === 'svg') { // XML tagNames are lowercase. // Switch to SVG rendering mode. return CCC.World.xmlToSvg(dom); } if (dom.tagName === 'CMDS') { // HTML tagNames are uppercase. return CCC.Common.newMenuIcon(dom); } if (dom.tagName === 'CMD') { // HTML tagNames are uppercase. var cmdText = dom.innerText; var a = document.createElement('a'); a.className = 'command'; a.appendChild(document.createTextNode(cmdText)); return a; } if (CCC.World.xmlToHtml.ELEMENT_NAMES && !CCC.World.xmlToHtml.ELEMENT_NAMES.has(dom.tagName)) { console.log('HTML element not in whitelist: <' + dom.tagName + '>'); return null; } var element = document.createElement(dom.tagName); for (var attr of dom.attributes) { if (CCC.World.xmlToHtml.ATTRIBUTE_NAMES && !CCC.World.xmlToHtml.ATTRIBUTE_NAMES.has(attr.name)) { console.log('HTML attribute not in whitelist: ' + '<' + dom.tagName + ' ' + attr.name + '="' + attr.value + '">'); } else { element.setAttribute(attr.name, attr.value); // Remove all styles not in the whitelist. if (attr.name === 'style') { for (var name in element.style) { if (element.style.hasOwnProperty(name) && isNaN(parseFloat(name)) && // Don't delete indexed props. element.style[name] && element.style[name] !== 'initial' && CCC.World.xmlToHtml.STYLE_NAMES && !CCC.World.xmlToHtml.STYLE_NAMES.has(name)) { console.log('Style attribute not in whitelist: ' + name + ': ' + element.style[name]); element.style[name] = ''; } } } } } for (var childDom of dom.childNodes) { var childNode = CCC.World.xmlToHtml(childDom); if (childNode) { element.appendChild(childNode); } } return element; case Node.TEXT_NODE: return document.createTextNode(dom.data); case Node.COMMENT_NODE: return null; } console.log('Unknown HTML node type: ' + dom); return null; }; /** * Whitelist of all allowed HTML element names. * 'svg' element is handled separately. * Set to null to disable filtering. */ CCC.World.xmlToHtml.ELEMENT_NAMES = new Set([ 'ABBR', 'ADDRESS', 'ARTICLE', 'ASIDE', 'B', 'BDI', 'BDO', 'BLOCKQUOTE', 'BODY', 'BR', 'CAPTION', 'CITE', 'CODE', 'COL', 'COLGROUP', 'DATA', 'DD', 'DEL', 'DFN', 'DIV', 'DL', 'DT', 'EM', 'FIELDSET', 'FIGCAPTION', 'FIGURE', 'FOOTER', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'HEADER', 'HGROUP', 'HR', 'I', 'INS', 'KBD', 'LEGEND', 'LI', 'MAIN', 'MARK', 'NAV', 'OL', 'P', 'PRE', 'Q', 'RP', 'RT', 'RTC', 'RUBY', 'S', 'SAMP', 'SECTION', 'SMALL', 'SPAN', 'STRONG', 'SUB', 'SUP', 'TABLE', 'TBODY', 'TD', 'TFOOT', 'TH', 'THEAD', 'TIME', 'TR', 'U', 'UL', 'VAR', 'WBR', ]); /** * Whitelist of all allowed HTML property names. * This architecture assumes that there are no banned properties * on one element type which are allowed on another. * Set to null to disable filtering. */ CCC.World.xmlToHtml.ATTRIBUTE_NAMES = new Set([ 'cite', 'colspan', 'datetime', 'dir', 'headers', 'nowrap', 'reversed', 'rowspan', 'scope', 'span', 'start', 'style', 'title', 'type', 'value', ]); /** * Whitelist of all allowed style property names. * Set to null to disable filtering. */ CCC.World.xmlToHtml.STYLE_NAMES = new Set([ 'border', 'borderBottom', 'borderBottomColor', 'borderBottomLeftRadius', 'borderBottomRightRadius', 'borderBottomStyle', 'borderBottomWidth', 'borderCollapse', 'borderColor', 'borderLeft', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRadius', 'borderRight', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderSpacing', 'borderStyle', 'borderTop', 'borderTopColor', 'borderTopLeftRadius', 'borderTopRightRadius', 'borderTopStyle', 'borderTopWidth', 'borderWidth', 'clear', 'direction', 'display', 'float', 'fontWeight', 'height', 'hyphens', 'padding', 'paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop', 'textAlign', 'verticalAlign', 'width', ]); /** * Unserialize stringified SVG. Wrap the SVG elements in an SVG. * @param {string} svgText '' * @return {SVGSVGElement} */ CCC.World.stringToSvg = function(svgText) { var dom = CCC.Common.parser.parseFromString( '' + svgText + '', 'image/svg+xml'); if (dom.getElementsByTagName('parsererror').length) { // Not valid XML. console.log('Syntax error in SVG: ' + svgText); return null; } return CCC.World.xmlToSvg(dom.firstChild); }; /** * Convert an XML tree into an SVG tree. * Whitelist used for all elements and properties. * @param {!Element} dom XML tree. * @return {SVGElement} SVG tree. */ CCC.World.xmlToSvg = function(dom) { if (!dom) { return null; } switch (dom.nodeType) { case Node.ELEMENT_NODE: if (CCC.World.xmlToSvg.ELEMENT_NAMES && !CCC.World.xmlToSvg.ELEMENT_NAMES.has(dom.tagName)) { console.log('SVG element not in whitelist: <' + dom.tagName + '>'); return null; } var svg = document.createElementNS(CCC.Common.NS, dom.tagName); for (var attr of dom.attributes) { if (CCC.World.xmlToSvg.ATTRIBUTE_NAMES && !CCC.World.xmlToSvg.ATTRIBUTE_NAMES.has(attr.name)) { console.log('SVG attribute not in whitelist: ' + '<' + dom.tagName + ' ' + attr.name + '="' + attr.value + '">'); } else { // Remove all styles not in the whitelist. if (attr.name === 'class') { var classes = attr.value.split(/\s+/g); for (var i = classes.length - 1; i >= 0; i--) { if (CCC.World.xmlToSvg.CLASS_NAMES && !CCC.World.xmlToSvg.CLASS_NAMES.has(classes[i])) { console.log('Class name not in whitelist: ' + classes[i]); classes.splice(i, 1); } } attr.value = classes.join(' '); } svg.setAttribute(attr.name, attr.value); } } for (var childDom of dom.childNodes) { var childSvg = CCC.World.xmlToSvg(childDom); if (childSvg) { svg.appendChild(childSvg); } } return svg; case Node.TEXT_NODE: return document.createTextNode(dom.data); case Node.COMMENT_NODE: return null; } console.log('Unknown XML node type: ' + dom); return null; }; /** * Whitelist of all allowed SVG element names. * Try to keep this list in sync with Code.svgEditor.ELEMENT_NAMES. * Set to null to disable filtering. */ CCC.World.xmlToSvg.ELEMENT_NAMES = new Set([ 'circle', 'desc', 'ellipse', 'g', 'line', 'path', 'polygon', 'polyline', 'rect', 'svg', 'text', 'title', 'tspan', ]); /** * Whitelist of all allowed SVG property names. * This architecture assumes that there are no banned properties * on one element type which are allowed on another. * Set to null to disable filtering. */ CCC.World.xmlToSvg.ATTRIBUTE_NAMES = new Set([ 'class', 'cx', 'cy', 'd', 'dx', 'dy', 'height', 'lengthAdjust', 'points', 'r', 'rx', 'ry', 'text-anchor', 'textLength', 'transform', 'viewBox', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'width', ]); /** * Whitelist of all allowed class names. * Set to null to disable filtering. */ CCC.World.xmlToSvg.CLASS_NAMES = new Set([ 'fillNone', 'fillWhite', 'fillBlack', 'fillGrey', 'fillGray', 'strokeNone', 'strokeWhite', 'strokeBlack', 'strokeGrey', 'strokeGray', ]); /** * Clone a tree of elements, and append it as a new child onto a DOM. * @param {!Element} parent Parent DOM element. * @param {Element} container A disposable or wrapper. */ CCC.World.cloneAndAppend = function(parent, container) { if (container) { var clonedContianer = container.cloneNode(true); while (clonedContianer.firstChild) { parent.appendChild(clonedContianer.firstChild); } } }; /** * Remove a node from the DOM. * @param {Node} node Node to remove, ok if null. */ CCC.World.removeNode = function(node) { if (node) { node.parentNode.removeChild(node); } }; /** * Gets the template with the given key from the document. * @param {string} key The key of the document element. * @return {string} The textContent of the specified element. */ CCC.World.getTemplate = function(key) { var element = document.getElementById(key); if (!element) { throw new Error('Unknown template ' + key); } return element.textContent; }; /** * Determine the width of scrollbars on this platform. * Code copied from https://stackoverflow.com/questions/8079187/ * @return {number} Width in pixels. */ CCC.World.getScrollBarWidth = function() { var inner = document.createElement('p'); inner.style.width = '100%'; inner.style.height = '200px'; var outer = document.createElement('div'); outer.style.position = 'absolute'; outer.style.top = 0; outer.style.left = 0; outer.style.visibility = 'hidden'; outer.style.width = '200px'; outer.style.height = '150px'; outer.style.overflow = 'hidden'; outer.appendChild(inner); document.body.appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 === w2) { w2 = outer.clientWidth; } document.body.removeChild(outer); return w1 - w2; }; /** * Create a block of text on SVG constrained to a given size. * @param {!SVGSVGElement} svg SVG element to use. * @param {string} text Text to create. * @param {number} width Maximum width. * @param {number} height Maximum height. * @return {!SVGElement} SVG group containing text. */ CCC.World.createTextArea = function(svg, text, width, height) { text = CCC.World.wrap(svg, text, width, height); text = CCC.Common.escapeSpaces(text); var lines = text.split('\n'); var textNode = document.createElementNS(CCC.Common.NS, 'text'); textNode.setAttribute('alignment-baseline', 'hanging'); if (lines.length) { var dy = CCC.World.measureText(svg, 'Wg').height; for (var line of lines) { if (line === '\r' || line === '\n') { line = '\u200B'; // Zero-width space. } var tspan = document.createElementNS(CCC.Common.NS, 'tspan'); tspan.appendChild(document.createTextNode(line)); tspan.setAttribute('x', 0); tspan.setAttribute('dy', dy); textNode.appendChild(tspan); } } var g = document.createElementNS(CCC.Common.NS, 'g'); CCC.Common.autoHyperlink(textNode); g.appendChild(textNode); return g; }; /** * Wrap text to the specified width. * @param {!SVGSVGElement} svg SVG element to use. * @param {string} text Text to wrap. * @param {number} width Maximum width. * @param {number} height Maximum height. * @return {string} Wrapped text. */ CCC.World.wrap = function(svg, text, width, height) { if (text.length > 1024) { // This algorithm doesn't scale to large texts. // Large texts shouldn't be in speech bubbles anyway. return text; } var minWidth = width; var maxWidth = svg.scaledWidth_ - 10; var measuredWidth, measuredHeight; var dy = CCC.World.measureText(svg, 'Wg').height; function wrapForWidth(width) { measuredWidth = 0; measuredHeight = 0; var paragraphs = text.split('\n'); for (var i = 0; i < paragraphs.length; i++) { paragraphs[i] = CCC.World.wrapLine_(svg, paragraphs[i], width); var lines = paragraphs[i].split('\n'); for (var line of lines) { var size = CCC.World.measureText(svg, line); measuredWidth = Math.max(measuredWidth, size.width); measuredHeight += dy; } } return paragraphs.join('\n'); } var wrappedText = wrapForWidth(width); if (measuredHeight > height) { // If overflowing on height, increase the width using a binary search. // Do not exceed the full width of the SVG. do { if (measuredHeight > height) { minWidth = width; width = Math.round((maxWidth - width) / 2 + width); } else { maxWidth = width; width = Math.round((width - minWidth) / 2 + minWidth); } wrappedText = wrapForWidth(width); } while (maxWidth - minWidth > 10); if (measuredHeight > height) { wrappedText = wrapForWidth(maxWidth); } } return wrappedText; }; /** * Wrap single line of text to the specified width. * @param {!SVGSVGElement} svg SVG element to use. * @param {string} text Text to wrap. * @param {number} limit Width to wrap each line. * @return {string} Wrapped text. * @private */ CCC.World.wrapLine_ = function(svg, text, limit) { if (CCC.World.measureText(svg, text).width <= limit) { // Short text, no need to wrap. return text; } // Split the text into words. var words = text.split(/\b(?=\w)/); // Set limit to be the length of the largest word. for (var word of words) { limit = Math.max(CCC.World.measureText(svg, word).width, limit); } limit = Math.min(svg.scaledWidth_ - 5, limit); // But not wider than panel. var lastScore; var score = -Infinity; var lastText; var lineCount = 1; do { lastScore = score; lastText = text; // Create a list of booleans representing if a space (false) or // a break (true) appears after each word. var wordBreaks = []; // Seed the list with evenly spaced linebreaks. var steps = words.length / lineCount; var insertedBreaks = 1; for (var i = 0; i < words.length - 1; i++) { if (insertedBreaks < (i + 1.5) / steps) { insertedBreaks++; wordBreaks[i] = true; } else { wordBreaks[i] = false; } } wordBreaks = CCC.World.wrapMutate_(svg, words, wordBreaks, limit); score = CCC.World.wrapScore_(svg, words, wordBreaks, limit); text = CCC.World.wrapToText_(words, wordBreaks); lineCount++; } while (score > lastScore); return lastText; }; /** * Compute a score for how good the wrapping is. * @param {!SVGSVGElement} svg SVG element to use. * @param {!Array.} words Array of each word. * @param {!Array.} wordBreaks Array of line breaks. * @param {number} limit Width to wrap each line. * @return {number} Larger the better. * @private */ CCC.World.wrapScore_ = function(svg, words, wordBreaks, limit) { // If this function becomes a performance liability, add caching. // Compute the length of each line. var lines = [[]]; for (var i = 0; i < words.length; i++) { lines[lines.length - 1].push(words[i]); if (wordBreaks[i] === true) { lines.push([]); } } var lineLengths = []; for (var i = 0; i < lines.length; i++) { lines[i] = lines[i].join(''); lineLengths.push(CCC.World.measureText(svg, lines[i]).width); } var score = 0; for (var i = 0; i < lineLengths.length; i++) { // Optimize for width. if (lineLengths[i] > limit) { // -1000 points per unit over limit. score -= (lineLengths[i] - limit) * 1000; } else { // -1 point per unit under limit (scaled to the power of 1.5). score -= Math.pow(Math.abs(limit - lineLengths[i]) * 1, 1.5); } // Optimize for structure. // Add score to line endings after punctuation. var lastLetter = lines[i].trim().slice(-1); if ('.?!'.includes(lastLetter)) { score += 6; } else if (',;)]}'.includes(lastLetter)) { score += 3; } } // All else being equal, the last line should not be longer than the // previous line. For example, this looks wrong: // aaa bbb // ccc ddd eee if (lineLengths.length > 1 && lineLengths[lineLengths.length - 1] <= lineLengths[lineLengths.length - 2]) { score += 5; } // Likewise, the first line should not be longer than the next line. // An ideal bubble with centered text has the first and last lines shorter. if (lineLengths.length > 2 && lineLengths[0] <= lineLengths[1]) { score += 5; } return score; }; /** * Mutate the array of line break locations until an optimal solution is found. * No line breaks are added or deleted, they are simply moved around. * @param {!SVGSVGElement} svg SVG element to use. * @param {!Array.} words Array of each word. * @param {!Array.} wordBreaks Array of line breaks. * @param {number} limit Width to wrap each line. * @return {!Array.} New array of optimal line breaks. * @private */ CCC.World.wrapMutate_ = function(svg, words, wordBreaks, limit) { var bestScore = CCC.World.wrapScore_(svg, words, wordBreaks, limit); var bestBreaks; // Try shifting every line break forward or backward. for (var i = 0; i < wordBreaks.length - 1; i++) { if (wordBreaks[i] === wordBreaks[i + 1]) { continue; } var mutatedWordBreaks = [].concat(wordBreaks); mutatedWordBreaks[i] = !mutatedWordBreaks[i]; mutatedWordBreaks[i + 1] = !mutatedWordBreaks[i + 1]; var mutatedScore = CCC.World.wrapScore_(svg, words, mutatedWordBreaks, limit); if (mutatedScore > bestScore) { bestScore = mutatedScore; bestBreaks = mutatedWordBreaks; } } if (bestBreaks) { // Found an improvement. See if it may be improved further. return CCC.World.wrapMutate_(svg, words, bestBreaks, limit); } // No improvements found. Done. return wordBreaks; }; /** * Reassemble the array of words into text, with the specified line breaks. * @param {!Array.} words Array of each word. * @param {!Array.} wordBreaks Array of line breaks. * @return {string} Plain text. * @private */ CCC.World.wrapToText_ = function(words, wordBreaks) { var text = []; for (var i = 0; i < words.length; i++) { text.push(words[i]); if (wordBreaks[i]) { text.push('\n'); } } return text.join(''); }; /** * Measure one line of text to obtain its height and width. * @param {!SVGSVGElement} svg SVG element to use. * @param {string} text Text to measure. * @return {!SVGRect} Height and width of text. */ CCC.World.measureText = function(svg, text) { if (!svg.measureTextCache_) { svg.measureTextCache_ = Object.create(null); } else if (svg.measureTextCache_[text]) { return svg.measureTextCache_[text]; } var textarea = document.createElementNS(CCC.Common.NS, 'text'); textarea.appendChild(document.createTextNode(text)); svg.appendChild(textarea); var bBox = textarea.getBBox(); svg.removeChild(textarea); svg.measureTextCache_[text] = bBox; return bBox; }; if (!window.TEST) { window.addEventListener('message', CCC.World.receiveMessage, false); window.addEventListener('load', CCC.World.init, false); // Temporary disabling of SVG filters. June 2020 CCC.World.xmlToSvg.ELEMENT_NAMES = null; CCC.World.xmlToSvg.ATTRIBUTE_NAMES = null; CCC.World.xmlToSvg.CLASS_NAMES = null; } ================================================ FILE: static/flamethrower.html ================================================ ================================================ FILE: static/login-close.html ================================================ Code City Login

Login successful.

Close this window.

================================================ FILE: static/securitystore/style.css ================================================ body { background-color: white; font-family: sans-serif; max-width: 50em; margin: 1em; } h1, h2, h3 { font-weight: normal; } .productImage { float: left; height: 60px; margin 1em; width: 60px; } .basketImage { height: 30px; width: 30px; } .footer { font-size: small; margin-top: 2em; } .balls { float: right; } ================================================ FILE: static/securitystore/utils.js ================================================ // Client-side utility functions for formatting prices according to the user's localle. // Format a number as a price. E.g. '1234.5' -> '$1,234.50' function formattedPrice(number) { return Number(number).toLocaleString('en', { style: 'currency', currency: 'USD' }); } // Find all '123' and format them as prices. function renderPrices() { var priceSpans = document.getElementsByClassName('price'); for (var i = 0, priceSpan; (priceSpan = priceSpans[i]); i++) { priceSpan.textContent = formattedPrice(priceSpan.textContent); } } window.addEventListener('DOMContentLoaded', renderPrices); ================================================ FILE: static/style/jfk.css ================================================ body { background-color: #fff; } /* Kennedy buttons. */ .jfk-button { user-select: none; box-shadow: none; background-color: #f5f5f5; background-image: -webkit-linear-gradient(top,#f5f5f5,#f1f1f1); background-image: -moz-linear-gradient(top,#f5f5f5,#f1f1f1); background-image: -ms-linear-gradient(top,#f5f5f5,#f1f1f1); background-image: -o-linear-gradient(top,#f5f5f5,#f1f1f1); background-image: linear-gradient(top,#f5f5f5,#f1f1f1); colour: #444; border: 1px solid rgba(0,0,0,.1); border-radius: 2px; cursor: default; font-size: 11px; font-weight: bold; text-align: center; white-space: nowrap; margin-right: 8px; height: 27px; line-height: 27px; min-width: 54px; outline: 0; padding: 0 8px; position: relative; display: inline-block; font-family: "Arial", "Helvetica", sans-serif; } .jfk-button:hover { box-shadow: none; background-color: #f8f8f8; background-image: -webkit-linear-gradient(top,#f8f8f8,#f1f1f1); background-image: -moz-linear-gradient(top,#f8f8f8,#f1f1f1); background-image: -ms-linear-gradient(top,#f8f8f8,#f1f1f1); background-image: -o-linear-gradient(top,#f8f8f8,#f1f1f1); background-image: linear-gradient(top,#f8f8f8,#f1f1f1); border: 1px solid #c6c6c6; color: #333 } .jfk-button:active { box-shadow: inset 0 1px 2px rgba(0,0,0,.2); } /* Unresponsive 'checked' buttons. */ .jfk-checked, .jfk-checked:hover, .jfk-checked:active { box-shadow: inset 0 1px 2px rgba(0,0,0,.1); background-color: #eee; background-image: -webkit-linear-gradient(top,#eee,#e0e0e0); background-image: -moz-linear-gradient(top,#eee,#e0e0e0); background-image: -ms-linear-gradient(top,#eee,#e0e0e0); background-image: -o-linear-gradient(top,#eee,#e0e0e0); background-image: linear-gradient(top,#eee,#e0e0e0); color: #333 } /* Red 'action' buttons. */ .jfk-button-action { color: #fff; background-color: #d14836; background-image: -webkit-linear-gradient(top,#dd4b39,#d14836); background-image: -moz-linear-gradient(top,#dd4b39,#d14836); background-image: -ms-linear-gradient(top,#dd4b39,#d14836); background-image: -o-linear-gradient(top,#dd4b39,#d14836); background-image: linear-gradient(top,#dd4b39,#d14836); } .jfk-button-action:hover { color: #fff; box-shadow: 0 1px 1px rgba(0,0,0,.2); background-color: #c53727; background-image: -webkit-linear-gradient(top,#dd4b39,#c53727); background-image: -moz-linear-gradient(top,#dd4b39,#c53727); background-image: -ms-linear-gradient(top,#dd4b39,#c53727); background-image: -o-linear-gradient(top,#dd4b39,#c53727); background-image: linear-gradient(top,#dd4b39,#c53727); border: 1px solid #b0281a; border-bottom-color: #af301f } /* Blue 'submit' buttons. */ .jfk-button-submit { color: #fff; background-color: #4d90fe; background-image: -webkit-linear-gradient(top,#4d90fe,#4787ed); background-image: -moz-linear-gradient(top,#4d90fe,#4787ed); background-image: -ms-linear-gradient(top,#4d90fe,#4787ed); background-image: -o-linear-gradient(top,#4d90fe,#4787ed); background-image: linear-gradient(top,#4d90fe,#4787ed); border-color: #3079ed; } .jfk-button-submit:hover { color: #fff; background-color: #357ae8; background-image: -webkit-linear-gradient(top,#4d90fe,#357ae8); background-image: -moz-linear-gradient(top,#4d90fe,#357ae8); background-image: -ms-linear-gradient(top,#4d90fe,#357ae8); background-image: -o-linear-gradient(top,#4d90fe,#357ae8); background-image: linear-gradient(top,#4d90fe,#357ae8); border-color: #2f5bb7; } ================================================ FILE: static/style/svg.css ================================================ /* Enforce a consistent drawing style on all content. */ svg { fill: none; stroke: #000; stroke-linecap: round; stroke-linejoin: round; stroke-width: .7px; } text { fill: #000; font-size: 4pt; stroke-width: 0; } a { cursor: pointer; text-decoration: underline; fill: #00e; } a:hover { fill: #d00; } .strokeNone { stroke: none; } .strokeWhite { stroke: #fff; } .strokeBlack { stroke: #000; } .strokeGrey, .strokeGray { stroke: #888; } .fillNone { fill: none; } .fillWhite { fill: #fff; } .fillBlack { fill: #000; } .fillGrey, .fillGray { fill: #888; } ================================================ FILE: third_party/CodeMirror/AUTHORS ================================================ List of CodeMirror contributors. Updated before every release. 4oo4 4r2r Aaron Brooks Abdelouahab Abdussalam Abdurrahman Abe Fettig Abhishek Gahlot Adam Ahmed Adam King Adam Particka adanlobato Adán Lobato Adrian Aichner Adrian Heine Adrien Bertrand aeroson Ahmad Amireh Ahmad M. Zawawi ahoward Akeksandr Motsjonov Alasdair Smith AlbertHilb Alberto González Palomo Alberto Pose Albert Xing Alexander Pavlov Alexander Schepanovski Alexander Shvets Alexander Solovyov Alexandre Bique alexey-k Alex Piggott Aliaksei Chapyzhenka Allen Sarkisyan Ami Fischman Amin Shali Amin Ullah Khan amshali@google.com Amsul amuntean Amy Ananya Sen anaran AndersMad Anders Nawroth Anderson Mesquita Anders Wåglund Andrea G Andreas Reischuck Andres Taylor Andre von Houck Andrew Cheng Andrew Dassonville Andrey Fedorov Andrey Klyuchnikov Andrey Lushnikov Andrey Shchekin Andy Joslin Andy Kimball Andy Li Angelo angelozerr angelo.zerr@gmail.com Ankit Ankit Ahuja Ansel Santosa Anthony Dugois anthonygego Anthony Gégo Anthony Grimes Anton Kovalyov Apollo Zhu AQNOUCH Mohammed Aram Shatakhtsyan areos Arnab Bose Arsène von Wyss Arthur Müller Arun Narasani as3boyan asolove atelierbram AtomicPages LLC Atul Bhouraskar Aurelian Oancea Axel Lewenhaupt Baptiste Augrain Barret Rennie Bartosz Dziewoński Basarat Ali Syed Bastian Müller belhaj Bem Jones-Bey benbro Beni Cherniavsky-Paskin Benjamin DeCoste Benjamin Young Ben Keen Ben Miller Ben Mosher Bernhard Sirlinger Bert Chang Bharad BigBlueHat Billy Moon binny Bjorn Hansen B Krishna Chaitanya Blaine G blukat29 Bo boomyjee Bo Peng borawjm Brad Metcalf Brandon Frohs Brandon Wamboldt Bret Little Brett Zamir Brian Grinstead Brian Sletten brrd Bruce Mitchener Bryan Massoth Caitlin Potter Calin Barbat callodacity Camilo Roca Casey Klebba César González Íñiguez Chad Jolly Chandra Sekhar Pydi Charles Skelton Cheah Chu Yeow Chris Colborne Chris Coyier Chris Ford Chris Granger Chris Houseknecht Chris Lohfink Chris Morgan Chris Reeves Chris Smith Christian Gruen Christian Oyarzun Christian Petrov christopherblaser Christopher Brown Christopher Kramer Christopher Mitchell Christopher Pfohl Christopher Wallis Chunliang Lyu ciaranj CodeAnimal CodeBitt coderaiser Cole R Lawrence ComFreek Cristian Prieto Curran Kelleher Curtis Gagliardi dagsta daines Dale Jung Dan Bentley Dan Heberden Daniel, Dao Quang Minh Daniele Di Sarli Daniel Faust Daniel Hanggi Daniel Huigens Daniel Kesler Daniel KJ Daniel Neel Daniel Parnell Daniel Thwaites Danila Malyutin Danny Yoo darealshinji Darius Roberts databricks-david-lewis Dave Brondsema Dave MacLachlan Dave Myers David Barnett David H. Bronke David Mignot David Pathakjee David Santana David Vázquez David Whittington deebugger Deep Thought Devin Abbott Devon Carew Dick Choi dignifiedquire Dimage Sapelkin dmaclach Dmitry Kiselyov domagoj412 Dominator008 Domizio Demichelis Doug Blank Doug Wikle Drew Bratcher Drew Hintz Drew Khoury Drini Cami Dror BG duralog dwelle eborden edsharp ekhaled Elisée Emmanuel Schanzer Enam Mijbah Noor Eric Allam Eric Bogard Erik Welander eustas Fabien Dubosson Fabien O'Carroll Fabio Zendhi Nagao Faiza Alsaied Fauntleroy fbuchinger feizhang365 Felipe Lalanne Felix Raab ficristo Filip Noetzel Filip Stollár Filype Pereira finalfantasia flack Florian Felten ForbesLindesay Forbes Lindesay Ford_Lawnmower Forrest Oliphant Franco Catena Frank Wiegand fraxx001 Fredrik Borg FUJI Goro (gfx) Gabriel Gheorghian Gabriel Horner Gabriel Nahmias galambalazs Gary Sheng Gautam Mehta Gavin Douglas gekkoe Geordie Hall George Stephanis geowarin Gerard Braad Gergely Hegykozi Germain Chazot Giovanni Calò Glebov Boris Glenn Jorde Glenn Ruehle goldsmcb Golevka Google LLC Gordon Smith Grant Skinner greengiant Gregory Koberger Grzegorz Mazur Guan Gui Guillaume Massé Guillaume Massé guraga Gustavo Rodrigues Hakan Tunc Hans Engel Harald Schilly Hardest Harshvardhan Gupta Hasan Karahan Heanes Hector Oswaldo Caballero Hélio Hendrik Wallbaum Henrik Haugbølle Herculano Campos hidaiy Hiroyuki Makino hitsthings Hocdoc Hugues Malphettes Ian Beck Ian Davies Ian Dickinson Ian Rose Ian Wehrman Ian Wetherbee Ice White ICHIKAWA, Yuji idleberg ilvalle Ingo Richter Irakli Gozalishvili Ivan Kurnosov Ivoah Jacob Lee Jaimin Jake Peyser Jakob Miland Jakub Vrana Jakub Vrána James Campos James Howard James Thorne Jamie Hill Jamie Morris Janice Leung Jan Jongboom jankeromnes Jan Keromnes Jan Odvarko Jan Schär Jan T. Sott Jared Dean Jared Forsyth Jared Jacobs Jason Jason Barnabe Jason Grout Jason Heeris Jason Johnston Jason San Jose Jason Siefken Jayaprabhakar Jaydeep Solanki Jean Boussier Jeff Blaisdell Jeff Hanke Jeff Jenkins jeffkenton Jeff Pickhardt jem (graphite) Jeremy Parmenter Jim Jim Avery jkaplon JobJob jochenberger Jochen Berger Joel Einbinder joelpinheiro joewalsh Johan Ask John Connor John-David Dalton John Engler John Lees-Miller John Snelson John Van Der Loo Jon Ander Peñalba Jonas Döbertin Jonas Helfer Jonathan Dierksen Jonathan Hart Jonathan Malmaud Jon Gacnik jongalloway Jon Malmaud Jon Sangster Joost-Wim Boekesteijn Joseph Pecoraro Josh Barnes Josh Cohen Josh Soref Joshua Newman Josh Watzman jots jsoojeon ju1ius Juan Benavides Romero Jucovschi Constantin Juho Vuori Julien CROUZET Julien Rebetez Justin Andresen Justin Hileman jwallers@gmail.com kaniga karevn Karol Kayur Patel Kazuhito Hokamura Ken Newman ken restivo Ken Rockot Kevin Earls Kevin Kwok Kevin Muret Kevin Sawicki Kevin Ushey Kier Darby Klaus Silveira Koh Zi Han, Cliff komakino Konstantin Lopuhin koops Kris Ciccarello ks-ifware kubelsmieci KwanEsq Kyle Kelley KyleMcNutt LaKing Lanfei Lanny laobubu Laszlo Vidacs leaf corcoran Lemmon Leonid Khachaturov Leon Sorokin Leonya Khachaturov Liam Newman Libo Cannici Lior Goldberg Lior Shub LloydMilligan LM lochel Lorenzo Simionato Lorenzo Stoakes Louis Mauchet Luca Fabbri Luciano Longo Lu Fangjian Luke Browning Luke Granger-Brown Luke Stagner lynschinzer M1cha Madhura Jayaratne Maksim Lin Maksym Taran Malay Majithia Manideep Manuel Rego Casasnovas Marat Dreizin Marcel Gerber Marcelo Camargo Marco Aurélio Marco Munizaga Marcus Bointon Marek Rudnicki Marijn Haverbeke Mário Gonçalves Mario Pietsch Mark Anderson Mark Dalgleish Mark Lentczner Marko Bonaci Mark Peace Markus Bordihn Markus Olsson Martin Balek Martín Gaitán Martin Hasoň Martin Hunt Martin Laine Martin Zagora Mason Malone Mateusz Paprocki Mathias Bynens mats cronqvist Matt Gaide Matthew Bauer Matthew Beale matthewhayes Matthew Rathbone Matthew Suozzo Matthias Bussonnier Matthias BUSSONNIER Matt MacPherson Matt McDonald Matt Pass Matt Sacks mauricio Maximilian Hils Maxim Kraev Max Kirsch Max Schaefer Max Xiantu mbarkhau McBrainy mce2 melpon meshuamam Metatheos Micah Dubinko Michael Michael Goderbauer Michael Grey Michael Kaminsky Michael Lehenbauer Michael Wadman Michael Walker Michael Zhou Michal Čihař Michal Dorner Michal Kapiczynski Mighty Guava Miguel Castillo mihailik Mika Andrianarijaona Mike Mike Bostock Mike Brevoort Mike Diaz Mike Ivanov Mike Kadin Mike Kobit Milan Szekely MinRK Miraculix87 misfo mkaminsky11 mloginov Moritz Schubotz (physikerwelt) Moritz Schwörer Moshe Wajnberg mps ms mtaran-google Mu-An Chiou Mu-An ✌️ Chiou mzabuawala Narciso Jaramillo Nathan Williams ndr Neil Anderson neon-dev nerbert NetworkNode nextrevision ngn nguillaumin Ng Zhi An Nicholas Bollweg Nicholas Bollweg (Nick) NickKolok Nick Kreeger Nick Small Nicolas Kick Nicolò Ribaudo Niels van Groningen nightwing Nikita Beloglazov Nikita Vasilyev Nikolaj Kappler Nikolay Kostov nilp0inter Nisarg Jhaveri nlwillia noragrossman Norman Rzepka Oleksandr Yakovenko opl- Oreoluwa Onatemowo Oskar Segersvärd overdodactyl pablo pabloferz Pablo Zubieta paddya Page paladox Panupong Pasupat paris Paris Paris Kasidiaris Patil Arpith Patrick Stoica Patrick Strawderman Paul Garvin Paul Ivanov Paul Masson Pavel Pavel Feldman Pavel Petržela Pavel Strashkin Paweł Bartkiewicz peteguhl peter Peter Flynn peterkroon Peter Kroon Philipp A Philipp Markovics Philip Stadermann Pi Delport Pierre Gerold Pieter Ouwerkerk Pontus Melke prasanthj Prasanth J Prayag Verma Prendota Qiang Li Radek Piórkowski Rahul Rahul Anand ramwin1 Randall Mason Randy Burden Randy Edmunds Randy Luecke Raphael Amorim Rasmus Erik Voel Jensen Rasmus Schultz Raymond Hill ray ratchup Ray Ratchup Remi Nyborg Renaud Durlin Reynold Xin Richard Denton Richard van der Meer Richard Z.H. Wang Rishi Goomar Robert Brignull Robert Crossfield Roberto Abdelkader Martínez Pérez robertop23 Robert Plummer Rrandom Rrrandom Ruslan Osmanov Ryan Petrello Ryan Prior ryu-sato sabaca Sam Lee Sam Rawlins Samuel Ainsworth Sam Wilson sandeepshetty Sander AKA Redsandro Sander Verweij santec Sarah McAlear and Wenlin Zhang Sascha Peilicke satamas satchmorun sathyamoorthi Saul Costa S. Chris Colbert SCLINIC\jdecker Scott Aikin Scott Goodhew Sebastian Wilzbach Sebastian Zaha Seren D Sergey Goder Sergey Tselovalnikov Se-Won Kim Shane Liesegang shaund shaun gilchrist Shawn A Shea Bunge sheopory Shil S Shiv Deepak Shmuel Englard Shubham Jain Siamak Mokhtari silverwind Simon Edwards sinkuu snasa soliton4 sonson Sorab Bisht spastorelli srajanpaliwal Stanislav Oaserele stan-z Stas Kobzar Stefan Borsje Steffen Beyer Steffen Bruchmann Steffen Kowalski Stephane Moore Stephen Lavelle Steve Champagne Steve Hoover Steve O'Hara stoskov Stu Kennedy Sungho Kim sverweij Taha Jahangir takamori Tako Schotanus Takuji Shimokawa Takuya Matsuyama Tarmil TDaglis tel Tentone tfjgeorge Thaddee Tyl thanasis TheHowl themrmax think Thomas Brouard Thomas Dvornik Thomas Kluyver Thomas Schmid Tim Alby Tim Baumann Timothy Farrell Timothy Gu Timothy Hatcher Tobias Bertelsen TobiasBg Todd Berman Todd Kennedy Tomas-A Tomas Varaneckas Tom Erik Støwer Tom Klancer Tom MacWright Tom McLaughlin Tony Jian tophf totalamd Travis Heppe Triangle717 Tristan Tarrant TSUYUSATO Kitsune Tugrul Elmas twifkak Tyler Long Vadzim Ramanenka Vaibhav Sagar VapidWorx Vestimir Markov vf Victor Bocharsky Vincent Woo Volker Mische vtripolitakis wdouglashall Weiyan Shao wenli Wes Cossick Wesley Wiser Weston Ruter Will Binns-Smith Will Dean William Jamieson William Stein Willy Wojtek Ptak wonderboyjon Wu Cheng-Han Xavier Mendez Yassin N. Hassan YNH Webdev yoongu Yunchi Luo Yuvi Panda Yvonnick Esnault Zac Anger Zachary Dremann Zeno Rocha Zhang Hao Ziv zziuni 魏鹏刚 ================================================ FILE: third_party/CodeMirror/CHANGELOG.md ================================================ ## 5.43.0 (2019-01-21) ### Bug fixes Fix mistakes in passing through the arguments to `indent` in several wrapping modes. [javascript mode](https://codemirror.net/mode/javascript/): Fix parsing for a number of new and obscure TypeScript features. [ruby mode](https://codemirror.net/mode/ruby): Support indented end tokens for heredoc strings. ### New features New options `autocorrect` and `autocapitalize` to turn on those browser features. ## 5.42.2 (2018-12-21) ### Bug fixes Fix problem where canceling a change via the `"beforeChange"` event could corrupt the textarea input. Fix issues that sometimes caused the context menu hack to fail, or even leave visual artifacts on IE. [vim bindings](https://codemirror.net/demo/vim.html): Make it possible to select text between angle brackets. [css mode](https://codemirror.net/mode/css/): Fix tokenizing of CSS variables. [python mode](https://codemirror.net/mode/python/): Fix another bug in tokenizing of format strings. [soy mode](https://codemirror.net/mode/soy/): More accurate highlighting. ## 5.42.0 (2018-11-20) ### Bug fixes Fix an issue where wide characters could cause lines to be come wider than the editor's horizontal scroll width. Optimize handling of window resize events. [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. [python mode](https://codemirror.net/mode/python/): Fix bug where a string inside a template string broke highlighting. [swift mode](https://codemirror.net/mode/swift): Support multi-line strings. ### New features The [`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. [vim bindings](https://codemirror.net/demo/vim.html): Add support for the `=` binding. ## 5.41.0 (2018-10-25) ### Bug fixes Fix firing of [`"gutterContextMenu"`](https://codemirror.net/doc/manual.html#event_gutterContextMenu) event on Firefox. Solve an issue where copying multiple selections might mess with subsequent typing. Don't crash when [`endOperation`](https://codemirror.net/doc/manual.html#endOperation) is called with no operation active. [vim bindings](https://codemirror.net/demo/vim.html): Fix insert mode repeat after visualBlock edits. [scheme mode](https://codemirror.net/mode/scheme/index.html): Improve highlighting of quoted expressions. [soy mode](https://codemirror.net/mode/soy/): Support injected data and `@param` in comments. [objective c mode](https://codemirror.net/mode/clike/): Improve conformance to the actual language. ### New features A new [`selectionsMayTouch`](https://codemirror.net/doc/manual.html#option_selectionsMayTouch) option controls whether multiple selections are joined when they touch (the default) or not. [vim bindings](https://codemirror.net/demo/vim.html): Add `noremap` binding command. ## 5.40.2 (2018-09-20) ### Bug fixes Fix firing of `gutterContextMenu` event on Firefox. Add `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. [clojure mode](https://codemirror.net/mode/clojure/index.html): Clean up and improve. ## 5.40.0 (2018-08-25) ### Bug fixes [closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Fix issue where bracket-closing wouldn't work before punctuation. [panel addon](https://codemirror.net/doc/manual.html#addon_panel): Fix problem where replacing the last remaining panel dropped the newly added panel. [hardwrap addon](https://codemirror.net/doc/manual.html#addon_hardwrap): Fix an infinite loop when the indention is greater than the target column. [jinja2](https://codemirror.net/mode/jinja2/) and [markdown](https://codemirror.net/mode/markdown/) modes: Add comment metadata. ### New features New 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. ## 5.39.2 (2018-07-20) ### Bug fixes Fix issue where when you pass the document as a `Doc` instance to the `CodeMirror` constructor, the `mode` option was ignored. Fix bug where line height could be computed wrong with a line widget below a collapsed line. Fix overeager `.npmignore` dropping the `bin/source-highlight` utility from the distribution. [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. ## 5.39.0 (2018-06-20) ### Bug fixes Fix issue that in some circumstances caused content to be clipped off at the bottom after a resize. [markdown mode](https://codemirror.net/mode/markdown/): Improve handling of blank lines in HTML tags. ### New features [stex mode](https://codemirror.net/mode/stex/): Add an `inMathMode` option to start the mode in math mode. ## 5.38.0 (2018-05-21) ### Bug fixes Improve reliability of noticing a missing mouseup event during dragging. Make sure `getSelection` is always called on the correct document. Fix interpretation of line breaks and non-breaking spaces inserted by renderer in contentEditable mode. Work around some browsers inexplicably making the fake scrollbars focusable. Make sure `coordsChar` doesn't return positions inside collapsed ranges. [javascript mode](https://codemirror.net/mode/javascript/): Support block scopes, bindingless catch, bignum suffix, `s` regexp flag. [markdown mode](https://codemirror.net/mode/markdown/): Adjust a wasteful regexp. [show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint): Allow opening the control without any item selected. ### New features New theme: [darcula](https://codemirror.net/demo/theme.html#darcula). [dialog addon](https://codemirror.net/doc/manual.html#addon_dialog): Add a CSS class (`dialog-opened`) to the editor when a dialog is open. ## 5.37.0 (2018-04-20) ### Bug fixes Suppress keypress events during composition, for platforms that don't properly do this themselves. [xml-fold addon](https://codemirror.net/demo/folding.html): Improve handling of line-wrapped opening tags. [javascript mode](https://codemirror.net/mode/javascript/): Improve TypeScript support. [python mode](https://codemirror.net/mode/python/): Highlight expressions inside format strings. ### New features [vim bindings](https://codemirror.net/demo/vim.html): Add support for '(' and ')' movement. New 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). ## 5.36.0 (2018-03-20) ### Bug fixes Make sure all document-level event handlers are registered on the document that the editor is part of. Fix issue that prevented edits whose origin starts with `+` from being combined in history events for an editor-less document. [multiplex addon](https://codemirror.net/demo/multiplex.html): Improve handling of indentation. [merge addon](https://codemirror.net/doc/manual.html#addon_merge): Use CSS `:after` element to style the scroll-lock icon. [javascript-hint addon](https://codemirror.net/doc/manual.html#addon_javascript-hint): Don't provide completions in JSON mode. [continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Fix numbering error. [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. [markdown mode](https://codemirror.net/mode/markdown/): Fix a regexp with potentially exponental complexity. ### New features New theme: [lucario](https://codemirror.net/demo/theme.html#lucario). ## 5.35.0 (2018-02-20) ### Bug fixes Fix problem where selection undo might change read-only documents. Fix crash when calling `addLineWidget` on a document that has no attached editor. [searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Fix behavior of `^` in multiline regexp mode. [match-highlighter addon](https://codemirror.net/doc/manual.html#addon_match-highlighter): Fix problem with matching words that have regexp special syntax in them. [sublime bindings](https://codemirror.net/demo/sublime.html): Fix `addCursorToSelection` for short lines. [javascript mode](https://codemirror.net/mode/javascript/): Support TypeScript intersection types, dynamic `import`. [stex mode](https://codemirror.net/mode/stex/): Fix parsing of `\(` `\)` delimiters, recognize more atom arguments. [haskell mode](https://codemirror.net/mode/haskell/): Highlight more builtins, support `<*` and `*>`. [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. [dockerfile mode](https://codemirror.net/mode/dockerfile/): Highlight strings and ports, recognize more instructions. ### New features [vim bindings](https://codemirror.net/demo/vim.html): Support alternative delimiters in replace command. ## 5.34.0 (2018-01-29) ### Bug fixes [markdown mode](https://codemirror.net/mode/markdown/): Fix a problem where inline styles would persist across list items. [sublime bindings](https://codemirror.net/demo/sublime.html): Fix the `toggleBookmark` command. [closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Improve behavior when closing triple quotes. [xml-fold addon](https://codemirror.net/demo/folding.html): Fix folding of line-broken XML tags. [shell mode](https://codemirror.net/mode/shell/): Better handling of nested quoting. [javascript-lint addon](https://codemirror.net/demo/lint.html): Clean up and simplify. [matchbrackets addon](https://codemirror.net/doc/manual.html#addon_matchbrackets): Fix support for multiple editors at the same time. ### New features New themes: [oceanic-next](https://codemirror.net/demo/theme.html#oceanic-next) and [shadowfox](https://codemirror.net/demo/theme.html#shadowfox). ## 5.33.0 (2017-12-21) ### Bug fixes [lint addon](https://codemirror.net/doc/manual.html#addon_lint): Make updates more efficient. [css mode](https://codemirror.net/mode/css/): The mode is now properly case-insensitive. [continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Fix broken handling of unordered lists introduced in previous release. [swift](https://codemirror.net/mode/swift) and [scala](https://codemirror.net/mode/clike/) modes: Support nested block comments. [mllike mode](https://codemirror.net/mode/mllike/index.html): Improve OCaml support. [sublime bindings](https://codemirror.net/demo/sublime.html): Use the proper key bindings for `addCursorToNextLine` and `addCursorToPrevLine`. ### New features [jsx mode](https://codemirror.net/mode/jsx/index.html): Support JSX fragments. [closetag addon](https://codemirror.net/demo/closetag.html): Add an option to disable auto-indenting. ## 5.32.0 (2017-11-22) ### Bug fixes Increase contrast on default bracket-matching colors. [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. [comment addon](https://codemirror.net/doc/manual.html#addon_comment): Fix bug when uncommenting a comment that spans all but the last selected line. [searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Fix bug in case folding. [emacs bindings](https://codemirror.net/demo/emacs.html): Prevent single-character deletions from resetting the kill ring. [closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Tweak quote matching behavior. ### New features [continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Increment ordered list numbers when adding one. ## 5.31.0 (2017-10-20) ### Bug fixes Further improve selection drawing and cursor motion in right-to-left documents. [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). [continuecomment addon](https://codemirror.net/doc/manual.html#addon_continuecomment): Fix bug when pressing enter after a single-line block comment. [markdown mode](https://codemirror.net/mode/markdown/): Fix issue with leaving indented fenced code blocks. [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. ### New features Modes 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. ## 5.30.0 (2017-09-20) ### Bug fixes Fixed a number of issues with drawing right-to-left selections and mouse selection in bidirectional text. [search addon](https://codemirror.net/demo/search/): Fix crash when restarting search after doing empty search. [mark-selection addon](http://cm/doc/manual.html#addon_mark-selection): Fix off-by-one bug. [tern addon](https://codemirror.net/demo/tern.html): Fix bad request made when editing at the bottom of a large document. [javascript mode](https://codemirror.net/mode/javascript/): Improve parsing in a number of corner cases. [markdown mode](https://codemirror.net/mode/markdown/): Fix crash when a sub-mode doesn't support indentation, allow uppercase X in task lists. [gfm mode](https://codemirror.net/mode/gfm/): Don't highlight SHA1 'hashes' without numbers to avoid false positives. [soy mode](https://codemirror.net/mode/soy/): Support injected data and `@param` in comments. ### New features [simple mode addon](https://codemirror.net/demo/simplemode.html): Allow groups in regexps when `token` isn't an array. ## 5.29.0 (2017-08-24) ### Bug fixes Fix crash in contentEditable input style when editing near a bookmark. Make sure change origins are preserved when splitting changes on [read-only marks](https://codemirror.net/doc/manual.html#mark_readOnly). [javascript mode](https://codemirror.net/mode/javascript/): More support for TypeScript syntax. [d mode](https://codemirror.net/mode/d/): Support nested comments. [python mode](https://codemirror.net/mode/python/): Improve tokenizing of operators. [markdown mode](https://codemirror.net/mode/markdown/): Further improve CommonMark conformance. [css mode](https://codemirror.net/mode/css/): Don't run comment tokens through the mode's state machine. [shell mode](https://codemirror.net/mode/shell/): Allow strings to span lines. [search addon](https://codemirror.net/demo/search/): Fix crash in persistent search when `extraKeys` is null. ## 5.28.0 (2017-07-21) ### Bug fixes Fix copying of, or replacing editor content with, a single dash character when copying a big selection in some corner cases. Make [`"goLineLeft"`](https://codemirror.net/doc/manual.html#command_goLineLeft)/`"goLineRight"` behave better on wrapped lines. [sql mode](https://codemirror.net/mode/sql/): Fix tokenizing of multi-dot operator and allow digits in subfield names. [searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Fix infinite loop on some composed character inputs. [markdown mode](https://codemirror.net/mode/markdown/): Make list parsing more CommonMark-compliant. [gfm mode](https://codemirror.net/mode/gfm/): Highlight colon syntax for emoji. ### New features Expose [`startOperation`](https://codemirror.net/doc/manual.html#startOperation) and `endOperation` for explicit operation management. [sublime bindings](https://codemirror.net/demo/sublime.html): Add extend-selection (Ctrl-Alt- or Cmd-Shift-Up/Down). ## 5.27.4 (2017-06-29) ### Bug fixes Fix crash when using mode lookahead. [markdown mode](https://codemirror.net/mode/markdown/): Don't block inner mode's indentation support. ## 5.27.2 (2017-06-22) ### Bug fixes Fix crash in the [simple mode](https://codemirror.net/demo/simplemode.html)< addon. ## 5.27.0 (2017-06-22) ### Bug fixes Fix infinite loop in forced display update. Properly disable the hidden textarea when `readOnly` is `"nocursor"`. Calling the `Doc` constructor without `new` works again. [sql mode](https://codemirror.net/mode/sql/): Handle nested comments. [javascript mode](https://codemirror.net/mode/javascript/): Improve support for TypeScript syntax. [markdown mode](https://codemirror.net/mode/markdown/): Fix bug where markup was ignored on indented paragraph lines. [vim bindings](https://codemirror.net/demo/vim.html): Referencing invalid registers no longer causes an uncaught exception. [rust mode](https://codemirror.net/mode/rust/): Add the correct MIME type. [matchbrackets addon](https://codemirror.net/doc/manual.html#addon_matchbrackets): Document options. ### New features Mouse 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. The behavior of mouse selection and dragging can now be customized with the [`configureMouse`](https://codemirror.net/doc/manual.html#option_configureMouse) option. Modes can now look ahead across line boundaries with the [`StringStream`](https://codemirror.net/doc/manual.html#StringStream)`.lookahead` method. Introduces a `"type"` token type, makes modes that recognize types output it, and add styling for it to the themes. New [`pasteLinesPerSelection`](https://codemirror.net/doc/manual.html#option_pasteLinesPerSelection) option to control the behavior of pasting multiple lines into multiple selections. [searchcursor addon](https://codemirror.net/doc/manual.html#addon_searchcursor): Support multi-line regular expression matches, and normalize strings when matching. ## 5.26.0 (2017-05-22) ### Bug fixes In textarea-mode, don't reset the input field during composition. More careful restoration of selections in widgets, during editor redraw. [javascript mode](https://codemirror.net/mode/javascript/): More TypeScript parsing fixes. [julia mode](https://codemirror.net/mode/julia/): Fix issue where the mode gets stuck. [markdown mode](https://codemirror.net/mode/markdown/): Understand cross-line links, parse all bracketed things as links. [soy mode](https://codemirror.net/mode/soy/): Support single-quoted strings. [go mode](https://codemirror.net/mode/go/): Don't try to indent inside strings or comments. ### New features [vim bindings](https://codemirror.net/demo/vim.html): Parse line offsets in line or range specs. ## 5.25.2 (2017-04-20) ### Bug fixes Better handling of selections that cover the whole viewport in contentEditable-mode. No longer accidentally scroll the editor into view when calling `setValue`. Work around Chrome Android bug when converting screen coordinates to editor positions. Make sure long-clicking a selection sets a cursor and doesn't show the editor losing focus. Fix issue where pointer events were incorrectly disabled on Chrome's overlay scrollbars. [javascript mode](https://codemirror.net/mode/javascript/): Recognize annotations and TypeScript-style type parameters. [shell mode](https://codemirror.net/mode/shell/): Handle nested braces. [markdown mode](https://codemirror.net/mode/markdown/): Make parsing of strong/em delimiters CommonMark-compliant. ## 5.25.0 (2017-03-20) ### Bug fixes In contentEditable-mode, properly locate changes that repeat a character when inserted with IME. Fix handling of selections bigger than the viewport in contentEditable mode. Improve handling of changes that insert or delete lines in contentEditable mode. Count Unicode control characters 0x80 to 0x9F as special (non-printing) chars. Fix handling of shadow DOM roots when finding the active element. Add `role=presentation` to more DOM elements to improve screen reader support. [merge addon](https://codemirror.net/doc/manual.html#addon_merge): Make aligning of unchanged chunks more robust. [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. [javascript mode](https://codemirror.net/mode/javascript/): Improve support for TypeScript syntax. [r mode](https://codemirror.net/mode/r/): Fix indentation after semicolon-less statements. [shell mode](https://codemirror.net/mode/shell/): Properly handle escaped parentheses in parenthesized expressions. [markdown mode](https://codemirror.net/mode/markdown/): Fix a few bugs around leaving fenced code blocks. [soy mode](https://codemirror.net/mode/soy/): Improve indentation. ### New features [lint addon](https://codemirror.net/doc/manual.html#addon_lint): Support asynchronous linters that return promises. [continuelist addon](https://codemirror.net/doc/manual.html#addon_continuelist): Support continuing task lists. [vim bindings](https://codemirror.net/demo/vim.html): Make Y behave like yy. [sql mode](https://codemirror.net/mode/sql/): Support sqlite dialect. ## 5.24.2 (2017-02-22) ### Bug fixes [javascript mode](https://codemirror.net/mode/javascript/): Support computed class method names. [merge addon](https://codemirror.net/doc/manual.html#addon_merge): Improve aligning of unchanged code in the presence of marks and line widgets. ## 5.24.0 (2017-02-20) ### Bug fixes A cursor directly before a line-wrapping break is now drawn before or after the line break depending on which direction you arrived from. Visual cursor motion in line-wrapped right-to-left text should be much more correct. Fix bug in handling of read-only marked text. [shell mode](https://codemirror.net/mode/shell/): Properly tokenize nested parentheses. [python mode](https://codemirror.net/mode/python/): Support underscores in number literals. [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. [css mode](https://codemirror.net/mode/css/): Expose `lineComment` property for LESS and SCSS dialects. Recognize vendor prefixes on pseudo-elements. [julia mode](https://codemirror.net/mode/julia/): Properly indent `elseif` lines. [markdown mode](https://codemirror.net/mode/markdown/): Properly recognize the end of fenced code blocks when inside other markup. [scala mode](https://codemirror.net/mode/clike/): Improve handling of operators containing #, @, and : chars. [xml mode](https://codemirror.net/mode/xml/): Allow dashes in HTML tag names. [javascript mode](https://codemirror.net/mode/javascript/): Improve parsing of async methods, TypeScript-style comma-separated superclass lists. [indent-fold addon](https://codemirror.net/demo/folding.html): Ignore comment lines. ### New features Positions now support a `sticky` property which determines whether they should be associated with the character before (value `"before"`) or after (value `"after"`) them. [vim bindings](https://codemirror.net/demo/vim.html): Make it possible to remove built-in bindings through the API. [comment addon](https://codemirror.net/doc/manual.html#addon_comment): Support a per-mode useInnerComments option to optionally suppress descending to the inner modes to get comment strings. ### Breaking changes The [sass mode](https://codemirror.net/mode/sass/) now depends on the [css mode](https://codemirror.net/mode/css/). ## 5.23.0 (2017-01-19) ### Bug fixes Presentation-related elements DOM elements are now marked as such to help screen readers. [markdown mode](https://codemirror.net/mode/markdown/): Be more picky about what HTML tags look like to avoid false positives. ### New features `findModeByMIME` now understands `+json` and `+xml` MIME suffixes. [closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Add support for an `override` option to ignore language-specific defaults. [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. ## 5.22.2 (2017-01-12) ### Bug fixes Include rollup.config.js in NPM package, so that it can be used to build from source. ## 5.22.0 (2016-12-20) ### Bug fixes [sublime bindings](https://codemirror.net/demo/sublime.html): Make `selectBetweenBrackets` work with multiple cursors. [javascript mode](https://codemirror.net/mode/javascript/): Fix issues with parsing complex TypeScript types, imports, and exports. A contentEditable editor instance with autofocus enabled no longer crashes during initializing. ### New features [emacs bindings](https://codemirror.net/demo/emacs.html): Export `CodeMirror.emacs` to allow other addons to hook into Emacs-style functionality. [active-line addon](https://codemirror.net/doc/manual.html#addon_active-line): Add `nonEmpty` option. New event: [`optionChange`](https://codemirror.net/doc/manual.html#event_optionChange). ## 5.21.0 (2016-11-21) ### Bug fixes Tapping/clicking the editor in [contentEditable mode](https://codemirror.net/doc/manual.html#option_inputStyle) on Chrome now puts the cursor at the tapped position. Fix various crashes and misbehaviors when reading composition events in [contentEditable mode](https://codemirror.net/doc/manual.html#option_inputStyle). Catches and ignores an IE 'Unspecified Error' when creating an editor in an iframe before there is a ``. [merge addon](https://codemirror.net/doc/manual.html#addon_merge): Fix several issues in the chunk-aligning feature. [verilog mode](https://codemirror.net/mode/verilog): Rewritten to address various issues. [julia mode](https://codemirror.net/mode/julia): Recognize Julia 0.5 syntax. [swift mode](https://codemirror.net/mode/swift): Various fixes and adjustments to current syntax. [markdown mode](https://codemirror.net/mode/markdown): Allow lists without a blank line above them. ### New features The [`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. The [`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. [ruby mode](https://codemirror.net/mode/ruby): `else` and `elsif` are now immediately indented. [vim bindings](https://codemirror.net/demo/vim.html): Bind Ctrl-T and Ctrl-D to in- and dedent in insert mode. ## 5.20.2 (2016-10-21) ### Bug fixes Fix `CodeMirror.version` returning the wrong version number. ## 5.20.0 (2016-10-20) ### Bug fixes Make `newlineAndIndent` command work with multiple cursors on the same line. Make sure keypress events for backspace are ignored. Tokens styled with overlays no longer get a nonsense `cm-cm-overlay` class. Line endings for pasted content are now normalized to the editor's [preferred ending](https://codemirror.net/doc/manual.html#option_lineSeparator). [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. [css mode](https://codemirror.net/mode/css): Fix highlighting of mixed-case keywords. [closebrackets addon](https://codemirror.net/doc/manual.html#addon_closebrackets): Improve behavior when typing a quote before a string. ### New features The 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). The [`refresh`](https://codemirror.net/doc/manual.html#event_refresh) event is now documented and stable. ## 5.19.0 (2016-09-20) ### Bugfixes [erlang mode](https://codemirror.net/mode/erlang): Fix mode crash when trying to read an empty context. [comment addon](https://codemirror.net/doc/manual.html#addon_comment): Fix broken behavior when toggling comments inside a comment. xml-fold addon: Fix a null-dereference bug. Page up and page down now do something even in single-line documents. Fix an issue where the cursor position could be off in really long (~8000 character) tokens. ### New features [javascript mode](https://codemirror.net/mode/javascript): Better indentation when semicolons are missing. Better support for TypeScript classes, optional parameters, and the `type` keyword. The [`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. ## 5.18.2 (2016-08-23) ### Bugfixes [vue mode](https://codemirror.net/mode/vue): Fix outdated references to renamed Pug mode dependency. ## 5.18.0 (2016-08-22) ### Bugfixes Make sure [gutter backgrounds](https://codemirror.net/doc/manual.html#addLineClass) stick to the rest of the gutter during horizontal scrolling. The contenteditable [`inputStyle`](https://codemirror.net/doc/manual.html#option_inputStyle) now properly supports pasting on pre-Edge IE versions. [javascript mode](https://codemirror.net/mode/javascript): Fix some small parsing bugs and improve TypeScript support. [matchbrackets addon](https://codemirror.net/doc/manual.html#addon_matchbrackets): Fix bug where active highlighting was left in editor when the addon was disabled. [match-highlighter addon](https://codemirror.net/doc/manual.html#addon_match-highlighter): Only start highlighting things when the editor gains focus. [javascript-hint addon](https://codemirror.net/doc/manual.html#addon_javascript-hint): Also complete non-enumerable properties. ### New features The [`addOverlay`](https://codemirror.net/doc/manual.html#addOverlay) method now supports a `priority` option to control the order in which overlays are applied. MIME types that end in `+json` now default to the JSON mode when the MIME itself is not defined. ### Breaking changes The mode formerly known as Jade was renamed to [Pug](https://codemirror.net/mode/pug). The [Python mode](https://codemirror.net/mode/python) now defaults to Python 3 (rather than 2) syntax. ## 5.17.0 (2016-07-19) ### Bugfixes Fix problem with wrapped trailing whitespace displaying incorrectly. Prevent IME dialog from overlapping typed content in Chrome. Improve measuring of characters near a line wrap. [javascript mode](https://codemirror.net/mode/javascript): Improve support for `async`, allow trailing commas in `import` lists. [vim bindings](https://codemirror.net/demo/vim.html): Fix backspace in replace mode. [sublime bindings](https://codemirror.net/demo/sublime.html): Fix some key bindings on OS X to match Sublime Text. ### New features [markdown mode](https://codemirror.net/mode/markdown): Add more classes to image links in highlight-formatting mode. ## 5.16.0 (2016-06-20) ### Bugfixes Fix glitches when dragging content caused by the drop indicator receiving mouse events. Make Control-drag work on Firefox. Make clicking or selection-dragging at the end of a wrapped line select the right position. [show-hint addon](https://codemirror.net/doc/manual.html#addon_show-hint): Prevent widget scrollbar from hiding part of the hint text. [rulers addon](https://codemirror.net/doc/manual.html#addon_rulers): Prevent rulers from forcing a horizontal editor scrollbar. ### New features [search addon](https://codemirror.net/doc/manual.html#addon_search): Automatically bind search-related keys in persistent dialog. [sublime keymap](https://codemirror.net/demo/sublime.html): Add a multi-cursor aware smart backspace binding. ## 5.15.2 (2016-05-20) ### Bugfixes Fix a critical document corruption bug that occurs when a document is gradually grown. ## 5.15.0 (2016-05-20) ### Bugfixes Fix bug that caused the selection to reset when focusing the editor in contentEditable input mode. Fix issue where not all ASCII control characters were being replaced by placeholders. Remove the assumption that all modes have a `startState` method from several wrapping modes. Fix issue where the editor would complain about overlapping collapsed ranges when there weren't any. Optimize document tree building when loading or pasting huge chunks of content. [markdown mode](https://codemirror.net/mode/markdown/): Fix several issues in matching link targets. [clike mode](https://codemirror.net/mode/clike/): Improve indentation of C++ template declarations. ### New features Explicitly bind Ctrl-O on OS X to make that binding (“open line”) act as expected. Pasting [linewise-copied](https://codemirror.net/doc/manual.html#option_lineWiseCopyCut) content when there is no selection now inserts the lines above the current line. [javascript mode](https://codemirror.net/mode/javascript/): Support `async`/`await` and improve support for TypeScript type syntax. ## 5.14.2 (2016-04-20) ### Bugfixes Push 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. Set `dataTransfer.effectAllowed` in `dragstart` handler to help browsers use the right drag icon. Add the [mbox mode](https://codemirror.net/mode/mbox/index.html) to `mode/meta.js`. ## 5.14.0 (2016-04-20) ### Bugfixes [`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. [vim bindings](https://codemirror.net/demo/vim.html): Only call `.save()` when it is actually available. [comment addon](https://codemirror.net/doc/manual.html#addon_comment): Be careful not to mangle multi-line strings. [Python mode](https://codemirror.net/mode/python/index.html): Improve distinguishing of decorators from `@` operators. [`findMarks`](https://codemirror.net/doc/manual.html#findMarks): No longer return marks that touch but don't overlap given range. ### New features [vim bindings](https://codemirror.net/demo/vim.html): Add yank command. [match-highlighter addon](https://codemirror.net/doc/manual.html#addon_match-highlighter): Add `trim` option to disable ignoring of whitespace. [PowerShell mode](https://codemirror.net/mode/powershell/index.html): Added. [Yacas mode](https://codemirror.net/mode/yacas/index.html): Added. [Web IDL mode](https://codemirror.net/mode/webidl/index.html): Added. [SAS mode](https://codemirror.net/mode/sas/index.html): Added. [mbox mode](https://codemirror.net/mode/mbox/index.html): Added. ## 5.13.2 (2016-03-23) ### Bugfixes Solves a problem where the gutter would sometimes not extend all the way to the end of the document. ## 5.13.0 (2016-03-21) ### New features New DOM event forwarded: [`"dragleave"`](https://codemirror.net/doc/manual.html#event_dom). [protobuf mode](https://codemirror.net/mode/protobuf/index.html): Newly added. ### Bugfixes Fix problem where [`findMarks`](https://codemirror.net/doc/manual.html#findMarks) sometimes failed to find multi-line marks. Fix crash that showed up when atomic ranges and bidi text were combined. [show-hint addon](https://codemirror.net/demo/complete.html): Completion widgets no longer close when the line indented or dedented. [merge addon](https://codemirror.net/demo/merge.html): Fix bug when merging chunks at the end of the file. [placeholder addon](https://codemirror.net/doc/manual.html#addon_placeholder): No longer gets confused by [`swapDoc`](https://codemirror.net/doc/manual.html#swapDoc). [simplescrollbars addon](https://codemirror.net/doc/manual.html#addon_simplescrollbars): Fix invalid state when deleting at end of document. [clike mode](https://codemirror.net/mode/clike/index.html): No longer gets confused when a comment starts after an operator. [markdown mode](https://codemirror.net/mode/markdown/index.html): Now supports CommonMark-style flexible list indentation. [dylan mode](https://codemirror.net/mode/dylan/index.html): Several improvements and fixes. ## 5.12.0 (2016-02-19) ### New features [Vim bindings](https://codemirror.net/demo/vim.html): Ctrl-Q is now an alias for Ctrl-V. [Vim bindings](https://codemirror.net/demo/vim.html): The Vim API now exposes an `unmap` method to unmap bindings. [active-line addon](https://codemirror.net/demo/activeline.html): This addon can now style the active line's gutter. [FCL mode](https://codemirror.net/mode/fcl/): Newly added. [SQL mode](https://codemirror.net/mode/sql/): Now has a Postgresql dialect. ### Bugfixes Fix [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. Use 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. Solve a [problem](https://github.com/codemirror/CodeMirror/issues/3821) where the horizontal scrollbar could hide text in Firefox. Fix a [bug](https://github.com/codemirror/CodeMirror/issues/3834) that caused phantom scroll space under the text in some situations. [Sublime Text bindings](https://codemirror.net/demo/sublime.html): Bind delete-line to Shift-Ctrl-K on OS X. [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. [Markdown mode](https://codemirror.net/mode/markdown/): Ignore backslashes in code fragments. [Markdown mode](https://codemirror.net/mode/markdown/): Use whichever mode is registered as `text/html` to parse HTML. [Clike mode](https://codemirror.net/mode/clike/): Improve indentation of Scala `=>` functions. [Python mode](https://codemirror.net/mode/python/): Improve indentation of bracketed code. [HTMLMixed mode](https://codemirror.net/mode/htmlmixed/): Support multi-line opening tags for sub-languages (`

Active Line Demo

Styling the current cursor line.

================================================ FILE: third_party/CodeMirror/demo/anywordhint.html ================================================ CodeMirror: Any Word Completion Demo

Any Word Completion Demo

Press ctrl-space to activate autocompletion. The completion uses the anyword-hint.js module, which simply looks at nearby words in the buffer and completes to those.

================================================ FILE: third_party/CodeMirror/demo/bidi.html ================================================ CodeMirror: Bi-directional Text Demo

Bi-directional Text Demo

Editor default direction:
HTML document direction:

Demonstration of bi-directional text support. See the related blog post for more background.

================================================ FILE: third_party/CodeMirror/demo/btree.html ================================================  CodeMirror: B-Tree visualization

B-Tree visualization

================================================ FILE: third_party/CodeMirror/demo/buffers.html ================================================ CodeMirror: Multiple Buffer & Split View Demo

Multiple Buffer & Split View Demo

Select buffer:    
Select buffer:    

Demonstration of using linked documents to provide a split view on a document, and using swapDoc to use a single editor to display multiple documents.

================================================ FILE: third_party/CodeMirror/demo/changemode.html ================================================ CodeMirror: Mode-Changing Demo

Mode-Changing Demo

On changes to the content of the above editor, a (crude) script tries to auto-detect the language used, and switches the editor to either JavaScript or Scheme mode based on that.

================================================ FILE: third_party/CodeMirror/demo/closebrackets.html ================================================ CodeMirror: Closebrackets Demo

Closebrackets Demo

================================================ FILE: third_party/CodeMirror/demo/closetag.html ================================================ CodeMirror: Close-Tag Demo

Close-Tag Demo

================================================ FILE: third_party/CodeMirror/demo/complete.html ================================================ CodeMirror: Autocomplete Demo

Autocomplete Demo

Press ctrl-space to activate autocompletion. Built on top of the show-hint and javascript-hint addons.

================================================ FILE: third_party/CodeMirror/demo/emacs.html ================================================ CodeMirror: Emacs bindings demo

Emacs bindings demo

The emacs keybindings are enabled by including keymap/emacs.js and setting the keyMap option to "emacs". Because CodeMirror's internal API is quite different from Emacs, they are only a loose approximation of actual emacs bindings, though.

Also note that a lot of browsers disallow certain keys from being captured. For example, Chrome blocks both Ctrl-W and Ctrl-N, with the result that idiomatic use of Emacs keys will constantly close your tab or open a new window.

================================================ FILE: third_party/CodeMirror/demo/folding.html ================================================ CodeMirror: Code Folding Demo

Code Folding Demo

JavaScript:
HTML:
Python:
Markdown:
================================================ FILE: third_party/CodeMirror/demo/fullscreen.html ================================================ CodeMirror: Full Screen Editing

Full Screen Editing

Demonstration of the fullscreen addon. Press F11 when cursor is in the editor to toggle full screen editing. Esc can also be used to exit full screen editing.

================================================ FILE: third_party/CodeMirror/demo/hardwrap.html ================================================ CodeMirror: Hard-wrapping Demo

Hard-wrapping Demo

Demonstration of the hardwrap addon. The above editor has its change event hooked up to the wrapParagraphsInRange method, so that the paragraphs are reflown as you are typing.

================================================ FILE: third_party/CodeMirror/demo/html5complete.html ================================================ CodeMirror: HTML completion demo

HTML completion demo

Shows the XML completer parameterized with information about the tags in HTML. Press ctrl-space to activate completion.

================================================ FILE: third_party/CodeMirror/demo/indentwrap.html ================================================ CodeMirror: Indented wrapped line demo

Indented wrapped line demo

This page uses a hack on top of the "renderLine" event to make wrapped text line up with the base indentation of the line.

================================================ FILE: third_party/CodeMirror/demo/lint.html ================================================ CodeMirror: Linter Demo

Linter Demo

================================================ FILE: third_party/CodeMirror/demo/loadmode.html ================================================ CodeMirror: Lazy Mode Loading Demo

Lazy Mode Loading Demo

Current mode: text/plain

Filename, mime, or mode name:

================================================ FILE: third_party/CodeMirror/demo/marker.html ================================================ CodeMirror: Breakpoint Demo

Breakpoint Demo

Click the line-number gutter to add or remove 'breakpoints'.

================================================ FILE: third_party/CodeMirror/demo/markselection.html ================================================ CodeMirror: Selection Marking Demo

Selection Marking Demo

Simple addon to easily mark (and style) selected text. Docs.

================================================ FILE: third_party/CodeMirror/demo/matchhighlighter.html ================================================ CodeMirror: Match Highlighter Demo

Match Highlighter Demo

Search and highlight occurences of the selected text.

================================================ FILE: third_party/CodeMirror/demo/matchtags.html ================================================ CodeMirror: Tag Matcher Demo

Tag Matcher Demo

Put the cursor on or inside a pair of tags to highlight them. Press Ctrl-J to jump to the tag that matches the one under the cursor.

================================================ FILE: third_party/CodeMirror/demo/merge.html ================================================ CodeMirror: merge view demo

merge view demo

The merge addon provides an interface for displaying and merging diffs, either two-way or three-way. The left (or center) pane is editable, and the differences with the other pane(s) are optionally shown live as you edit it. In the two-way configuration, there are also options to pad changed sections to align them, and to collapse unchanged stretches of text.

This addon depends on the google-diff-match-patch library to compute the diffs.

================================================ FILE: third_party/CodeMirror/demo/multiplex.html ================================================ CodeMirror: Multiplexing Parser Demo

Multiplexing Parser Demo

Demonstration of a multiplexing mode, which, at certain boundary strings, switches to one or more inner modes. The out (HTML) mode does not get fed the content of the << >> blocks. See the manual and the source for more information.

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/demo/mustache.html ================================================ CodeMirror: Overlay Parser Demo

Overlay Parser Demo

Demonstration of a mode that parses HTML, highlighting the Mustache templating directives inside of it by using the code in overlay.js. View source to see the 15 lines of code needed to accomplish this.

================================================ FILE: third_party/CodeMirror/demo/panel.html ================================================ CodeMirror: Panel Demo

Panel Demo

The panel addon allows you to display panels above or below an editor.
Click the links below to add panels at the given position:

top after-top before-bottom bottom

You can also replace an existing panel:

================================================ FILE: third_party/CodeMirror/demo/placeholder.html ================================================ CodeMirror: Placeholder demo

Placeholder demo

The placeholder plug-in adds an option placeholder that can be set to make text appear in the editor when it is empty and not focused. If the source textarea has a placeholder attribute, it will automatically be inherited.

================================================ FILE: third_party/CodeMirror/demo/preview.html ================================================ CodeMirror: HTML5 preview

HTML5 preview

================================================ FILE: third_party/CodeMirror/demo/requirejs.html ================================================ CodeMirror: HTML completion demo

RequireJS module loading demo

This demo does the same thing as the HTML5 completion demo, but loads its dependencies with Require.js, rather than explicitly. Press ctrl-space to activate completion.

================================================ FILE: third_party/CodeMirror/demo/resize.html ================================================ CodeMirror: Autoresize Demo

Autoresize Demo

By setting an editor's height style to auto and giving the viewportMargin a value of Infinity, CodeMirror can be made to automatically resize to fit its content.

================================================ FILE: third_party/CodeMirror/demo/rulers.html ================================================ CodeMirror: Ruler Demo

Ruler Demo

Demonstration of the rulers addon, which displays vertical lines at given column offsets.

================================================ FILE: third_party/CodeMirror/demo/runmode.html ================================================ CodeMirror: Mode Runner Demo

Mode Runner Demo




    

    

Running a CodeMirror mode outside of the editor. The CodeMirror.runMode function, defined in addon/runmode/runmode.js takes the following arguments:

text (string)
The document to run through the highlighter.
mode (mode spec)
The mode to use (must be loaded as normal).
output (function or DOM node)
If this is a function, it will be called for each token with two arguments, the token's text and the token's style class (may be null for unstyled tokens). If it is a DOM node, the tokens will be converted to span elements as in an editor, and inserted into the node (through innerHTML).
================================================ FILE: third_party/CodeMirror/demo/search.html ================================================ CodeMirror: Search/Replace Demo

Search/Replace Demo

Demonstration of primitive search/replace functionality. The keybindings (which can be configured with custom keymaps) are:

Ctrl-F / Cmd-F
Start searching
Ctrl-G / Cmd-G
Find next
Shift-Ctrl-G / Shift-Cmd-G
Find previous
Shift-Ctrl-F / Cmd-Option-F
Replace
Shift-Ctrl-R / Shift-Cmd-Option-F
Replace all
Alt-F
Persistent search (dialog doesn't autoclose, enter to find next, Shift-Enter to find previous)
Alt-G
Jump to line

Searching is enabled by including addon/search/search.js and addon/search/searchcursor.js. Jump to line - including addon/search/jump-to-line.js.

For good-looking input dialogs, you also want to include addon/dialog/dialog.js and addon/dialog/dialog.css.

================================================ FILE: third_party/CodeMirror/demo/simplemode.html ================================================ CodeMirror: Simple Mode Demo

Simple Mode Demo

The mode/simple addon allows CodeMirror modes to be specified using a relatively simple declarative format. This format is not as powerful as writing code directly against the mode interface, but is a lot easier to get started with, and sufficiently expressive for many simple language modes.

This interface is still in flux. It is unlikely to be scrapped or overhauled completely, so do start writing code against it, but details might change as it stabilizes, and you might have to tweak your code when upgrading.

Simple modes (loosely based on the Common JavaScript Syntax Highlighting Specification, which never took off), are state machines, where each state has a number of rules that match tokens. A rule describes a type of token that may occur in the current state, and possibly a transition to another state caused by that token.

The CodeMirror.defineSimpleMode(name, states) method takes a mode name and an object that describes the mode's states. The editor below shows an example of such a mode (and is itself highlighted by the mode shown in it).

Each state is an array of rules. A rule may have the following properties:

regex: string | RegExp
The regular expression that matches the token. May be a string or a regex object. When a regex, the ignoreCase flag will be taken into account when matching the token. This regex has to capture groups when the token property is an array. If it captures groups, it must capture all of the string (since JS provides no way to find out where a group matched).
token: string | array<string> | null
An optional token style. Multiple styles can be specified by separating them with dots or spaces. When this property holds an array of token styles, the regex for this rule must capture a group for each array item.
sol: boolean
When true, this token will only match at the start of the line. (The ^ regexp marker doesn't work as you'd expect in this context because of limitations in JavaScript's RegExp API.)
next: string
When a next property is present, the mode will transfer to the state named by the property when the token is encountered.
push: string
Like next, but instead replacing the current state by the new state, the current state is kept on a stack, and can be returned to with the pop directive.
pop: bool
When true, and there is another state on the state stack, will cause the mode to pop that state off the stack and transition to it.
mode: {spec, end, persistent}
Can be used to embed another mode inside a mode. When present, must hold an object with a spec property that describes the embedded mode, and an optional end end property that specifies the regexp that will end the extent of the mode. When a persistent property is set (and true), the nested mode's state will be preserved between occurrences of the mode.
indent: bool
When true, this token changes the indentation to be one unit more than the current line's indentation.
dedent: bool
When true, this token will pop one scope off the indentation stack.
dedentIfLineStart: bool
If a token has its dedent property set, it will, by default, cause lines where it appears at the start to be dedented. Set this property to false to prevent that behavior.

The meta property of the states object is special, and will not be interpreted as a state. Instead, properties set on it will be set on the mode, which is useful for properties like lineComment, which sets the comment style for a mode. The simple mode addon also recognizes a few such properties:

dontIndentStates: array<string>
An array of states in which the mode's auto-indentation should not take effect. Usually used for multi-line comment and string states.
================================================ FILE: third_party/CodeMirror/demo/simplescrollbars.html ================================================ CodeMirror: Simple Scrollbar Demo

Simple Scrollbar Demo

The simplescrollbars addon defines two styles of non-native scrollbars: "simple" and "overlay" (click to try), which can be passed to the scrollbarStyle option. These implement the scrollbar using DOM elements, allowing more control over its appearance.

================================================ FILE: third_party/CodeMirror/demo/spanaffectswrapping_shim.html ================================================ CodeMirror: Automatically derive odd wrapping behavior for your browser

Automatically derive odd wrapping behavior for your browser

This is a hack to automatically derive a spanAffectsWrapping regexp for a browser. See the comments above that variable in lib/codemirror.js for some more details.



    
  
================================================ FILE: third_party/CodeMirror/demo/sublime.html ================================================ CodeMirror: Sublime Text bindings demo

Sublime Text bindings demo

The sublime keymap defines many Sublime Text-specific bindings for CodeMirror. See the code below for an overview.

Enable the keymap by loading keymap/sublime.js and setting the keyMap option to "sublime".

(A lot of the search functionality is still missing.)

================================================ FILE: third_party/CodeMirror/demo/tern.html ================================================ CodeMirror: Tern Demo

Tern Demo

Demonstrates integration of Tern and CodeMirror. The following keys are bound:

Ctrl-Space
Autocomplete
Ctrl-O
Find docs for the expression at the cursor
Ctrl-I
Find type at cursor
Alt-.
Jump to definition (Alt-, to jump back)
Ctrl-Q
Rename variable
Ctrl-.
Select all occurrences of a variable

Documentation is sparse for now. See the top of the script for a rough API overview.

================================================ FILE: third_party/CodeMirror/demo/theme.html ================================================ CodeMirror: Theme Demo

Theme Demo

Select a theme:

================================================ FILE: third_party/CodeMirror/demo/trailingspace.html ================================================ CodeMirror: Trailing Whitespace Demo

Trailing Whitespace Demo

Uses the trailingspace addon to highlight trailing whitespace.

================================================ FILE: third_party/CodeMirror/demo/variableheight.html ================================================ CodeMirror: Variable Height Demo

Variable Height Demo

================================================ FILE: third_party/CodeMirror/demo/vim.html ================================================ CodeMirror: Vim bindings demo

Vim bindings demo

Note: The CodeMirror vim bindings do not have an active maintainer. That means that if you report bugs in it, they are likely to go unanswered. It also means that if you want to help, you are very welcome to look at the open issues and see which ones you can solve.

Key buffer:

The vim keybindings are enabled by including keymap/vim.js and setting the keyMap option to vim.

Features

  • All common motions and operators, including text objects
  • Operator motion orthogonality
  • Visual mode - characterwise, linewise, blockwise
  • Full macro support (q, @)
  • Incremental highlighted search (/, ?, #, *, g#, g*)
  • Search/replace with confirm (:substitute, :%s)
  • Search history
  • Jump lists (Ctrl-o, Ctrl-i)
  • Key/command mapping with API (:map, :nmap, :vmap)
  • Sort (:sort)
  • Marks (`, ')
  • :global
  • Insert mode behaves identical to base CodeMirror
  • Cross-buffer yank/paste

For the full list of key mappings and Ex commands, refer to the defaultKeymap and defaultExCommandMap at the top of keymap/vim.js.

Note that while the vim mode tries to emulate the most useful features of vim as faithfully as possible, it does not strive to become a complete vim implementation

================================================ FILE: third_party/CodeMirror/demo/visibletabs.html ================================================ CodeMirror: Visible tabs demo

Visible tabs demo

Tabs inside the editor are spans with the class cm-tab, and can be styled.

================================================ FILE: third_party/CodeMirror/demo/widget.html ================================================ CodeMirror: Inline Widget Demo

Inline Widget Demo

This demo runs JSHint over the code in the editor (which is the script used on this page), and inserts line widgets to display the warnings that JSHint comes up with.

================================================ FILE: third_party/CodeMirror/demo/xmlcomplete.html ================================================  CodeMirror: XML Autocomplete Demo

XML Autocomplete Demo

Press ctrl-space, or type a '<' character to activate autocompletion. This demo defines a simple schema that guides completion. The schema can be customized—see the manual.

Development of the xml-hint addon was kindly sponsored by www.xperiment.mobi.

================================================ FILE: third_party/CodeMirror/doc/activebookmark.js ================================================ // Kludge in HTML5 tag recognition in IE8 document.createElement("section"); document.createElement("article"); (function() { if (!window.addEventListener) return; var pending = false, prevVal = null; function updateSoon() { if (!pending) { pending = true; setTimeout(update, 250); } } function update() { pending = false; var marks = document.getElementById("nav").getElementsByTagName("a"), found; for (var i = 0; i < marks.length; ++i) { var mark = marks[i], m; if (mark.getAttribute("data-default")) { if (found == null) found = i; } else if (m = mark.href.match(/#(.*)/)) { var ref = document.getElementById(m[1]); if (ref && ref.getBoundingClientRect().top < 50) found = i; } } if (found != null && found != prevVal) { prevVal = found; var lis = document.getElementById("nav").getElementsByTagName("li"); for (var i = 0; i < lis.length; ++i) lis[i].className = ""; for (var i = 0; i < marks.length; ++i) { if (found == i) { marks[i].className = "active"; for (var n = marks[i]; n; n = n.parentNode) if (n.nodeName == "LI") n.className = "active"; } else { marks[i].className = ""; } } } } window.addEventListener("scroll", updateSoon); window.addEventListener("load", updateSoon); window.addEventListener("hashchange", function() { setTimeout(function() { var hash = document.location.hash, found = null, m; var marks = document.getElementById("nav").getElementsByTagName("a"); for (var i = 0; i < marks.length; i++) if ((m = marks[i].href.match(/(#.*)/)) && m[1] == hash) { found = i; break; } if (found != null) for (var i = 0; i < marks.length; i++) marks[i].className = i == found ? "active" : ""; }, 300); }); })(); ================================================ FILE: third_party/CodeMirror/doc/docs.css ================================================ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; src: local('Source Sans Pro'), local('SourceSansPro-Regular'), url(//themes.googleusercontent.com/static/fonts/sourcesanspro/v5/ODelI1aHBYDBqgeIAH2zlBM0YzuT7MdOe03otPbuUS0.woff) format('woff'); } body, html { margin: 0; padding: 0; height: 100%; } section, article { display: block; padding: 0; } body { background: #f8f8f8; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; line-height: 1.5; } p { margin-top: 0; } h2, h3, h1 { font-weight: normal; margin-bottom: .7em; } h1 { font-size: 140%; } h2 { font-size: 120%; } h3 { font-size: 110%; } article > h2:first-child, section:first-child > h2 { margin-top: 0; } #nav h1 { margin-right: 12px; margin-top: 0; margin-bottom: 2px; color: #d30707; letter-spacing: .5px; } a, a:visited, a:link, .quasilink { color: #A21313; } em { padding-right: 2px; } .quasilink { cursor: pointer; } article { max-width: 700px; margin: 0 0 0 160px; border-left: 2px solid #E30808; border-right: 1px solid #ddd; padding: 30px 50px 100px 50px; background: white; z-index: 2; position: relative; min-height: 100%; box-sizing: border-box; -moz-box-sizing: border-box; } #nav { position: fixed; padding-top: 30px; max-height: 100%; box-sizing: -moz-border-box; box-sizing: border-box; overflow-y: auto; left: 0; right: none; width: 160px; text-align: right; z-index: 1; } @media screen and (min-width: 1000px) { article { margin: 0 auto; } #nav { right: 50%; width: auto; border-right: 349px solid transparent; } } #nav ul { display: block; margin: 0; padding: 0; margin-bottom: 32px; } #nav a { text-decoration: none; } #nav li { display: block; margin-bottom: 4px; } #nav li ul { font-size: 80%; margin-bottom: 0; display: none; } #nav li.active ul { display: block; } #nav li li a { padding-right: 20px; display: inline-block; } #nav ul a { color: black; padding: 0 7px 1px 11px; } #nav ul a.active, #nav ul a:hover { border-bottom: 1px solid #E30808; margin-bottom: -1px; color: #E30808; } #logo { border: 0; margin-right: 12px; margin-bottom: 25px; } section { border-top: 1px solid #E30808; margin: 1.5em 0; } section.first { border: none; margin-top: 0; } #demo { position: relative; } #demolist { position: absolute; right: 5px; top: 5px; z-index: 25; } .yinyang { position: absolute; top: -10px; left: 0; right: 0; margin: auto; display: block; height: 120px; } .actions { margin: 1em 0 0; min-height: 100px; position: relative; } .actionspicture { pointer-events: none; position: absolute; height: 100px; top: 0; left: 0; right: 0; } .actionlink { pointer-events: auto; font-family: arial; font-size: 80%; font-weight: bold; position: absolute; top: 0; bottom: 0; line-height: 1; height: 1em; margin: auto; } .actionlink.download { color: white; right: 50%; margin-right: 13px; text-shadow: -1px 1px 3px #b00, -1px -1px 3px #b00, 1px 0px 3px #b00; } .actionlink.fund { color: #b00; left: 50%; margin-left: 15px; } .actionlink:hover { text-decoration: underline; } .actionlink a { color: inherit; } .actionsleft { float: left; } .actionsright { float: right; text-align: right; } @media screen and (max-width: 800px) { .actions { padding-top: 120px; } .actionsleft, .actionsright { float: none; text-align: left; margin-bottom: 1em; } } th { text-decoration: underline; font-weight: normal; text-align: left; } #features ul { list-style: none; margin: 0 0 1em; padding: 0 0 0 1.2em; } #features li:before { content: "-"; width: 1em; display: inline-block; padding: 0; margin: 0; margin-left: -1em; } .rel { margin-bottom: 0; } .rel-note { margin-top: 0; color: #555; } pre { padding-left: 15px; border-left: 2px solid #ddd; } code { padding: 0 2px; } strong { text-decoration: underline; font-weight: normal; } .field { border: 1px solid #A21313; } ================================================ FILE: third_party/CodeMirror/doc/internals.html ================================================  CodeMirror: Internals

(Re-) Implementing A Syntax-Highlighting Editor in JavaScript

Topic: JavaScript, code editor implementation
Author: Marijn Haverbeke
Date: March 2nd 2011 (updated November 13th 2011)

Caution: this text was written briefly after version 2 was initially written. It no longer (even including the update at the bottom) fully represents the current implementation. I'm leaving it here as a historic document. For more up-to-date information, look at the entries tagged cm-internals on my blog.

This is a followup to my Brutal Odyssey to the Dark Side of the DOM Tree story. That one describes the mind-bending process of implementing (what would become) CodeMirror 1. This one describes the internals of CodeMirror 2, a complete rewrite and rethink of the old code base. I wanted to give this piece another Hunter Thompson copycat subtitle, but somehow that would be out of place—the process this time around was one of straightforward engineering, requiring no serious mind-bending whatsoever.

So, what is wrong with CodeMirror 1? I'd estimate, by mailing list activity and general search-engine presence, that it has been integrated into about a thousand systems by now. The most prominent one, since a few weeks, being Google code's project hosting. It works, and it's being used widely.

Still, I did not start replacing it because I was bored. CodeMirror 1 was heavily reliant on designMode or contentEditable (depending on the browser). Neither of these are well specified (HTML5 tries to specify their basics), and, more importantly, they tend to be one of the more obscure and buggy areas of browser functionality—CodeMirror, by using this functionality in a non-typical way, was constantly running up against browser bugs. WebKit wouldn't show an empty line at the end of the document, and in some releases would suddenly get unbearably slow. Firefox would show the cursor in the wrong place. Internet Explorer would insist on linkifying everything that looked like a URL or email address, a behaviour that can't be turned off. Some bugs I managed to work around (which was often a frustrating, painful process), others, such as the Firefox cursor placement, I gave up on, and had to tell user after user that they were known problems, but not something I could help.

Also, there is the fact that designMode (which seemed to be less buggy than contentEditable in Webkit and Firefox, and was thus used by CodeMirror 1 in those browsers) requires a frame. Frames are another tricky area. It takes some effort to prevent getting tripped up by domain restrictions, they don't initialize synchronously, behave strangely in response to the back button, and, on several browsers, can't be moved around the DOM without having them re-initialize. They did provide a very nice way to namespace the library, though—CodeMirror 1 could freely pollute the namespace inside the frame.

Finally, working with an editable document means working with selection in arbitrary DOM structures. Internet Explorer (8 and before) has an utterly different (and awkward) selection API than all of the other browsers, and even among the different implementations of document.selection, details about how exactly a selection is represented vary quite a bit. Add to that the fact that Opera's selection support tended to be very buggy until recently, and you can imagine why CodeMirror 1 contains 700 lines of selection-handling code.

And that brings us to the main issue with the CodeMirror 1 code base: The proportion of browser-bug-workarounds to real application code was getting dangerously high. By building on top of a few dodgy features, I put the system in a vulnerable position—any incompatibility and bugginess in these features, I had to paper over with my own code. Not only did I have to do some serious stunt-work to get it to work on older browsers (as detailed in the previous story), things also kept breaking in newly released versions, requiring me to come up with new scary hacks in order to keep up. This was starting to lose its appeal.

General Approach

What CodeMirror 2 does is try to sidestep most of the hairy hacks that came up in version 1. I owe a lot to the ACE editor for inspiration on how to approach this.

I absolutely did not want to be completely reliant on key events to generate my input. Every JavaScript programmer knows that key event information is horrible and incomplete. Some people (most awesomely Mihai Bazon with Ymacs) have been able to build more or less functioning editors by directly reading key events, but it takes a lot of work (the kind of never-ending, fragile work I described earlier), and will never be able to properly support things like multi-keystoke international character input. [see below for caveat]

So what I do is focus a hidden textarea, and let the browser believe that the user is typing into that. What we show to the user is a DOM structure we built to represent his document. If this is updated quickly enough, and shows some kind of believable cursor, it feels like a real text-input control.

Another big win is that this DOM representation does not have to span the whole document. Some CodeMirror 1 users insisted that they needed to put a 30 thousand line XML document into CodeMirror. Putting all that into the DOM takes a while, especially since, for some reason, an editable DOM tree is slower than a normal one on most browsers. If we have full control over what we show, we must only ensure that the visible part of the document has been added, and can do the rest only when needed. (Fortunately, the onscroll event works almost the same on all browsers, and lends itself well to displaying things only as they are scrolled into view.)

Input

ACE uses its hidden textarea only as a text input shim, and does all cursor movement and things like text deletion itself by directly handling key events. CodeMirror's way is to let the browser do its thing as much as possible, and not, for example, define its own set of key bindings. One way to do this would have been to have the whole document inside the hidden textarea, and after each key event update the display DOM to reflect what's in that textarea.

That'd be simple, but it is not realistic. For even medium-sized document the editor would be constantly munging huge strings, and get terribly slow. What CodeMirror 2 does is put the current selection, along with an extra line on the top and on the bottom, into the textarea.

This means that the arrow keys (and their ctrl-variations), home, end, etcetera, do not have to be handled specially. We just read the cursor position in the textarea, and update our cursor to match it. Also, copy and paste work pretty much for free, and people get their native key bindings, without any special work on my part. For example, I have emacs key bindings configured for Chrome and Firefox. There is no way for a script to detect this. [no longer the case]

Of course, since only a small part of the document sits in the textarea, keys like page up and ctrl-end won't do the right thing. CodeMirror is catching those events and handling them itself.

Selection

Getting and setting the selection range of a textarea in modern browsers is trivial—you just use the selectionStart and selectionEnd properties. On IE you have to do some insane stuff with temporary ranges and compensating for the fact that moving the selection by a 'character' will treat \r\n as a single character, but even there it is possible to build functions that reliably set and get the selection range.

But consider this typical case: When I'm somewhere in my document, press shift, and press the up arrow, something gets selected. Then, if I, still holding shift, press the up arrow again, the top of my selection is adjusted. The selection remembers where its head and its anchor are, and moves the head when we shift-move. This is a generally accepted property of selections, and done right by every editing component built in the past twenty years.

But not something that the browser selection APIs expose.

Great. So when someone creates an 'upside-down' selection, the next time CodeMirror has to update the textarea, it'll re-create the selection as an 'upside-up' selection, with the anchor at the top, and the next cursor motion will behave in an unexpected way—our second up-arrow press in the example above will not do anything, since it is interpreted in exactly the same way as the first.

No problem. We'll just, ehm, detect that the selection is upside-down (you can tell by the way it was created), and then, when an upside-down selection is present, and a cursor-moving key is pressed in combination with shift, we quickly collapse the selection in the textarea to its start, allow the key to take effect, and then combine its new head with its old anchor to get the real selection.

In short, scary hacks could not be avoided entirely in CodeMirror 2.

And, the observant reader might ask, how do you even know that a key combo is a cursor-moving combo, if you claim you support any native key bindings? Well, we don't, but we can learn. The editor keeps a set known cursor-movement combos (initialized to the predictable defaults), and updates this set when it observes that pressing a certain key had (only) the effect of moving the cursor. This, of course, doesn't work if the first time the key is used was for extending an inverted selection, but it works most of the time.

Intelligent Updating

One thing that always comes up when you have a complicated internal state that's reflected in some user-visible external representation (in this case, the displayed code and the textarea's content) is keeping the two in sync. The naive way is to just update the display every time you change your state, but this is not only error prone (you'll forget), it also easily leads to duplicate work on big, composite operations. Then you start passing around flags indicating whether the display should be updated in an attempt to be efficient again and, well, at that point you might as well give up completely.

I did go down that road, but then switched to a much simpler model: simply keep track of all the things that have been changed during an action, and then, only at the end, use this information to update the user-visible display.

CodeMirror uses a concept of operations, which start by calling a specific set-up function that clears the state and end by calling another function that reads this state and does the required updating. Most event handlers, and all the user-visible methods that change state are wrapped like this. There's a method called operation that accepts a function, and returns another function that wraps the given function as an operation.

It's trivial to extend this (as CodeMirror does) to detect nesting, and, when an operation is started inside an operation, simply increment the nesting count, and only do the updating when this count reaches zero again.

If we have a set of changed ranges and know the currently shown range, we can (with some awkward code to deal with the fact that changes can add and remove lines, so we're dealing with a changing coordinate system) construct a map of the ranges that were left intact. We can then compare this map with the part of the document that's currently visible (based on scroll offset and editor height) to determine whether something needs to be updated.

CodeMirror uses two update algorithms—a full refresh, where it just discards the whole part of the DOM that contains the edited text and rebuilds it, and a patch algorithm, where it uses the information about changed and intact ranges to update only the out-of-date parts of the DOM. When more than 30 percent (which is the current heuristic, might change) of the lines need to be updated, the full refresh is chosen (since it's faster to do than painstakingly finding and updating all the changed lines), in the other case it does the patching (so that, if you scroll a line or select another character, the whole screen doesn't have to be re-rendered). [the full-refresh algorithm was dropped, it wasn't really faster than the patching one]

All updating uses innerHTML rather than direct DOM manipulation, since that still seems to be by far the fastest way to build documents. There's a per-line function that combines the highlighting, marking, and selection info for that line into a snippet of HTML. The patch updater uses this to reset individual lines, the refresh updater builds an HTML chunk for the whole visible document at once, and then uses a single innerHTML update to do the refresh.

Parsers can be Simple

When I wrote CodeMirror 1, I thought interruptable parsers were a hugely scary and complicated thing, and I used a bunch of heavyweight abstractions to keep this supposed complexity under control: parsers were iterators that consumed input from another iterator, and used funny closure-resetting tricks to copy and resume themselves.

This made for a rather nice system, in that parsers formed strictly separate modules, and could be composed in predictable ways. Unfortunately, it was quite slow (stacking three or four iterators on top of each other), and extremely intimidating to people not used to a functional programming style.

With a few small changes, however, we can keep all those advantages, but simplify the API and make the whole thing less indirect and inefficient. CodeMirror 2's mode API uses explicit state objects, and makes the parser/tokenizer a function that simply takes a state and a character stream abstraction, advances the stream one token, and returns the way the token should be styled. This state may be copied, optionally in a mode-defined way, in order to be able to continue a parse at a given point. Even someone who's never touched a lambda in his life can understand this approach. Additionally, far fewer objects are allocated in the course of parsing now.

The biggest speedup comes from the fact that the parsing no longer has to touch the DOM though. In CodeMirror 1, on an older browser, you could see the parser work its way through the document, managing some twenty lines in each 50-millisecond time slice it got. It was reading its input from the DOM, and updating the DOM as it went along, which any experienced JavaScript programmer will immediately spot as a recipe for slowness. In CodeMirror 2, the parser usually finishes the whole document in a single 100-millisecond time slice—it manages some 1500 lines during that time on Chrome. All it has to do is munge strings, so there is no real reason for it to be slow anymore.

What Gives?

Given all this, what can you expect from CodeMirror 2?

  • Small. the base library is some 45k when minified now, 17k when gzipped. It's smaller than its own logo.
  • Lightweight. CodeMirror 2 initializes very quickly, and does almost no work when it is not focused. This means you can treat it almost like a textarea, have multiple instances on a page without trouble.
  • Huge document support. Since highlighting is really fast, and no DOM structure is being built for non-visible content, you don't have to worry about locking up your browser when a user enters a megabyte-sized document.
  • Extended API. Some things kept coming up in the mailing list, such as marking pieces of text or lines, which were extremely hard to do with CodeMirror 1. The new version has proper support for these built in.
  • Tab support. Tabs inside editable documents were, for some reason, a no-go. At least six different people announced they were going to add tab support to CodeMirror 1, none survived (I mean, none delivered a working version). CodeMirror 2 no longer removes tabs from your document.
  • Sane styling. iframe nodes aren't really known for respecting document flow. Now that an editor instance is a plain div element, it is much easier to size it to fit the surrounding elements. You don't even have to make it scroll if you do not want to.

On the downside, a CodeMirror 2 instance is not a native editable component. Though it does its best to emulate such a component as much as possible, there is functionality that browsers just do not allow us to hook into. Doing select-all from the context menu, for example, is not currently detected by CodeMirror.

[Updates from November 13th 2011] Recently, I've made some changes to the codebase that cause some of the text above to no longer be current. I've left the text intact, but added markers at the passages that are now inaccurate. The new situation is described below.

Content Representation

The original implementation of CodeMirror 2 represented the document as a flat array of line objects. This worked well—splicing arrays will require the part of the array after the splice to be moved, but this is basically just a simple memmove of a bunch of pointers, so it is cheap even for huge documents.

However, I recently added line wrapping and code folding (line collapsing, basically). Once lines start taking up a non-constant amount of vertical space, looking up a line by vertical position (which is needed when someone clicks the document, and to determine the visible part of the document during scrolling) can only be done with a linear scan through the whole array, summing up line heights as you go. Seeing how I've been going out of my way to make big documents fast, this is not acceptable.

The new representation is based on a B-tree. The leaves of the tree contain arrays of line objects, with a fixed minimum and maximum size, and the non-leaf nodes simply hold arrays of child nodes. Each node stores both the amount of lines that live below them and the vertical space taken up by these lines. This allows the tree to be indexed both by line number and by vertical position, and all access has logarithmic complexity in relation to the document size.

I gave line objects and tree nodes parent pointers, to the node above them. When a line has to update its height, it can simply walk these pointers to the top of the tree, adding or subtracting the difference in height from each node it encounters. The parent pointers also make it cheaper (in complexity terms, the difference is probably tiny in normal-sized documents) to find the current line number when given a line object. In the old approach, the whole document array had to be searched. Now, we can just walk up the tree and count the sizes of the nodes coming before us at each level.

I chose B-trees, not regular binary trees, mostly because they allow for very fast bulk insertions and deletions. When there is a big change to a document, it typically involves adding, deleting, or replacing a chunk of subsequent lines. In a regular balanced tree, all these inserts or deletes would have to be done separately, which could be really expensive. In a B-tree, to insert a chunk, you just walk down the tree once to find where it should go, insert them all in one shot, and then break up the node if needed. This breaking up might involve breaking up nodes further up, but only requires a single pass back up the tree. For deletion, I'm somewhat lax in keeping things balanced—I just collapse nodes into a leaf when their child count goes below a given number. This means that there are some weird editing patterns that may result in a seriously unbalanced tree, but even such an unbalanced tree will perform well, unless you spend a day making strangely repeating edits to a really big document.

Keymaps

Above, I claimed that directly catching key events for things like cursor movement is impractical because it requires some browser-specific kludges. I then proceeded to explain some awful hacks that were needed to make it possible for the selection changes to be detected through the textarea. In fact, the second hack is about as bad as the first.

On top of that, in the presence of user-configurable tab sizes and collapsed and wrapped lines, lining up cursor movement in the textarea with what's visible on the screen becomes a nightmare. Thus, I've decided to move to a model where the textarea's selection is no longer depended on.

So I moved to a model where all cursor movement is handled by my own code. This adds support for a goal column, proper interaction of cursor movement with collapsed lines, and makes it possible for vertical movement to move through wrapped lines properly, instead of just treating them like non-wrapped lines.

The key event handlers now translate the key event into a string, something like Ctrl-Home or Shift-Cmd-R, and use that string to look up an action to perform. To make keybinding customizable, this lookup goes through a table, using a scheme that allows such tables to be chained together (for example, the default Mac bindings fall through to a table named 'emacsy', which defines basic Emacs-style bindings like Ctrl-F, and which is also used by the custom Emacs bindings).

A new option extraKeys allows ad-hoc keybindings to be defined in a much nicer way than what was possible with the old onKeyEvent callback. You simply provide an object mapping key identifiers to functions, instead of painstakingly looking at raw key events.

Built-in commands map to strings, rather than functions, for example "goLineUp" is the default action bound to the up arrow key. This allows new keymaps to refer to them without duplicating any code. New commands can be defined by assigning to the CodeMirror.commands object, which maps such commands to functions.

The hidden textarea now only holds the current selection, with no extra characters around it. This has a nice advantage: polling for input becomes much, much faster. If there's a big selection, this text does not have to be read from the textarea every time—when we poll, just noticing that something is still selected is enough to tell us that no new text was typed.

The reason that cheap polling is important is that many browsers do not fire useful events on IME (input method engine) input, which is the thing where people inputting a language like Japanese or Chinese use multiple keystrokes to create a character or sequence of characters. Most modern browsers fire input when the composing is finished, but many don't fire anything when the character is updated during composition. So we poll, whenever the editor is focused, to provide immediate updates of the display.

================================================ FILE: third_party/CodeMirror/doc/manual.html ================================================ CodeMirror: User Manual

User manual and reference guide version 5.43.0

CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides only 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 addons included in the distribution, and the list of externally hosted addons, for reusable implementations of extra features.

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 mode/ directory), and it isn't hard to write new ones for other languages.

Basic Usage

The easiest way to use CodeMirror is to simply load the script and style sheet found under lib/ in the distribution, plus a mode script from one of the mode/ directories. For example:

<script src="lib/codemirror.js"></script>
<link rel="stylesheet" href="lib/codemirror.css">
<script src="mode/javascript/javascript.js"></script>

(Alternatively, use a module loader. More about that later.)

Having done this, an editor instance can be created like this:

var myCodeMirror = CodeMirror(document.body);

The editor will be appended to the document body, will start empty, and will use the mode that we loaded. To have more control over the new editor, a configuration object can be passed to CodeMirror as a second argument:

var myCodeMirror = CodeMirror(document.body, {
  value: "function myScript(){return 100;}\n",
  mode:  "javascript"
});

This will initialize the editor with a piece of code already in it, and explicitly tell it to use the JavaScript mode (which is useful when multiple modes are loaded). See below for a full discussion of the configuration options that CodeMirror accepts.

In cases where you don't want to append the editor to an element, and need more control over the way it is inserted, the first argument to the CodeMirror function can also be a function that, when given a DOM element, inserts it into the document somewhere. This could be used to, for example, replace a textarea with a real editor:

var myCodeMirror = CodeMirror(function(elt) {
  myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {value: myTextArea.value});

However, for this use case, which is a common way to use CodeMirror, the library provides a much more powerful shortcut:

var myCodeMirror = CodeMirror.fromTextArea(myTextArea);

This will, among other things, ensure that the textarea's value is updated with the editor's contents when the form (if it is part of a form) is submitted. See the API reference for a full description of this method.

Module loaders

The files in the CodeMirror distribution contain shims for loading them (and their dependencies) in AMD or CommonJS environments. If the variables exports and module exist and have type object, CommonJS-style require will be used. If not, but there is a function define with an amd property present, AMD-style (RequireJS) will be used.

It is possible to use Browserify or similar tools to statically build modules using CodeMirror. Alternatively, use RequireJS to dynamically load dependencies at runtime. Both of these approaches have the advantage that they don't use the global namespace and can, thus, do things like load multiple versions of CodeMirror alongside each other.

Here's a simple example of using RequireJS to load CodeMirror:

require([
  "cm/lib/codemirror", "cm/mode/htmlmixed/htmlmixed"
], function(CodeMirror) {
  CodeMirror.fromTextArea(document.getElementById("code"), {
    lineNumbers: true,
    mode: "htmlmixed"
  });
});

It will automatically load the modes that the mixed HTML mode depends on (XML, JavaScript, and CSS). Do not use RequireJS' paths option to configure the path to CodeMirror, since it will break loading submodules through relative paths. Use the packages configuration option instead, as in:

require.config({
  packages: [{
    name: "codemirror",
    location: "../path/to/codemirror",
    main: "lib/codemirror"
  }]
});

Configuration

Both the CodeMirror function and its fromTextArea method take as second (optional) argument an object containing configuration options. Any option not supplied like this will be taken from CodeMirror.defaults, an object containing the default options. You can update this object to change the defaults on your page.

Options are not checked in any way, so setting bogus option values is bound to lead to odd errors.

These are the supported options:

value: string|CodeMirror.Doc
The starting value of the editor. Can be a string, or a document object.
mode: string|object
The mode to use. When not given, this will default to the first mode that was loaded. It may be a string, which either simply names the mode or is a MIME type associated with the mode. Alternatively, it may be an object containing configuration options for the mode, with a name property that names the mode (for example {name: "javascript", json: true}). The demo pages for each mode contain information about what configuration parameters the mode supports. You can ask CodeMirror which modes and MIME types have been defined by inspecting the CodeMirror.modes and CodeMirror.mimeModes objects. The first maps mode names to their constructors, and the second maps MIME types to mode specs.
lineSeparator: string|null
Explicitly set the line separator for the editor. By default (value null), the document will be split on CRLFs as well as lone CRs and LFs, and a single LF will be used as line separator in all output (such as getValue). When a specific string is given, lines will only be split on that string, and output will, by default, use that same separator.
theme: string
The theme to style the editor with. You must make sure the CSS file defining the corresponding .cm-s-[name] styles is loaded (see the theme directory in the distribution). The default is "default", for which colors are included in codemirror.css. It is possible to use multiple theming classes at once—for example "foo bar" will assign both the cm-s-foo and the cm-s-bar classes to the editor.
indentUnit: integer
How many spaces a block (whatever that means in the edited language) should be indented. The default is 2.
smartIndent: boolean
Whether to use the context-sensitive indentation that the mode provides (or just indent the same as the line before). Defaults to true.
tabSize: integer
The width of a tab character. Defaults to 4.
indentWithTabs: boolean
Whether, when indenting, the first N*tabSize spaces should be replaced by N tabs. Default is false.
electricChars: boolean
Configures whether the editor should re-indent the current line when a character is typed that might change its proper indentation (only works if the mode supports indentation). Default is true.
specialChars: RegExp
A regular expression used to determine which characters should be replaced by a special placeholder. Mostly useful for non-printing special characters. The default is /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/.
specialCharPlaceholder: function(char) → Element
A function that, given a special character identified by the specialChars option, produces a DOM node that is used to represent the character. By default, a red dot () is shown, with a title tooltip to indicate the character code.
direction: "ltr" | "rtl"
Flips overall layout and selects base paragraph direction to be left-to-right or right-to-left. Default is "ltr". CodeMirror applies the Unicode Bidirectional Algorithm to each line, but does not autodetect base direction — it's set to the editor direction for all lines. The resulting order is sometimes wrong when base direction doesn't match user intent (for example, leading and trailing punctuation jumps to the wrong side of the line). Therefore, it's helpful for multilingual input to let users toggle this option.
rtlMoveVisually: boolean
Determines whether horizontal cursor movement through right-to-left (Arabic, Hebrew) text is visual (pressing the left arrow moves the cursor left) or logical (pressing the left arrow moves to the next lower index in the string, which is visually right in right-to-left text). The default is false on Windows, and true on other platforms.
keyMap: string
Configures the key map to use. The default is "default", which is the only key map defined in codemirror.js itself. Extra key maps are found in the key map directory. See the section on key maps for more information.
extraKeys: object
Can be used to specify extra key bindings for the editor, alongside the ones defined by keyMap. Should be either null, or a valid key map value.
configureMouse: fn(cm: CodeMirror, repeat: "single" | "double" | "triple", event: Event) → Object
Allows you to configure the behavior of mouse selection and dragging. The function is called when the left mouse button is pressed. The returned object may have the following properties:
unit: "char" | "word" | "line" | "rectangle" | fn(CodeMirror, Pos) → {from: Pos, to: Pos}
The unit by which to select. May be one of the built-in units or a function that takes a position and returns a range around that, for a custom unit. The default is to return "word" for double clicks, "line" for triple clicks, "rectangle" for alt-clicks (or, on Chrome OS, meta-shift-clicks), and "single" otherwise.
extend: bool
Whether to extend the existing selection range or start a new one. By default, this is enabled when shift clicking.
addNew: bool
When enabled, this adds a new range to the existing selection, rather than replacing it. The default behavior is to enable this for command-click on Mac OS, and control-click on other platforms.
moveOnDrag: bool
When the mouse even drags content around inside the editor, this controls whether it is copied (false) or moved (true). By default, this is enabled by alt-clicking on Mac OS, and ctrl-clicking elsewhere.
lineWrapping: boolean
Whether CodeMirror should scroll or wrap for long lines. Defaults to false (scroll).
lineNumbers: boolean
Whether to show line numbers to the left of the editor.
firstLineNumber: integer
At which number to start counting lines. Default is 1.
lineNumberFormatter: function(line: integer) → string
A function used to format line numbers. The function is passed the line number, and should return a string that will be shown in the gutter.
gutters: array<string>
Can be used to add extra gutters (beyond or instead of the line number gutter). Should be an array of CSS class names, each of which defines a width (and optionally a background), and which will be used to draw the background of the gutters. May include the CodeMirror-linenumbers class, in order to explicitly set the position of the line number gutter (it will default to be to the right of all other gutters). These class names are the keys passed to setGutterMarker.
fixedGutter: boolean
Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default).
scrollbarStyle: string
Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models.
coverGutterNextToScrollbar: boolean
When fixedGutter is on, and there is a horizontal scrollbar, by default the gutter will be visible to the left of this scrollbar. If this option is set to true, it will be covered by an element with class CodeMirror-gutter-filler.
inputStyle: string
Selects the way CodeMirror handles input and focus. The core library defines the "textarea" and "contenteditable" input models. On mobile browsers, the default is "contenteditable". On desktop browsers, the default is "textarea". Support for IME and screen readers is better in the "contenteditable" model. The intention is to make it the default on modern desktop browsers in the future.
readOnly: boolean|string
This disables editing of the editor content by the user. If the special value "nocursor" is given (instead of simply true), focusing of the editor is also disallowed.
showCursorWhenSelecting: boolean
Whether the cursor should be drawn when a selection is active. Defaults to false.
lineWiseCopyCut: boolean
When enabled, which is the default, doing copy or cut when there is no selection will copy or cut the whole lines that have cursors on them.
pasteLinesPerSelection: boolean
When pasting something from an external source (not from the editor itself), if the number of lines matches the number of selection, CodeMirror will by default insert one line per selection. You can set this to false to disable that behavior.
selectionsMayTouch: boolean
Determines whether multiple selections are joined as soon as they touch (the default) or only when they overlap (true).
undoDepth: integer
The maximum number of undo levels that the editor stores. Note that this includes selection change events. Defaults to 200.
historyEventDelay: integer
The period of inactivity (in milliseconds) that will cause a new history event to be started when typing or deleting. Defaults to 1250.
tabindex: integer
The tab index to assign to the editor. If not given, no tab index will be assigned.
autofocus: boolean
Can be used to make CodeMirror focus itself on initialization. Defaults to off. When fromTextArea is used, and no explicit value is given for this option, it will be set to true when either the source textarea is focused, or it has an autofocus attribute and no other element is focused.
phrases: ?object
Some addons run user-visible strings (such as labels in the interface) through the phrase method to allow for translation. This option determines the return value of that method. When it is null or an object that doesn't have a property named by the input string, that string is returned. Otherwise, the value of the property corresponding to that string is returned.

Below this a few more specialized, low-level options are listed. These are only useful in very specific situations, you might want to skip them the first time you read this manual.

dragDrop: boolean
Controls whether drag-and-drop is enabled. On by default.
allowDropFileTypes: array<string>
When set (default is null) only files whose type is in the array can be dropped into the editor. The strings should be MIME types, and will be checked against the type of the File object as reported by the browser.
cursorBlinkRate: number
Half-period in milliseconds used for cursor blinking. The default blink rate is 530ms. By setting this to zero, blinking can be disabled. A negative value hides the cursor entirely.
cursorScrollMargin: number
How much extra space to always keep above and below the cursor when approaching the top or bottom of the visible view in a scrollable document. Default is 0.
cursorHeight: number
Determines the height of the cursor. Default is 1, meaning it spans the whole height of the line. For some fonts (and by some tastes) a smaller height (for example 0.85), which causes the cursor to not reach all the way to the bottom of the line, looks better
resetSelectionOnContextMenu: boolean
Controls whether, when the context menu is opened with a click outside of the current selection, the cursor is moved to the point of the click. Defaults to true.
workTime, workDelay: number
Highlighting is done by a pseudo background-thread that will work for workTime milliseconds, and then use timeout to sleep for workDelay milliseconds. The defaults are 200 and 300, you can change these options to make the highlighting more or less aggressive.
pollInterval: number
Indicates how quickly CodeMirror should poll its input textarea for changes (when focused). Most input is captured by events, but some things, like IME input on some browsers, don't generate events that allow CodeMirror to properly detect it. Thus, it polls. Default is 100 milliseconds.
flattenSpans: boolean
By default, CodeMirror will combine adjacent tokens into a single span if they have the same class. This will result in a simpler DOM tree, and thus perform better. With some kinds of styling (such as rounded corners), this will change the way the document looks. You can set this option to false to disable this behavior.
addModeClass: boolean
When enabled (off by default), an extra CSS class will be added to each token, indicating the (inner) mode that produced it, prefixed with "cm-m-". For example, tokens from the XML mode will get the cm-m-xml class.
maxHighlightLength: number
When highlighting long lines, in order to stay responsive, the editor will give up and simply style the rest of the line as plain text when it reaches a certain position. The default is 10 000. You can set this to Infinity to turn off this behavior.
viewportMargin: integer
Specifies the amount of lines that are rendered above and below the part of the document that's currently scrolled into view. This affects the amount of updates needed when scrolling, and the amount of work that such an update does. You should usually leave it at its default, 10. Can be set to Infinity to make sure the whole document is always rendered, and thus the browser's text search works on it. This will have bad effects on performance of big documents.
spellcheck: boolean
Specifies whether or not spellcheck will be enabled on the input.
autocorrect: boolean
Specifies whether or not autocorrect will be enabled on the input.
autocapitalize: boolean
Specifies whether or not autocapitalization will be enabled on the input.

Events

Various CodeMirror-related objects emit events, which allow client code to react to various situations. Handlers for such events can be registered with the on and off methods on the objects that the event fires on. To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object.

An editor instance fires the following events. The instance argument always refers to the editor itself.

"change" (instance: CodeMirror, changeObj: object)
Fires every time the content of the editor is changed. The changeObj is a {from, to, text, removed, origin} object containing information about the changes that occurred as second argument. from and to are the positions (in the pre-change coordinate system) where the change started and ended (for example, it might be {ch:0, line:18} if the position is at the beginning of line #19). text is an array of strings representing the text that replaced the changed range (split by line). removed is the text that used to be between from and to, which is overwritten by this change. This event is fired before the end of an operation, before the DOM updates happen.
"changes" (instance: CodeMirror, changes: array<object>)
Like the "change" event, but batched per operation, passing an array containing all the changes that happened in the operation. This event is fired after the operation finished, and display changes it makes will trigger a new operation.
"beforeChange" (instance: CodeMirror, changeObj: object)
This event is fired before a change is applied, and its handler may choose to modify or cancel the change. The changeObj object has from, to, and text properties, as with the "change" event. It also has a cancel() method, which can be called to cancel the change, and, if the change isn't coming from an undo or redo event, an update(from, to, text) method, which may be used to modify the change. Undo or redo changes can't be modified, because they hold some metainformation for restoring old marked ranges that is only valid for that specific change. All three arguments to update are optional, and can be left off to leave the existing value for that field intact. Note: you may not do anything from a "beforeChange" handler that would cause changes to the document or its visualization. Doing so will, since this handler is called directly from the bowels of the CodeMirror implementation, probably cause the editor to become corrupted.
"cursorActivity" (instance: CodeMirror)
Will be fired when the cursor or selection moves, or any change is made to the editor content.
"keyHandled" (instance: CodeMirror, name: string, event: Event)
Fired after a key is handled through a key map. name is the name of the handled key (for example "Ctrl-X" or "'q'"), and event is the DOM keydown or keypress event.
"inputRead" (instance: CodeMirror, changeObj: object)
Fired whenever new input is read from the hidden textarea (typed or pasted by the user).
"electricInput" (instance: CodeMirror, line: integer)
Fired if text input matched the mode's electric patterns, and this caused the line's indentation to change.
"beforeSelectionChange" (instance: CodeMirror, obj: {ranges, origin, update})
This event is fired before the selection is moved. Its handler may inspect the set of selection ranges, present as an array of {anchor, head} objects in the ranges property of the obj argument, and optionally change them by calling the update method on this object, passing an array of ranges in the same format. The object also contains an origin property holding the origin string passed to the selection-changing method, if any. Handlers for this event have the same restriction as "beforeChange" handlers — they should not do anything to directly update the state of the editor.
"viewportChange" (instance: CodeMirror, from: number, to: number)
Fires whenever the view port of the editor changes (due to scrolling, editing, or any other factor). The from and to arguments give the new start and end of the viewport.
"swapDoc" (instance: CodeMirror, oldDoc: Doc)
This is signalled when the editor's document is replaced using the swapDoc method.
"gutterClick" (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)
Fires when the editor gutter (the line-number area) is clicked. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw mousedown event object as fourth argument.
"gutterContextMenu" (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)
Fires when the editor gutter (the line-number area) receives a contextmenu event. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw contextmenu mouse event object as fourth argument. You can preventDefault the event, to signal that CodeMirror should do no further handling.
"focus" (instance: CodeMirror, event: Event)
Fires whenever the editor is focused.
"blur" (instance: CodeMirror, event: Event)
Fires whenever the editor is unfocused.
"scroll" (instance: CodeMirror)
Fires when the editor is scrolled.
"refresh" (instance: CodeMirror)
Fires when the editor is refreshed or resized. Mostly useful to invalidate cached values that depend on the editor or character size.
"optionChange" (instance: CodeMirror, option: string)
Dispatched every time an option is changed with setOption.
"scrollCursorIntoView" (instance: CodeMirror, event: Event)
Fires when the editor tries to scroll its cursor into view. Can be hooked into to take care of additional scrollable containers around the editor. When the event object has its preventDefault method called, CodeMirror will not itself try to scroll the window.
"update" (instance: CodeMirror)
Will be fired whenever CodeMirror updates its DOM display.
"renderLine" (instance: CodeMirror, line: LineHandle, element: Element)
Fired whenever a line is (re-)rendered to the DOM. Fired right after the DOM element is built, before it is added to the document. The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor.
"mousedown", "dblclick", "touchstart", "contextmenu", "keydown", "keypress", "keyup", "cut", "copy", "paste", "dragstart", "dragenter", "dragover", "dragleave", "drop" (instance: CodeMirror, event: Event)
Fired when CodeMirror is handling a DOM event of this type. You can preventDefault the event, or give it a truthy codemirrorIgnore property, to signal that CodeMirror should do no further handling.

Document objects (instances of CodeMirror.Doc) emit the following events:

"change" (doc: CodeMirror.Doc, changeObj: object)
Fired whenever a change occurs to the document. changeObj has a similar type as the object passed to the editor's "change" event.
"beforeChange" (doc: CodeMirror.Doc, change: object)
See the description of the same event on editor instances.
"cursorActivity" (doc: CodeMirror.Doc)
Fired whenever the cursor or selection in this document changes.
"beforeSelectionChange" (doc: CodeMirror.Doc, selection: {head, anchor})
Equivalent to the event by the same name as fired on editor instances.

Line handles (as returned by, for example, getLineHandle) support these events:

"delete" ()
Will be fired when the line object is deleted. A line object is associated with the start of the line. Mostly useful when you need to find out when your gutter markers on a given line are removed.
"change" (line: LineHandle, changeObj: object)
Fires when the line's text content is changed in any way (but the line is not deleted outright). The change object is similar to the one passed to change event on the editor object.

Marked range handles (CodeMirror.TextMarker), as returned by markText and setBookmark, emit the following events:

"beforeCursorEnter" ()
Fired when the cursor enters the marked range. From this event handler, the editor state may be inspected but not modified, with the exception that the range on which the event fires may be cleared.
"clear" (from: {line, ch}, to: {line, ch})
Fired when the range is cleared, either through cursor movement in combination with clearOnEnter or through a call to its clear() method. Will only be fired once per handle. Note that deleting the range through text editing does not fire this event, because an undo action might bring the range back into existence. from and to give the part of the document that the range spanned when it was cleared.
"hide" ()
Fired when the last part of the marker is removed from the document by editing operations.
"unhide" ()
Fired when, after the marker was removed by editing, a undo operation brought the marker back.

Line widgets (CodeMirror.LineWidget), returned by addLineWidget, fire these events:

"redraw" ()
Fired whenever the editor re-adds the widget to the DOM. This will happen once right after the widget is added (if it is scrolled into view), and then again whenever it is scrolled out of view and back in again, or when changes to the editor options or the line the widget is on require the widget to be redrawn.

Key Maps

Key maps are ways to associate keys and mouse buttons with functionality. A key map is an object mapping strings that identify the buttons to functions that implement their functionality.

The CodeMirror distributions comes with Emacs, Vim, and Sublime Text-style keymaps.

Keys are identified either by name or by character. The CodeMirror.keyNames object defines names for common keys and associates them with their key codes. Examples of names defined here are Enter, F5, and Q. These can be prefixed with Shift-, Cmd-, Ctrl-, and Alt- to specify a modifier. So for example, Shift-Ctrl-Space would be a valid key identifier.

Common example: map the Tab key to insert spaces instead of a tab character.

editor.setOption("extraKeys", {
  Tab: function(cm) {
    var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
    cm.replaceSelection(spaces);
  }
});

Alternatively, a character can be specified directly by surrounding it in single quotes, for example '$' or 'q'. Due to limitations in the way browsers fire key events, these may not be prefixed with modifiers.

To bind mouse buttons, use the names `LeftClick`, `MiddleClick`, and `RightClick`. These can also be prefixed with modifiers, and in addition, the word `Double` or `Triple` can be put before `Click` (as in `LeftDoubleClick`) to bind a double- or triple-click. The function for such a binding is passed the position that was clicked as second argument.

Multi-stroke key bindings can be specified by separating the key names by spaces in the property name, for example Ctrl-X Ctrl-V. When a map contains multi-stoke bindings or keys with modifiers that are not specified in the default order (Shift-Cmd-Ctrl-Alt), you must call CodeMirror.normalizeKeyMap on it before it can be used. This function takes a keymap and modifies it to normalize modifier order and properly recognize multi-stroke bindings. It will return the keymap itself.

The CodeMirror.keyMap object associates key maps with names. User code and key map definitions can assign extra properties to this object. Anywhere where a key map is expected, a string can be given, which will be looked up in this object. It also contains the "default" key map holding the default bindings.

The values of properties in key maps can be either functions of a single argument (the CodeMirror instance), strings, or false. Strings refer to commands, which are described below. If the property is set to false, CodeMirror leaves handling of the key up to the browser. A key handler function may return CodeMirror.Pass to indicate that it has decided not to handle the key, and other handlers (or the default behavior) should be given a turn.

Keys mapped to command names that start with the characters "go" or to functions that have a truthy motion property (which should be used for cursor-movement actions) will be fired even when an extra Shift modifier is present (i.e. "Up": "goLineUp" matches both up and shift-up). This is used to easily implement shift-selection.

Key maps can defer to each other by defining a fallthrough property. This indicates that when a key is not found in the map itself, one or more other maps should be searched. It can hold either a single key map or an array of key maps.

When a key map needs to set something up when it becomes active, or tear something down when deactivated, it can contain attach and/or detach properties, which should hold functions that take the editor instance and the next or previous keymap. Note that this only works for the top-level keymap, not for fallthrough maps or maps added with extraKeys or addKeyMap.

Commands

Commands are parameter-less actions that can be performed on an editor. Their main use is for key bindings. Commands are defined by adding properties to the CodeMirror.commands object. A number of common commands are defined by the library itself, most of them used by the default key bindings. The value of a command property must be a function of one argument (an editor instance).

Some of the commands below are referenced in the default key map, but not defined by the core library. These are intended to be defined by user code or addons.

Commands can also be run with the execCommand method.

selectAllCtrl-A (PC), Cmd-A (Mac)
Select the whole content of the editor.
singleSelectionEsc
When multiple selections are present, this deselects all but the primary selection.
killLineCtrl-K (Mac)
Emacs-style line killing. Deletes the part of the line after the cursor. If that consists only of whitespace, the newline at the end of the line is also deleted.
deleteLineCtrl-D (PC), Cmd-D (Mac)
Deletes the whole line under the cursor, including newline at the end.
delLineLeft
Delete the part of the line before the cursor.
delWrappedLineLeftCmd-Backspace (Mac)
Delete the part of the line from the left side of the visual line the cursor is on to the cursor.
delWrappedLineRightCmd-Delete (Mac)
Delete the part of the line from the cursor to the right side of the visual line the cursor is on.
undoCtrl-Z (PC), Cmd-Z (Mac)
Undo the last change. Note that, because browsers still don't make it possible for scripts to react to or customize the context menu, selecting undo (or redo) from the context menu in a CodeMirror instance does not work.
redoCtrl-Y (PC), Shift-Cmd-Z (Mac), Cmd-Y (Mac)
Redo the last undone change.
undoSelectionCtrl-U (PC), Cmd-U (Mac)
Undo the last change to the selection, or if there are no selection-only changes at the top of the history, undo the last change.
redoSelectionAlt-U (PC), Shift-Cmd-U (Mac)
Redo the last change to the selection, or the last text change if no selection changes remain.
goDocStartCtrl-Home (PC), Cmd-Up (Mac), Cmd-Home (Mac)
Move the cursor to the start of the document.
goDocEndCtrl-End (PC), Cmd-End (Mac), Cmd-Down (Mac)
Move the cursor to the end of the document.
goLineStartAlt-Left (PC), Ctrl-A (Mac)
Move the cursor to the start of the line.
goLineStartSmartHome
Move to the start of the text on the line, or if we are already there, to the actual start of the line (including whitespace).
goLineEndAlt-Right (PC), Ctrl-E (Mac)
Move the cursor to the end of the line.
goLineRightCmd-Right (Mac)
Move the cursor to the right side of the visual line it is on.
goLineLeftCmd-Left (Mac)
Move the cursor to the left side of the visual line it is on. If this line is wrapped, that may not be the start of the line.
goLineLeftSmart
Move the cursor to the left side of the visual line it is on. If that takes it to the start of the line, behave like goLineStartSmart.
goLineUpUp, Ctrl-P (Mac)
Move the cursor up one line.
goLineDownDown, Ctrl-N (Mac)
Move down one line.
goPageUpPageUp, Shift-Ctrl-V (Mac)
Move the cursor up one screen, and scroll up by the same distance.
goPageDownPageDown, Ctrl-V (Mac)
Move the cursor down one screen, and scroll down by the same distance.
goCharLeftLeft, Ctrl-B (Mac)
Move the cursor one character left, going to the previous line when hitting the start of line.
goCharRightRight, Ctrl-F (Mac)
Move the cursor one character right, going to the next line when hitting the end of line.
goColumnLeft
Move the cursor one character left, but don't cross line boundaries.
goColumnRight
Move the cursor one character right, don't cross line boundaries.
goWordLeftAlt-B (Mac)
Move the cursor to the start of the previous word.
goWordRightAlt-F (Mac)
Move the cursor to the end of the next word.
goGroupLeftCtrl-Left (PC), Alt-Left (Mac)
Move to the left of the group before the cursor. A group is a stretch of word characters, a stretch of punctuation characters, a newline, or a stretch of more than one whitespace character.
goGroupRightCtrl-Right (PC), Alt-Right (Mac)
Move to the right of the group after the cursor (see above).
delCharBeforeShift-Backspace, Ctrl-H (Mac)
Delete the character before the cursor.
delCharAfterDelete, Ctrl-D (Mac)
Delete the character after the cursor.
delWordBeforeAlt-Backspace (Mac)
Delete up to the start of the word before the cursor.
delWordAfterAlt-D (Mac)
Delete up to the end of the word after the cursor.
delGroupBeforeCtrl-Backspace (PC), Alt-Backspace (Mac)
Delete to the left of the group before the cursor.
delGroupAfterCtrl-Delete (PC), Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac)
Delete to the start of the group after the cursor.
indentAutoShift-Tab
Auto-indent the current line or selection.
indentMoreCtrl-] (PC), Cmd-] (Mac)
Indent the current line or selection by one indent unit.
indentLessCtrl-[ (PC), Cmd-[ (Mac)
Dedent the current line or selection by one indent unit.
insertTab
Insert a tab character at the cursor.
insertSoftTab
Insert the amount of spaces that match the width a tab at the cursor position would have.
defaultTabTab
If something is selected, indent it by one indent unit. If nothing is selected, insert a tab character.
transposeCharsCtrl-T (Mac)
Swap the characters before and after the cursor.
newlineAndIndentEnter
Insert a newline and auto-indent the new line.
toggleOverwriteInsert
Flip the overwrite flag.
saveCtrl-S (PC), Cmd-S (Mac)
Not defined by the core library, only referred to in key maps. Intended to provide an easy way for user code to define a save command.
findCtrl-F (PC), Cmd-F (Mac)
findNextCtrl-G (PC), Cmd-G (Mac)
findPrevShift-Ctrl-G (PC), Shift-Cmd-G (Mac)
replaceShift-Ctrl-F (PC), Cmd-Alt-F (Mac)
replaceAllShift-Ctrl-R (PC), Shift-Cmd-Alt-F (Mac)
Not defined by the core library, but defined in the search addon (or custom client addons).

Customized Styling

Up to a certain extent, CodeMirror's look can be changed by modifying style sheet files. The style sheets supplied by modes simply provide the colors for that mode, and can be adapted in a very straightforward way. To style the editor itself, it is possible to alter or override the styles defined in codemirror.css.

Some care must be taken there, since a lot of the rules in this file are necessary to have CodeMirror function properly. Adjusting colors should be safe, of course, and with some care a lot of other things can be changed as well. The CSS classes defined in this file serve the following roles:

CodeMirror
The outer element of the editor. This should be used for the editor width, height, borders and positioning. Can also be used to set styles that should hold for everything inside the editor (such as font and font size), or to set a background. Setting this class' height style to auto will make the editor resize to fit its content (it is recommended to also set the viewportMargin option to Infinity when doing this.
CodeMirror-focused
Whenever the editor is focused, the top element gets this class. This is used to hide the cursor and give the selection a different color when the editor is not focused.
CodeMirror-gutters
This is the backdrop for all gutters. Use it to set the default gutter background color, and optionally add a border on the right of the gutters.
CodeMirror-linenumbers
Use this for giving a background or width to the line number gutter.
CodeMirror-linenumber
Used to style the actual individual line numbers. These won't be children of the CodeMirror-linenumbers (plural) element, but rather will be absolutely positioned to overlay it. Use this to set alignment and text properties for the line numbers.
CodeMirror-lines
The visible lines. This is where you specify vertical padding for the editor content.
CodeMirror-cursor
The cursor is a block element that is absolutely positioned. You can make it look whichever way you want.
CodeMirror-selected
The selection is represented by span elements with this class.
CodeMirror-matchingbracket, CodeMirror-nonmatchingbracket
These are used to style matched (or unmatched) brackets.

If your page's style sheets do funky things to all div or pre elements (you probably shouldn't do that), you'll have to define rules to cancel these effects out again for elements under the CodeMirror class.

Themes are also simply CSS files, which define colors for various syntactic elements. See the files in the theme directory.

Programming API

A lot of CodeMirror features are only available through its API. Thus, you need to write code (or use addons) if you want to expose them to your users.

Whenever points in the document are represented, the API uses objects with line and ch properties. Both are zero-based. CodeMirror makes sure to 'clip' any positions passed by client code so that they fit inside the document, so you shouldn't worry too much about sanitizing your coordinates. If you give ch a value of null, or don't specify it, it will be replaced with the length of the specified line. Such positions may also have a sticky property holding "before" or "after", whether the position is associated with the character before or after it. This influences, for example, where the cursor is drawn on a line-break or bidi-direction boundary.

Methods prefixed with doc. can, unless otherwise specified, be called both on CodeMirror (editor) instances and CodeMirror.Doc instances. Methods prefixed with cm. are only available on CodeMirror instances.

Constructor

Constructing an editor instance is done with the CodeMirror(place: Element|fn(Element), ?option: object) constructor. If the place argument is a DOM element, the editor will be appended to it. If it is a function, it will be called, and is expected to place the editor into the document. options may be an element mapping option names to values. The options that it doesn't explicitly specify (or all options, if it is not passed) will be taken from CodeMirror.defaults.

Note that the options object passed to the constructor will be mutated when the instance's options are changed, so you shouldn't share such objects between instances.

See CodeMirror.fromTextArea for another way to construct an editor instance.

Content manipulation methods

doc.getValue(?separator: string) → string
Get the current editor content. You can pass it an optional argument to specify the string to be used to separate lines (defaults to "\n").
doc.setValue(content: string)
Set the editor content.
doc.getRange(from: {line, ch}, to: {line, ch}, ?separator: string) → string
Get the text between the given points in the editor, which should be {line, ch} objects. An optional third argument can be given to indicate the line separator string to use (defaults to "\n").
doc.replaceRange(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)
Replace the part of the document between from and to with the given string. from and to must be {line, ch} objects. to can be left off to simply insert the string at position from. When origin is given, it will be passed on to "change" events, and its first letter will be used to determine whether this change can be merged with previous history events, in the way described for selection origins.
doc.getLine(n: integer) → string
Get the content of line n.
doc.lineCount() → integer
Get the number of lines in the editor.
doc.firstLine() → integer
Get the number of first line in the editor. This will usually be zero but for linked sub-views, or documents instantiated with a non-zero first line, it might return other values.
doc.lastLine() → integer
Get the number of last line in the editor. This will usually be doc.lineCount() - 1, but for linked sub-views, it might return other values.
doc.getLineHandle(num: integer) → LineHandle
Fetches the line handle for the given line number.
doc.getLineNumber(handle: LineHandle) → integer
Given a line handle, returns the current position of that line (or null when it is no longer in the document).
doc.eachLine(f: (line: LineHandle))
doc.eachLine(start: integer, end: integer, f: (line: LineHandle))
Iterate over the whole document, or if start and end line numbers are given, the range from start up to (not including) end, and call f for each line, passing the line handle. This is a faster way to visit a range of line handlers than calling getLineHandle for each of them. Note that line handles have a text property containing the line's content (as a string).
doc.markClean()
Set the editor content as 'clean', a flag that it will retain until it is edited, and which will be set again when such an edit is undone again. Useful to track whether the content needs to be saved. This function is deprecated in favor of changeGeneration, which allows multiple subsystems to track different notions of cleanness without interfering.
doc.changeGeneration(?closeEvent: boolean) → integer
Returns a number that can later be passed to isClean to test whether any edits were made (and not undone) in the meantime. If closeEvent is true, the current history event will be ‘closed’, meaning it can't be combined with further changes (rapid typing or deleting events are typically combined).
doc.isClean(?generation: integer) → boolean
Returns whether the document is currently clean — not modified since initialization or the last call to markClean if no argument is passed, or since the matching call to changeGeneration if a generation value is given.

Cursor and selection methods

doc.getSelection(?lineSep: string) → string
Get the currently selected code. Optionally pass a line separator to put between the lines in the output. When multiple selections are present, they are concatenated with instances of lineSep in between.
doc.getSelections(?lineSep: string) → array<string>
Returns an array containing a string for each selection, representing the content of the selections.
doc.replaceSelection(replacement: string, ?select: string)
Replace the selection(s) with the given string. By default, the new selection ends up after the inserted text. The optional select argument can be used to change this—passing "around" will cause the new text to be selected, passing "start" will collapse the selection to the start of the inserted text.
doc.replaceSelections(replacements: array<string>, ?select: string)
The length of the given array should be the same as the number of active selections. Replaces the content of the selections with the strings in the array. The select argument works the same as in replaceSelection.
doc.getCursor(?start: string) → {line, ch}
Retrieve one end of the primary selection. start is an optional string indicating which end of the selection to return. It may be "from", "to", "head" (the side of the selection that moves when you press shift+arrow), or "anchor" (the fixed side of the selection). Omitting the argument is the same as passing "head". A {line, ch} object will be returned.
doc.listSelections() → array<{anchor, head}>
Retrieves a list of all current selections. These will always be sorted, and never overlap (overlapping selections are merged). Each object in the array contains anchor and head properties referring to {line, ch} objects.
doc.somethingSelected() → boolean
Return true if any text is selected.
doc.setCursor(pos: {line, ch}|number, ?ch: number, ?options: object)
Set the cursor position. You can either pass a single {line, ch} object, or the line and the character as two separate parameters. Will replace all selections with a single, empty selection at the given position. The supported options are the same as for setSelection.
doc.setSelection(anchor: {line, ch}, ?head: {line, ch}, ?options: object)
Set a single selection range. anchor and head should be {line, ch} objects. head defaults to anchor when not given. These options are supported:
scroll: boolean
Determines whether the selection head should be scrolled into view. Defaults to true.
origin: string
Determines whether the selection history event may be merged with the previous one. When an origin starts with the character +, and the last recorded selection had the same origin and was similar (close in time, both collapsed or both non-collapsed), the new one will replace the old one. When it starts with *, it will always replace the previous event (if that had the same origin). Built-in motion uses the "+move" origin. User input uses the "+input" origin.
bias: number
Determine the direction into which the selection endpoints should be adjusted when they fall inside an atomic range. Can be either -1 (backward) or 1 (forward). When not given, the bias will be based on the relative position of the old selection—the editor will try to move further away from that, to prevent getting stuck.
doc.setSelections(ranges: array<{anchor, head}>, ?primary: integer, ?options: object)
Sets a new set of selections. There must be at least one selection in the given array. When primary is a number, it determines which selection is the primary one. When it is not given, the primary index is taken from the previous selection, or set to the last range if the previous selection had less ranges than the new one. Supports the same options as setSelection.
doc.addSelection(anchor: {line, ch}, ?head: {line, ch})
Adds a new selection to the existing set of selections, and makes it the primary selection.
doc.extendSelection(from: {line, ch}, ?to: {line, ch}, ?options: object)
Similar to setSelection, but will, if shift is held or the extending flag is set, move the head of the selection while leaving the anchor at its current place. to is optional, and can be passed to ensure a region (for example a word or paragraph) will end up selected (in addition to whatever lies between that region and the current anchor). When multiple selections are present, all but the primary selection will be dropped by this method. Supports the same options as setSelection.
doc.extendSelections(heads: array<{line, ch}>, ?options: object)
An equivalent of extendSelection that acts on all selections at once.
doc.extendSelectionsBy(f: function(range: {anchor, head}) → {line, ch}), ?options: object)
Applies the given function to all existing selections, and calls extendSelections on the result.
doc.setExtending(value: boolean)
Sets or clears the 'extending' flag, which acts similar to the shift key, in that it will cause cursor movement and calls to extendSelection to leave the selection anchor in place.
doc.getExtending() → boolean
Get the value of the 'extending' flag.
cm.hasFocus() → boolean
Tells you whether the editor currently has focus.
cm.findPosH(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}
Used to find the target position for horizontal cursor motion. start is a {line, ch} object, amount an integer (may be negative), and unit one of the string "char", "column", or "word". Will return a position that is produced by moving amount times the distance specified by unit. When visually is true, motion in right-to-left text will be visual rather than logical. When the motion was clipped by hitting the end or start of the document, the returned value will have a hitSide property set to true.
cm.findPosV(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}
Similar to findPosH, but used for vertical motion. unit may be "line" or "page". The other arguments and the returned value have the same interpretation as they have in findPosH.
cm.findWordAt(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}
Returns the start and end of the 'word' (the stretch of letters, whitespace, or punctuation) at the given position.

Configuration methods

cm.setOption(option: string, value: any)
Change the configuration of the editor. option should the name of an option, and value should be a valid value for that option.
cm.getOption(option: string) → any
Retrieves the current value of the given option for this editor instance.
cm.addKeyMap(map: object, bottom: boolean)
Attach an additional key map to the editor. This is mostly useful for addons that need to register some key handlers without trampling on the extraKeys option. Maps added in this way have a higher precedence than the extraKeys and keyMap options, and between them, the maps added earlier have a lower precedence than those added later, unless the bottom argument was passed, in which case they end up below other key maps added with this method.
cm.removeKeyMap(map: object)
Disable a keymap added with addKeyMap. Either pass in the key map object itself, or a string, which will be compared against the name property of the active key maps.
cm.addOverlay(mode: string|object, ?options: object)
Enable a highlighting overlay. This is a stateless mini-mode that can be used to add extra highlighting. For example, the search addon uses it to highlight the term that's currently being searched. mode can be a mode spec or a mode object (an object with a token method). The options parameter is optional. If given, it should be an object, optionally containing the following options:
opaque: bool
Defaults to off, but can be given to allow the overlay styling, when not null, to override the styling of the base mode entirely, instead of the two being applied together.
priority: number
Determines the ordering in which the overlays are applied. Those with high priority are applied after those with lower priority, and able to override the opaqueness of the ones that come before. Defaults to 0.
cm.removeOverlay(mode: string|object)
Pass this the exact value passed for the mode parameter to addOverlay, or a string that corresponds to the name property of that value, to remove an overlay again.
cm.on(type: string, func: (...args))
Register an event handler for the given event type (a string) on the editor instance. There is also a CodeMirror.on(object, type, func) version that allows registering of events on any object.
cm.off(type: string, func: (...args))
Remove an event handler on the editor instance. An equivalent CodeMirror.off(object, type, func) also exists.

Document management methods

Each editor is associated with an instance of CodeMirror.Doc, its document. A document represents the editor content, plus a selection, an undo history, and a mode. A document can only be associated with a single editor at a time. You can create new documents by calling the CodeMirror.Doc(text: string, mode: Object, firstLineNumber: ?number, lineSeparator: ?string) constructor. The last three arguments are optional and can be used to set a mode for the document, make it start at a line number other than 0, and set a specific line separator respectively.

cm.getDoc() → Doc
Retrieve the currently active document from an editor.
doc.getEditor() → CodeMirror
Retrieve the editor associated with a document. May return null.
cm.swapDoc(doc: CodeMirror.Doc) → Doc
Attach a new document to the editor. Returns the old document, which is now no longer associated with an editor.
doc.copy(copyHistory: boolean) → Doc
Create an identical copy of the given doc. When copyHistory is true, the history will also be copied. Can not be called directly on an editor.
doc.linkedDoc(options: object) → Doc
Create a new document that's linked to the target document. Linked documents will stay in sync (changes to one are also applied to the other) until unlinked. These are the options that are supported:
sharedHist: boolean
When turned on, the linked copy will share an undo history with the original. Thus, something done in one of the two can be undone in the other, and vice versa.
from: integer
to: integer
Can be given to make the new document a subview of the original. Subviews only show a given range of lines. Note that line coordinates inside the subview will be consistent with those of the parent, so that for example a subview starting at line 10 will refer to its first line as line 10, not 0.
mode: string|object
By default, the new document inherits the mode of the parent. This option can be set to a mode spec to give it a different mode.
doc.unlinkDoc(doc: CodeMirror.Doc)
Break the link between two documents. After calling this, changes will no longer propagate between the documents, and, if they had a shared history, the history will become separate.
doc.iterLinkedDocs(function: (doc: CodeMirror.Doc, sharedHist: boolean))
Will call the given function for all documents linked to the target document. It will be passed two arguments, the linked document and a boolean indicating whether that document shares history with the target.

History-related methods

doc.undo()
Undo one edit (if any undo events are stored).
doc.redo()
Redo one undone edit.
doc.undoSelection()
Undo one edit or selection change.
doc.redoSelection()
Redo one undone edit or selection change.
doc.historySize() → {undo: integer, redo: integer}
Returns an object with {undo, redo} properties, both of which hold integers, indicating the amount of stored undo and redo operations.
doc.clearHistory()
Clears the editor's undo history.
doc.getHistory() → object
Get a (JSON-serializable) representation of the undo history.
doc.setHistory(history: object)
Replace the editor's undo history with the one provided, which must be a value as returned by getHistory. Note that this will have entirely undefined results if the editor content isn't also the same as it was when getHistory was called.

Text-marking methods

doc.markText(from: {line, ch}, to: {line, ch}, ?options: object) → TextMarker
Can be used to mark a range of text with a specific CSS class name. from and to should be {line, ch} objects. The options parameter is optional. When given, it should be an object that may contain the following configuration options:
className: string
Assigns a CSS class to the marked stretch of text.
inclusiveLeft: boolean
Determines whether text inserted on the left of the marker will end up inside or outside of it.
inclusiveRight: boolean
Like inclusiveLeft, but for the right side.
atomic: boolean
Atomic ranges act as a single unit when cursor movement is concerned—i.e. it is impossible to place the cursor inside of them. In atomic ranges, inclusiveLeft and inclusiveRight have a different meaning—they will prevent the cursor from being placed respectively directly before and directly after the range.
collapsed: boolean
Collapsed ranges do not show up in the display. Setting a range to be collapsed will automatically make it atomic.
clearOnEnter: boolean
When enabled, will cause the mark to clear itself whenever the cursor enters its range. This is mostly useful for text-replacement widgets that need to 'snap open' when the user tries to edit them. The "clear" event fired on the range handle can be used to be notified when this happens.
clearWhenEmpty: boolean
Determines whether the mark is automatically cleared when it becomes empty. Default is true.
replacedWith: Element
Use a given node to display this range. Implies both collapsed and atomic. The given DOM node must be an inline element (as opposed to a block element).
handleMouseEvents: boolean
When replacedWith is given, this determines whether the editor will capture mouse and drag events occurring in this widget. Default is false—the events will be left alone for the default browser handler, or specific handlers on the widget, to capture.
readOnly: boolean
A read-only span can, as long as it is not cleared, not be modified except by calling setValue to reset the whole document. Note: adding a read-only span currently clears the undo history of the editor, because existing undo events being partially nullified by read-only spans would corrupt the history (in the current implementation).
addToHistory: boolean
When set to true (default is false), adding this marker will create an event in the undo history that can be individually undone (clearing the marker).
startStyle: string
Can be used to specify an extra CSS class to be applied to the leftmost span that is part of the marker.
endStyle: string
Equivalent to startStyle, but for the rightmost span.
css: string
A string of CSS to be applied to the covered text. For example "color: #fe3".
attributes: object
When given, add the attributes in the given object to the elements created for the marked text. Adding class or style attributes this way is not supported.
shared: boolean
When the target document is linked to other documents, you can set shared to true to make the marker appear in all documents. By default, a marker appears only in its target document.
The method will return an object that represents the marker (with constructor CodeMirror.TextMarker), which exposes three methods: clear(), to remove the mark, find(), which returns a {from, to} object (both holding document positions), indicating the current position of the marked range, or undefined if the marker is no longer in the document, and finally changed(), which you can call if you've done something that might change the size of the marker (for example changing the content of a replacedWith node), and want to cheaply update the display.
doc.setBookmark(pos: {line, ch}, ?options: object) → TextMarker
Inserts a bookmark, a handle that follows the text around it as it is being edited, at the given position. A bookmark has two methods find() and clear(). The first returns the current position of the bookmark, if it is still in the document, and the second explicitly removes the bookmark. The options argument is optional. If given, the following properties are recognized:
widget: Element
Can be used to display a DOM node at the current location of the bookmark (analogous to the replacedWith option to markText).
insertLeft: boolean
By default, text typed when the cursor is on top of the bookmark will end up to the right of the bookmark. Set this option to true to make it go to the left instead.
shared: boolean
See the corresponding option to markText.
handleMouseEvents: boolean
As with markText, this determines whether mouse events on the widget inserted for this bookmark are handled by CodeMirror. The default is false.
doc.findMarks(from: {line, ch}, to: {line, ch}) → array<TextMarker>
Returns an array of all the bookmarks and marked ranges found between the given positions (non-inclusive).
doc.findMarksAt(pos: {line, ch}) → array<TextMarker>
Returns an array of all the bookmarks and marked ranges present at the given position.
doc.getAllMarks() → array<TextMarker>
Returns an array containing all marked ranges in the document.

Widget, gutter, and decoration methods

doc.setGutterMarker(line: integer|LineHandle, gutterID: string, value: Element) → LineHandle
Sets the gutter marker for the given gutter (identified by its CSS class, see the gutters option) to the given value. Value can be either null, to clear the marker, or a DOM element, to set it. The DOM element will be shown in the specified gutter next to the specified line.
doc.clearGutter(gutterID: string)
Remove all gutter markers in the gutter with the given ID.
doc.addLineClass(line: integer|LineHandle, where: string, class: string) → LineHandle
Set a CSS class name for the given line. line can be a number or a line handle. where determines to which element this class should be applied, can can be one of "text" (the text element, which lies in front of the selection), "background" (a background element that will be behind the selection), "gutter" (the line's gutter space), or "wrap" (the wrapper node that wraps all of the line's elements, including gutter elements). class should be the name of the class to apply.
doc.removeLineClass(line: integer|LineHandle, where: string, class: string) → LineHandle
Remove a CSS class from a line. line can be a line handle or number. where should be one of "text", "background", or "wrap" (see addLineClass). class can be left off to remove all classes for the specified node, or be a string to remove only a specific class.
doc.lineInfo(line: integer|LineHandle) → object
Returns the line number, text content, and marker status of the given line, which can be either a number or a line handle. The returned object has the structure {line, handle, text, gutterMarkers, textClass, bgClass, wrapClass, widgets}, where gutterMarkers is an object mapping gutter IDs to marker elements, and widgets is an array of line widgets attached to this line, and the various class properties refer to classes added with addLineClass.
cm.addWidget(pos: {line, ch}, node: Element, scrollIntoView: boolean)
Puts node, which should be an absolutely positioned DOM node, into the editor, positioned right below the given {line, ch} position. When scrollIntoView is true, the editor will ensure that the entire node is visible (if possible). To remove the widget again, simply use DOM methods (move it somewhere else, or call removeChild on its parent).
doc.addLineWidget(line: integer|LineHandle, node: Element, ?options: object) → LineWidget
Adds a line widget, an element shown below a line, spanning the whole of the editor's width, and moving the lines below it downwards. line should be either an integer or a line handle, and node should be a DOM node, which will be displayed below the given line. options, when given, should be an object that configures the behavior of the widget. The following options are supported (all default to false):
coverGutter: boolean
Whether the widget should cover the gutter.
noHScroll: boolean
Whether the widget should stay fixed in the face of horizontal scrolling.
above: boolean
Causes the widget to be placed above instead of below the text of the line.
handleMouseEvents: boolean
Determines whether the editor will capture mouse and drag events occurring in this widget. Default is false—the events will be left alone for the default browser handler, or specific handlers on the widget, to capture.
insertAt: integer
By default, the widget is added below other widgets for the line. This option can be used to place it at a different position (zero for the top, N to put it after the Nth other widget). Note that this only has effect once, when the widget is created.
Note that the widget node will become a descendant of nodes with CodeMirror-specific CSS classes, and those classes might in some cases affect it. This method returns an object that represents the widget placement. It'll have a line property pointing at the line handle that it is associated with, and the following methods:
clear()
Removes the widget.
changed()
Call this if you made some change to the widget's DOM node that might affect its height. It'll force CodeMirror to update the height of the line that contains the widget.

Sizing, scrolling and positioning methods

cm.setSize(width: number|string, height: number|string)
Programmatically set the size of the editor (overriding the applicable CSS rules). width and height can be either numbers (interpreted as pixels) or CSS units ("100%", for example). You can pass null for either of them to indicate that that dimension should not be changed.
cm.scrollTo(x: number, y: number)
Scroll the editor to a given (pixel) position. Both arguments may be left as null or undefined to have no effect.
cm.getScrollInfo() → {left, top, width, height, clientWidth, clientHeight}
Get an {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position, the size of the scrollable area, and the size of the visible area (minus scrollbars).
cm.scrollIntoView(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)
Scrolls the given position into view. what may be null to scroll the cursor into view, a {line, ch} position to scroll a character into view, a {left, top, right, bottom} pixel range (in editor-local coordinates), or a range {from, to} containing either two character positions or two pixel squares. The margin parameter is optional. When given, it indicates the amount of vertical pixels around the given area that should be made visible as well.
cm.cursorCoords(where: boolean|{line, ch}, mode: string) → {left, top, bottom}
Returns an {left, top, bottom} object containing the coordinates of the cursor position. If mode is "local", they will be relative to the top-left corner of the editable document. If it is "page" or not given, they are relative to the top-left corner of the page. If mode is "window", the coordinates are relative to the top-left corner of the currently visible (scrolled) window. where can be a boolean indicating whether you want the start (true) or the end (false) of the selection, or, if a {line, ch} object is given, it specifies the precise position at which you want to measure.
cm.charCoords(pos: {line, ch}, ?mode: string) → {left, right, top, bottom}
Returns the position and dimensions of an arbitrary character. pos should be a {line, ch} object. This differs from cursorCoords in that it'll give the size of the whole character, rather than just the position that the cursor would have when it would sit at that position.
cm.coordsChar(object: {left, top}, ?mode: string) → {line, ch}
Given an {left, top} object (e.g. coordinates of a mouse event) returns the {line, ch} position that corresponds to it. The optional mode parameter determines relative to what the coordinates are interpreted. It may be "window", "page" (the default), or "local".
cm.lineAtHeight(height: number, ?mode: string) → number
Computes the line at the given pixel height. mode can be one of the same strings that coordsChar accepts.
cm.heightAtLine(line: integer|LineHandle, ?mode: string, ?includeWidgets: bool) → number
Computes the height of the top of a line, in the coordinate system specified by mode (see coordsChar), which defaults to "page". When a line below the bottom of the document is specified, the returned value is the bottom of the last line in the document. By default, the position of the actual text is returned. If `includeWidgets` is true and the line has line widgets, the position above the first line widget is returned.
cm.defaultTextHeight() → number
Returns the line height of the default font for the editor.
cm.defaultCharWidth() → number
Returns the pixel width of an 'x' in the default font for the editor. (Note that for non-monospace fonts, this is mostly useless, and even for monospace fonts, non-ascii characters might have a different width).
cm.getViewport() → {from: number, to: number}
Returns a {from, to} object indicating the start (inclusive) and end (exclusive) of the currently rendered part of the document. In big documents, when most content is scrolled out of view, CodeMirror will only render the visible part, and a margin around it. See also the viewportChange event.
cm.refresh()
If your code does something to change the size of the editor element (window resizes are already listened for), or unhides it, you should probably follow up by calling this method to ensure CodeMirror is still looking as intended. See also the autorefresh addon.

Mode, state, and token-related methods

When writing language-aware functionality, it can often be useful to hook into the knowledge that the CodeMirror language mode has. See the section on modes for a more detailed description of how these work.

doc.getMode() → object
Gets the (outer) mode object for the editor. Note that this is distinct from getOption("mode"), which gives you the mode specification, rather than the resolved, instantiated mode object.
cm.getModeAt(pos: {line, ch}) → object
Gets the inner mode at a given position. This will return the same as getMode for simple modes, but will return an inner mode for nesting modes (such as htmlmixed).
cm.getTokenAt(pos: {line, ch}, ?precise: boolean) → object
Retrieves information about the token the current mode found before the given position (a {line, ch} object). The returned object has the following properties:
start
The character (on the given line) at which the token starts.
end
The character at which the token ends.
string
The token's string.
type
The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null).
state
The mode's state at the end of this token.
If precise is true, the token will be guaranteed to be accurate based on recent edits. If false or not specified, the token will use cached state information, which will be faster but might not be accurate if edits were recently made and highlighting has not yet completed.
cm.getLineTokens(line: integer, ?precise: boolean) → array<{start, end, string, type, state}>
This is similar to getTokenAt, but collects all tokens for a given line into an array. It is much cheaper than repeatedly calling getTokenAt, which re-parses the part of the line before the token for every call.
cm.getTokenTypeAt(pos: {line, ch}) → string
This is a (much) cheaper version of getTokenAt useful for when you just need the type of the token at a given position, and no other information. Will return null for unstyled tokens, and a string, potentially containing multiple space-separated style names, otherwise.
cm.getHelpers(pos: {line, ch}, type: string) → array<helper>
Fetch the set of applicable helper values for the given position. Helpers provide a way to look up functionality appropriate for a mode. The type argument provides the helper namespace (see registerHelper), in which the values will be looked up. When the mode itself has a property that corresponds to the type, that directly determines the keys that are used to look up the helper values (it may be either a single string, or an array of strings). Failing that, the mode's helperType property and finally the mode's name are used.
For example, the JavaScript mode has a property fold containing "brace". When the brace-fold addon is loaded, that defines a helper named brace in the fold namespace. This is then used by the foldcode addon to figure out that it can use that folding function to fold JavaScript code.
When any 'global' helpers are defined for the given namespace, their predicates are called on the current mode and editor, and all those that declare they are applicable will also be added to the array that is returned.
cm.getHelper(pos: {line, ch}, type: string) → helper
Returns the first applicable helper value. See getHelpers.
cm.getStateAfter(?line: integer, ?precise: boolean) → object
Returns the mode's parser state, if any, at the end of the given line number. If no line number is given, the state at the end of the document is returned. This can be useful for storing parsing errors in the state, or getting other kinds of contextual information for a line. precise is defined as in getTokenAt().

Miscellaneous methods

cm.operation(func: () → any) → any
CodeMirror internally buffers changes and only updates its DOM structure after it has finished performing some operation. If you need to perform a lot of operations on a CodeMirror instance, you can call this method with a function argument. It will call the function, buffering up all changes, and only doing the expensive update after the function returns. This can be a lot faster. The return value from this method will be the return value of your function.
cm.startOperation()
cm.endOperation()
In normal circumstances, use the above operation method. But if you want to buffer operations happening asynchronously, or that can't all be wrapped in a callback function, you can call startOperation to tell CodeMirror to start buffering changes, and endOperation to actually render all the updates. Be careful: if you use this API and forget to call endOperation, the editor will just never update.
cm.indentLine(line: integer, ?dir: string|integer)
Adjust the indentation of the given line. The second argument (which defaults to "smart") may be one of:
"prev"
Base indentation on the indentation of the previous line.
"smart"
Use the mode's smart indentation if available, behave like "prev" otherwise.
"add"
Increase the indentation of the line by one indent unit.
"subtract"
Reduce the indentation of the line.
<integer>
Add (positive number) or reduce (negative number) the indentation by the given amount of spaces.
cm.toggleOverwrite(?value: boolean)
Switches between overwrite and normal insert mode (when not given an argument), or sets the overwrite mode to a specific state (when given an argument).
cm.isReadOnly() → boolean
Tells you whether the editor's content can be edited by the user.
doc.lineSeparator()
Returns the preferred line separator string for this document, as per the option by the same name. When that option is null, the string "\n" is returned.
cm.execCommand(name: string)
Runs the command with the given name on the editor.
doc.posFromIndex(index: integer) → {line, ch}
Calculates and returns a {line, ch} object for a zero-based index who's value is relative to the start of the editor's text. If the index is out of range of the text then the returned object is clipped to start or end of the text respectively.
doc.indexFromPos(object: {line, ch}) → integer
The reverse of posFromIndex.
cm.focus()
Give the editor focus.
cm.phrase(text: string) → string
Allow the given string to be translated with the phrases option.
cm.getInputField() → Element
Returns the input field for the editor. Will be a textarea or an editable div, depending on the value of the inputStyle option.
cm.getWrapperElement() → Element
Returns the DOM node that represents the editor, and controls its size. Remove this from your tree to delete an editor instance.
cm.getScrollerElement() → Element
Returns the DOM node that is responsible for the scrolling of the editor.
cm.getGutterElement() → Element
Fetches the DOM node that contains the editor gutters.

Static properties

The CodeMirror object itself provides several useful properties.

CodeMirror.version: string
It contains a string that indicates the version of the library. This is a triple of integers "major.minor.patch", where patch is zero for releases, and something else (usually one) for dev snapshots.
CodeMirror.fromTextArea(textArea: TextAreaElement, ?config: object)
This method provides another way to initialize an editor. It takes a textarea DOM node as first argument and an optional configuration object as second. It will replace the textarea with a CodeMirror instance, and wire up the form of that textarea (if any) to make sure the editor contents are put into the textarea when the form is submitted. The text in the textarea will provide the content for the editor. A CodeMirror instance created this way has three additional methods:
cm.save()
Copy the content of the editor into the textarea.
cm.toTextArea()
Remove the editor, and restore the original textarea (with the editor's current content). If you dynamically create and destroy editors made with `fromTextArea`, without destroying the form they are part of, you should make sure to call `toTextArea` to remove the editor, or its `"submit"` handler on the form will cause a memory leak.
cm.getTextArea() → TextAreaElement
Returns the textarea that the instance was based on.
CodeMirror.defaults: object
An object containing default values for all options. You can assign to its properties to modify defaults (though this won't affect editors that have already been created).
CodeMirror.defineExtension(name: string, value: any)
If you want to define extra methods in terms of the CodeMirror API, it is possible to use defineExtension. This will cause the given value (usually a method) to be added to all CodeMirror instances created from then on.
CodeMirror.defineDocExtension(name: string, value: any)
Like defineExtension, but the method will be added to the interface for Doc objects instead.
CodeMirror.defineOption(name: string, default: any, updateFunc: function)
Similarly, defineOption can be used to define new options for CodeMirror. The updateFunc will be called with the editor instance and the new value when an editor is initialized, and whenever the option is modified through setOption.
CodeMirror.defineInitHook(func: function)
If your extension just needs to run some code whenever a CodeMirror instance is initialized, use CodeMirror.defineInitHook. Give it a function as its only argument, and from then on, that function will be called (with the instance as argument) whenever a new CodeMirror instance is initialized.
CodeMirror.registerHelper(type: string, name: string, value: helper)
Registers a helper value with the given name in the given namespace (type). This is used to define functionality that may be looked up by mode. Will create (if it doesn't already exist) a property on the CodeMirror object for the given type, pointing to an object that maps names to values. I.e. after doing CodeMirror.registerHelper("hint", "foo", myFoo), the value CodeMirror.hint.foo will point to myFoo.
CodeMirror.registerGlobalHelper(type: string, name: string, predicate: fn(mode, CodeMirror), value: helper)
Acts like registerHelper, but also registers this helper as 'global', meaning that it will be included by getHelpers whenever the given predicate returns true when called with the local mode and editor.
CodeMirror.Pos(line: integer, ?ch: integer, ?sticky: string)
A constructor for the objects that are used to represent positions in editor documents. sticky defaults to null, but can be set to "before" or "after" to make the position explicitly associate with the character before or after it.
CodeMirror.changeEnd(change: object) → {line, ch}
Utility function that computes an end position from a change (an object with from, to, and text properties, as passed to various event handlers). The returned position will be the end of the changed range, after the change is applied.
CodeMirror.countColumn(line: string, index: number, tabSize: number) → number
Find the column position at a given string index using a given tabsize.

Addons

The addon directory in the distribution contains a number of reusable components that implement extra editor functionality (on top of extension functions like defineOption, defineExtension, and registerHelper). In brief, they are:

dialog/dialog.js
Provides a very simple way to query users for text input. Adds the openDialog(template, callback, options) → closeFunction method to CodeMirror instances, which can be called with an HTML fragment or a detached DOM node that provides the prompt (should include an input or button tag), and a callback function that is called when the user presses enter. It returns a function closeFunction which, if called, will close the dialog immediately. openDialog takes the following options:
closeOnEnter: bool
If true, the dialog will be closed when the user presses enter in the input. Defaults to true.
closeOnBlur: bool
Determines whether the dialog is closed when it loses focus. Defaults to true.
onKeyDown: fn(event: KeyboardEvent, value: string, close: fn()) → bool
An event handler that will be called whenever keydown fires in the dialog's input. If your callback returns true, the dialog will not do any further processing of the event.
onKeyUp: fn(event: KeyboardEvent, value: string, close: fn()) → bool
Same as onKeyDown but for the keyup event.
onInput: fn(event: InputEvent, value: string, close: fn()) → bool
Same as onKeyDown but for the input event.
onClose: fn(instance):
A callback that will be called after the dialog has been closed and removed from the DOM. No return value.

Also adds an openNotification(template, options) → closeFunction function that simply shows an HTML fragment as a notification at the top of the editor. It takes a single option: duration, the amount of time after which the notification will be automatically closed. If duration is zero, the dialog will not be closed automatically.

Depends on addon/dialog/dialog.css.

search/searchcursor.js
Adds the getSearchCursor(query, start, options) → cursor method to CodeMirror instances, which can be used to implement search/replace functionality. query can be a regular expression or a string. start provides the starting position of the search. It can be a {line, ch} object, or can be left off to default to the start of the document. options is an optional object, which can contain the property `caseFold: false` to disable case folding when matching a string, or the property `multiline: disable` to disable multi-line matching for regular expressions (which may help performance). A search cursor has the following methods:
findNext() → boolean
findPrevious() → boolean
Search forward or backward from the current position. The return value indicates whether a match was found. If matching a regular expression, the return value will be the array returned by the match method, in case you want to extract matched groups.
from() → {line, ch}
to() → {line, ch}
These are only valid when the last call to findNext or findPrevious did not return false. They will return {line, ch} objects pointing at the start and end of the match.
replace(text: string, ?origin: string)
Replaces the currently found match with the given text and adjusts the cursor position to reflect the replacement.
Implements the search commands. CodeMirror has keys bound to these by default, but will not do anything with them unless an implementation is provided. Depends on searchcursor.js, and will make use of openDialog when available to make prompting for search queries less ugly.
search/jump-to-line.js
Implements a jumpToLine command and binding Alt-G to it. Accepts linenumber, +/-linenumber, line:char, scroll% and :linenumber formats. This will make use of openDialog when available to make prompting for line number neater.
search/matchesonscrollbar.js
Adds a showMatchesOnScrollbar method to editor instances, which should be given a query (string or regular expression), optionally a case-fold flag (only applicable for strings), and optionally a class name (defaults to CodeMirror-search-match) as arguments. When called, matches of the given query will be displayed on the editor's vertical scrollbar. The method returns an object with a clear method that can be called to remove the matches. Depends on the annotatescrollbar addon, and the matchesonscrollbar.css file provides a default (transparent yellowish) definition of the CSS class applied to the matches. Note that the matches are only perfectly aligned if your scrollbar does not have buttons at the top and bottom. You can use the simplescrollbar addon to make sure of this. If this addon is loaded, the search addon will automatically use it.
edit/matchbrackets.js
Defines an option matchBrackets which, when set to true or an options object, causes matching brackets to be highlighted whenever the cursor is next to them. It also adds a method matchBrackets that forces this to happen once, and a method findMatchingBracket that can be used to run the bracket-finding algorithm that this uses internally. It takes a start position and an optional config object. By default, it will find the match to a matchable character either before or after the cursor (preferring the one before), but you can control its behavior with these options:
afterCursor
Only use the character after the start position, never the one before it.
strict
Causes only matches where both brackets are at the same side of the start position to be considered.
maxScanLines
Stop after scanning this amount of lines without a successful match. Defaults to 1000.
maxScanLineLength
Ignore lines longer than this. Defaults to 10000.
maxHighlightLineLength
Don't highlight a bracket in a line longer than this. Defaults to 1000.
edit/closebrackets.js
Defines an option autoCloseBrackets that will auto-close brackets and quotes when typed. By default, it'll auto-close ()[]{}''"", but you can pass it a string similar to that (containing pairs of matching characters), or an object with pairs and optionally explode properties to customize it. explode should be a similar string that gives the pairs of characters that, when enter is pressed between them, should have the second character also moved to its own line. By default, if the active mode has a closeBrackets property, that overrides the configuration given in the option. But you can add an override property with a truthy value to override mode-specific configuration. Demo here.
edit/matchtags.js
Defines an option matchTags that, when enabled, will cause the tags around the cursor to be highlighted (using the CodeMirror-matchingtag class). Also defines a command toMatchingTag, which you can bind a key to in order to jump to the tag matching the one under the cursor. Depends on the addon/fold/xml-fold.js addon. Demo here.
edit/trailingspace.js
Adds an option showTrailingSpace which, when enabled, adds the CSS class cm-trailingspace to stretches of whitespace at the end of lines. The demo has a nice squiggly underline style for this class.
edit/closetag.js
Defines an autoCloseTags option that will auto-close XML tags when '>' or '/' is typed, and a closeTag command that closes the nearest open tag. Depends on the fold/xml-fold.js addon. See the demo.
edit/continuelist.js
Markdown specific. Defines a "newlineAndIndentContinueMarkdownList" command that can be bound to enter to automatically insert the leading characters for continuing a list. See the Markdown mode demo.
comment/comment.js
Addon for commenting and uncommenting code. Adds four methods to CodeMirror instances:
toggleComment(?options: object)
Tries to uncomment the current selection, and if that fails, line-comments it.
lineComment(from: {line, ch}, to: {line, ch}, ?options: object)
Set the lines in the given range to be line comments. Will fall back to blockComment when no line comment style is defined for the mode.
blockComment(from: {line, ch}, to: {line, ch}, ?options: object)
Wrap the code in the given range in a block comment. Will fall back to lineComment when no block comment style is defined for the mode.
uncomment(from: {line, ch}, to: {line, ch}, ?options: object) → boolean
Try to uncomment the given range. Returns true if a comment range was found and removed, false otherwise.
The options object accepted by these methods may have the following properties:
blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string
Override the comment string properties of the mode with custom comment strings.
padding: string
A string that will be inserted after opening and leading markers, and before closing comment markers. Defaults to a single space.
commentBlankLines: boolean
Whether, when adding line comments, to also comment lines that contain only whitespace.
indent: boolean
When adding line comments and this is turned on, it will align the comment block to the current indentation of the first line of the block.
fullLines: boolean
When block commenting, this controls whether the whole lines are indented, or only the precise range that is given. Defaults to true.
The addon also defines a toggleComment command, which is a shorthand command for calling toggleComment with no options.
fold/foldcode.js
Helps with code folding. Adds a foldCode method to editor instances, which will try to do a code fold starting at the given line, or unfold the fold that is already present. The method takes as first argument the position that should be folded (may be a line number or a Pos), and as second optional argument either a range-finder function, or an options object, supporting the following properties:
rangeFinder: fn(CodeMirror, Pos)
The function that is used to find foldable ranges. If this is not directly passed, it will default to CodeMirror.fold.auto, which uses getHelpers with a "fold" type to find folding functions appropriate for the local mode. There are files in the addon/fold/ directory providing CodeMirror.fold.brace, which finds blocks in brace languages (JavaScript, C, Java, etc), CodeMirror.fold.indent, for languages where indentation determines block structure (Python, Haskell), and CodeMirror.fold.xml, for XML-style languages, and CodeMirror.fold.comment, for folding comment blocks.
widget: string|Element
The widget to show for folded ranges. Can be either a string, in which case it'll become a span with class CodeMirror-foldmarker, or a DOM node.
scanUp: boolean
When true (default is false), the addon will try to find foldable ranges on the lines above the current one if there isn't an eligible one on the given line.
minFoldSize: integer
The minimum amount of lines that a fold should span to be accepted. Defaults to 0, which also allows single-line folds.
See the demo for an example.
fold/foldgutter.js
Provides an option foldGutter, which can be used to create a gutter with markers indicating the blocks that can be folded. Create a gutter using the gutters option, giving it the class CodeMirror-foldgutter or something else if you configure the addon to use a different class, and this addon will show markers next to folded and foldable blocks, and handle clicks in this gutter. Note that CSS styles should be applied to make the gutter, and the fold markers within it, visible. A default set of CSS styles are available in: addon/fold/foldgutter.css . The option can be either set to true, or an object containing the following optional option fields:
gutter: string
The CSS class of the gutter. Defaults to "CodeMirror-foldgutter". You will have to style this yourself to give it a width (and possibly a background). See the default gutter style rules above.
indicatorOpen: string | Element
A CSS class or DOM element to be used as the marker for open, foldable blocks. Defaults to "CodeMirror-foldgutter-open".
indicatorFolded: string | Element
A CSS class or DOM element to be used as the marker for folded blocks. Defaults to "CodeMirror-foldgutter-folded".
rangeFinder: fn(CodeMirror, Pos)
The range-finder function to use when determining whether something can be folded. When not given, CodeMirror.fold.auto will be used as default.
The foldOptions editor option can be set to an object to provide an editor-wide default configuration. Demo here.
runmode/runmode.js
Can be used to run a CodeMirror mode over text without actually opening an editor instance. See the demo for an example. There are alternate versions of the file available for running stand-alone (without including all of CodeMirror) and for running under node.js (see bin/source-highlight for an example of using the latter).
runmode/colorize.js
Provides a convenient way to syntax-highlight code snippets in a webpage. Depends on the runmode addon (or its standalone variant). Provides a CodeMirror.colorize function that can be called with an array (or other array-ish collection) of DOM nodes that represent the code snippets. By default, it'll get all pre tags. Will read the data-lang attribute of these nodes to figure out their language, and syntax-color their content using the relevant CodeMirror mode (you'll have to load the scripts for the relevant modes yourself). A second argument may be provided to give a default mode, used when no language attribute is found for a node. Used in this manual to highlight example code.
mode/overlay.js
Mode combinator that can be used to extend a mode with an 'overlay' — a secondary mode is run over the stream, along with the base mode, and can color specific pieces of text without interfering with the base mode. Defines CodeMirror.overlayMode, which is used to create such a mode. See this demo for a detailed example.
mode/multiplex.js
Mode combinator that can be used to easily 'multiplex' between several modes. Defines CodeMirror.multiplexingMode which, when given as first argument a mode object, and as other arguments any number of {open, close, mode [, delimStyle, innerStyle, parseDelimiters]} objects, will return a mode object that starts parsing using the mode passed as first argument, but will switch to another mode as soon as it encounters a string that occurs in one of the open fields of the passed objects. When in a sub-mode, it will go back to the top mode again when the close string is encountered. Pass "\n" for open or close if you want to switch on a blank line.
  • When delimStyle is specified, it will be the token style returned for the delimiter tokens (as well as [delimStyle]-open on the opening token and [delimStyle]-close on the closing token).
  • When innerStyle is specified, it will be the token style added for each inner mode token.
  • When parseDelimiters is true, the content of the delimiters will also be passed to the inner mode. (And delimStyle is ignored.)
The outer mode will not see the content between the delimiters. See this demo for an example.
hint/show-hint.js
Provides a framework for showing autocompletion hints. Defines editor.showHint, which takes an optional options object, and pops up a widget that allows the user to select a completion. Finding hints is done with a hinting functions (the hint option), which is a function that take an editor instance and options object, and return a {list, from, to} object, where list is an array of strings or objects (the completions), and from and to give the start and end of the token that is being completed as {line, ch} objects. An optional selectedHint property (an integer) can be added to the completion object to control the initially selected hint.
If no hinting function is given, the addon will use CodeMirror.hint.auto, which calls getHelpers with the "hint" type to find applicable hinting functions, and tries them one by one. If that fails, it looks for a "hintWords" helper to fetch a list of completable words for the mode, and uses CodeMirror.hint.fromList to complete from those.
When completions aren't simple strings, they should be objects with the following properties:
text: string
The completion text. This is the only required property.
displayText: string
The text that should be displayed in the menu.
className: string
A CSS class name to apply to the completion's line in the menu.
render: fn(Element, self, data)
A method used to create the DOM structure for showing the completion by appending it to its first argument.
hint: fn(CodeMirror, self, data)
A method used to actually apply the completion, instead of the default behavior.
from: {line, ch}
Optional from position that will be used by pick() instead of the global one passed with the full list of completions.
to: {line, ch}
Optional to position that will be used by pick() instead of the global one passed with the full list of completions.
The plugin understands the following options, which may be either passed directly in the argument to showHint, or provided by setting an hintOptions editor option to an object (the former takes precedence). The options object will also be passed along to the hinting function, which may understand additional options.
hint: function
A hinting function, as specified above. It is possible to set the async property on a hinting function to true, in which case it will be called with arguments (cm, callback, ?options), and the completion interface will only be popped up when the hinting function calls the callback, passing it the object holding the completions. The hinting function can also return a promise, and the completion interface will only be popped when the promise resolves. By default, hinting only works when there is no selection. You can give a hinting function a supportsSelection property with a truthy value to indicate that it supports selections.
completeSingle: boolean
Determines whether, when only a single completion is available, it is completed without showing the dialog. Defaults to true.
alignWithWord: boolean
Whether the pop-up should be horizontally aligned with the start of the word (true, default), or with the cursor (false).
closeOnUnfocus: boolean
When enabled (which is the default), the pop-up will close when the editor is unfocused.
customKeys: keymap
Allows you to provide a custom key map of keys to be active when the pop-up is active. The handlers will be called with an extra argument, a handle to the completion menu, which has moveFocus(n), setFocus(n), pick(), and close() methods (see the source for details), that can be used to change the focused element, pick the current element or close the menu. Additionally menuSize() can give you access to the size of the current dropdown menu, length give you the number of available completions, and data give you full access to the completion returned by the hinting function.
extraKeys: keymap
Like customKeys above, but the bindings will be added to the set of default bindings, instead of replacing them.
The following events will be fired on the completions object during completion:
"shown" ()
Fired when the pop-up is shown.
"select" (completion, Element)
Fired when a completion is selected. Passed the completion value (string or object) and the DOM node that represents it in the menu.
"pick" (completion)
Fired when a completion is picked. Passed the completion value (string or object).
"close" ()
Fired when the completion is finished.
This addon depends on styles from addon/hint/show-hint.css. Check out the demo for an example.
hint/javascript-hint.js
Defines a simple hinting function for JavaScript (CodeMirror.hint.javascript) and CoffeeScript (CodeMirror.hint.coffeescript) code. This will simply use the JavaScript environment that the editor runs in as a source of information about objects and their properties.
hint/xml-hint.js
Defines CodeMirror.hint.xml, which produces hints for XML tagnames, attribute names, and attribute values, guided by a schemaInfo option (a property of the second argument passed to the hinting function, or the third argument passed to CodeMirror.showHint).
The schema info should be an object mapping tag names to information about these tags, with optionally a "!top" property containing a list of the names of valid top-level tags. The values of the properties should be objects with optional properties children (an array of valid child element names, omit to simply allow all tags to appear) and attrs (an object mapping attribute names to null for free-form attributes, and an array of valid values for restricted attributes). Demo here.
hint/html-hint.js
Provides schema info to the xml-hint addon for HTML documents. Defines a schema object CodeMirror.htmlSchema that you can pass to as a schemaInfo option, and a CodeMirror.hint.html hinting function that automatically calls CodeMirror.hint.xml with this schema data. See the demo.
hint/css-hint.js
A hinting function for CSS, SCSS, or LESS code. Defines CodeMirror.hint.css.
hint/anyword-hint.js
A very simple hinting function (CodeMirror.hint.anyword) that simply looks for words in the nearby code and completes to those. Takes two optional options, word, a regular expression that matches words (sequences of one or more character), and range, which defines how many lines the addon should scan when completing (defaults to 500).
hint/sql-hint.js
A simple SQL hinter. Defines CodeMirror.hint.sql. Takes two optional options, tables, a object with table names as keys and array of respective column names as values, and defaultTable, a string corresponding to a table name in tables for autocompletion.
search/match-highlighter.js
Adds a highlightSelectionMatches option that can be enabled to highlight all instances of a currently selected word. Can be set either to true or to an object containing the following options: minChars, for the minimum amount of selected characters that triggers a highlight (default 2), style, for the style to be used to highlight the matches (default "matchhighlight", which will correspond to CSS class cm-matchhighlight), trim, which controls whether whitespace is trimmed from the selection, and showToken which can be set to true or to a regexp matching the characters that make up a word. When enabled, it causes the current word to be highlighted when nothing is selected (defaults to off). Demo here.
lint/lint.js
Defines an interface component for showing linting warnings, with pluggable warning sources (see html-lint.js, json-lint.js, javascript-lint.js, coffeescript-lint.js, and css-lint.js in the same directory). Defines a lint option that can be set to an annotation source (for example CodeMirror.lint.javascript), to an options object (in which case the getAnnotations field is used as annotation source), or simply to true. When no annotation source is specified, getHelper with type "lint" is used to find an annotation function. An annotation source function should, when given a document string, an options object, and an editor instance, return an array of {message, severity, from, to} objects representing problems. When the function has an async property with a truthy value, it will be called with an additional second argument, which is a callback to pass the array to. The linting function can also return a promise, in that case the linter will only be executed when the promise resolves. By default, the linter will run (debounced) whenever the document is changed. You can pass a lintOnChange: false option to disable that. Depends on addon/lint/lint.css. A demo can be found here.
selection/mark-selection.js
Causes the selected text to be marked with the CSS class CodeMirror-selectedtext when the styleSelectedText option is enabled. Useful to change the colour of the selection (in addition to the background), like in this demo.
selection/active-line.js
Defines a styleActiveLine option that, when enabled, gives the wrapper of the line that contains the cursor the class CodeMirror-activeline, adds a background with the class CodeMirror-activeline-background, and adds the class CodeMirror-activeline-gutter to the line's gutter space is enabled. The option's value may be a boolean or an object specifying the following options:
nonEmpty: bool
Controls whether single-line selections, or just cursor selections, are styled. Defaults to false (only cursor selections).
See the demo.
selection/selection-pointer.js
Defines a selectionPointer option which you can use to control the mouse cursor appearance when hovering over the selection. It can be set to a string, like "pointer", or to true, in which case the "default" (arrow) cursor will be used. You can see a demo here.
mode/loadmode.js
Defines a CodeMirror.requireMode(modename, callback) function that will try to load a given mode and call the callback when it succeeded. You'll have to set CodeMirror.modeURL to a string that mode paths can be constructed from, for example "mode/%N/%N.js"—the %N's will be replaced with the mode name. Also defines CodeMirror.autoLoadMode(instance, mode), which will ensure the given mode is loaded and cause the given editor instance to refresh its mode when the loading succeeded. See the demo.
mode/meta.js
Provides meta-information about all the modes in the distribution in a single file. Defines CodeMirror.modeInfo, an array of objects with {name, mime, mode} properties, where name is the human-readable name, mime the MIME type, and mode the name of the mode file that defines this MIME. There are optional properties mimes, which holds an array of MIME types for modes with multiple MIMEs associated, and ext, which holds an array of file extensions associated with this mode. Four convenience functions, CodeMirror.findModeByMIME, CodeMirror.findModeByExtension, CodeMirror.findModeByFileName and CodeMirror.findModeByName are provided, which return such an object given a MIME, extension, file name or mode name string. Note that, for historical reasons, this file resides in the top-level mode directory, not under addon. Demo.
comment/continuecomment.js
Adds a continueComments option, which sets whether the editor will make the next line continue a comment when you press Enter inside a comment block. Can be set to a boolean to enable/disable this functionality. Set to a string, it will continue comments using a custom shortcut. Set to an object, it will use the key property for a custom shortcut and the boolean continueLineComment property to determine whether single-line comments should be continued (defaulting to true).
display/placeholder.js
Adds a placeholder option that can be used to make content appear in the editor when it is empty and not focused. It can hold either a string or a DOM node. Also gives the editor a CodeMirror-empty CSS class whenever it doesn't contain any text. See the demo.
display/fullscreen.js
Defines an option fullScreen that, when set to true, will make the editor full-screen (as in, taking up the whole browser window). Depends on fullscreen.css. Demo here.
display/autorefresh.js
This addon can be useful when initializing an editor in a hidden DOM node, in cases where it is difficult to call refresh when the editor becomes visible. It defines an option autoRefresh which you can set to true to ensure that, if the editor wasn't visible on initialization, it will be refreshed the first time it becomes visible. This is done by polling every 250 milliseconds (you can pass a value like {delay: 500} as the option value to configure this). Note that this addon will only refresh the editor once when it first becomes visible, and won't take care of further restyling and resizing.
scroll/simplescrollbars.js
Defines two additional scrollbar models, "simple" and "overlay" (see demo) that can be selected with the scrollbarStyle option. Depends on simplescrollbars.css, which can be further overridden to style your own scrollbars.
scroll/annotatescrollbar.js
Provides functionality for showing markers on the scrollbar to call out certain parts of the document. Adds a method annotateScrollbar to editor instances that can be called, with a CSS class name as argument, to create a set of annotations. The method returns an object whose update method can be called with a sorted array of {from: Pos, to: Pos} objects marking the ranges to be highlighted. To detach the annotations, call the object's clear method.
display/rulers.js
Adds a rulers option, which can be used to show one or more vertical rulers in the editor. The option, if defined, should be given an array of {column [, className, color, lineStyle, width]} objects or numbers (which indicate a column). The ruler will be displayed at the column indicated by the number or the column property. The className property can be used to assign a custom style to a ruler. Demo here.
display/panel.js
Defines an addPanel method for CodeMirror instances, which places a DOM node above or below an editor, and shrinks the editor to make room for the node. The method takes as first argument as DOM node, and as second an optional options object. The Panel object returned by this method has a clear method that is used to remove the panel, and a changed method that can be used to notify the addon when the size of the panel's DOM node has changed.
The method accepts the following options:
position: string
Controls the position of the newly added panel. The following values are recognized:
top (default)
Adds the panel at the very top.
after-top
Adds the panel at the bottom of the top panels.
bottom
Adds the panel at the very bottom.
before-bottom
Adds the panel at the top of the bottom panels.
before: Panel
The new panel will be added before the given panel.
after: Panel
The new panel will be added after the given panel.
replace: Panel
The new panel will replace the given panel.
stable: bool
Whether to scroll the editor to keep the text's vertical position stable, when adding a panel above it. Defaults to false.
When using the after, before or replace options, if the panel doesn't exists or has been removed, the value of the position option will be used as a fallback.
A demo of the addon is available here.
wrap/hardwrap.js
Addon to perform hard line wrapping/breaking for paragraphs of text. Adds these methods to editor instances:
wrapParagraph(?pos: {line, ch}, ?options: object)
Wraps the paragraph at the given position. If pos is not given, it defaults to the cursor position.
wrapRange(from: {line, ch}, to: {line, ch}, ?options: object)
Wraps the given range as one big paragraph.
wrapParagraphsInRange(from: {line, ch}, to: {line, ch}, ?options: object)
Wraps the paragraphs in (and overlapping with) the given range individually.
The following options are recognized:
paragraphStart, paragraphEnd: RegExp
Blank lines are always considered paragraph boundaries. These options can be used to specify a pattern that causes lines to be considered the start or end of a paragraph.
column: number
The column to wrap at. Defaults to 80.
wrapOn: RegExp
A regular expression that matches only those two-character strings that allow wrapping. By default, the addon wraps on whitespace and after dash characters.
killTrailingSpace: boolean
Whether trailing space caused by wrapping should be preserved, or deleted. Defaults to true.
A demo of the addon is available here.
merge/merge.js
Implements an interface for merging changes, using either a 2-way or a 3-way view. The CodeMirror.MergeView constructor takes arguments similar to the CodeMirror constructor, first a node to append the interface to, and then an options object. Options are passed through to the editors inside the view. These extra options are recognized:
origLeft and origRight: string
If given these provide original versions of the document, which will be shown to the left and right of the editor in non-editable CodeMirror instances. The merge interface will highlight changes between the editable document and the original(s). To create a 2-way (as opposed to 3-way) merge view, provide only one of them.
revertButtons: boolean
Determines whether buttons that allow the user to revert changes are shown. Defaults to true.
revertChunk: fn(mv: MergeView, from: CodeMirror, fromStart: Pos, fromEnd: Pos, to: CodeMirror, toStart: Pos, toEnd: Pos)
Can be used to define custom behavior when the user reverts a changed chunk.
connect: string
Sets the style used to connect changed chunks of code. By default, connectors are drawn. When this is set to "align", the smaller chunk is padded to align with the bigger chunk instead.
collapseIdentical: boolean|number
When true (default is false), stretches of unchanged text will be collapsed. When a number is given, this indicates the amount of lines to leave visible around such stretches (which defaults to 2).
allowEditingOriginals: boolean
Determines whether the original editor allows editing. Defaults to false.
showDifferences: boolean
When true (the default), changed pieces of text are highlighted.
chunkClassLocation: string|Array
By default the chunk highlights are added using addLineClass with "background". Override this to customize it to be any valid `where` parameter or an Array of valid `where` parameters.
The addon also defines commands "goNextDiff" and "goPrevDiff" to quickly jump to the next changed chunk. Demo here.
tern/tern.js
Provides integration with the Tern JavaScript analysis engine, for completion, definition finding, and minor refactoring help. See the demo for a very simple integration. For more involved scenarios, see the comments at the top of the addon and the implementation of the (multi-file) demonstration on the Tern website.

Writing CodeMirror Modes

Modes typically consist of a single JavaScript file. This file defines, in the simplest case, a lexer (tokenizer) for your language—a function that takes a character stream as input, advances it past a token, and returns a style for that token. More advanced modes can also handle indentation for the language.

This section describes the low-level mode interface. Many modes are written directly against this, since it offers a lot of control, but for a quick mode definition, you might want to use the simple mode addon.

The mode script should call CodeMirror.defineMode to register itself with CodeMirror. This function takes two arguments. The first should be the name of the mode, for which you should use a lowercase string, preferably one that is also the name of the files that define the mode (i.e. "xml" is defined in xml.js). The second argument should be a function that, given a CodeMirror configuration object (the thing passed to the CodeMirror function) and an optional mode configuration object (as in the mode option), returns a mode object.

Typically, you should use this second argument to defineMode as your module scope function (modes should not leak anything into the global scope!), i.e. write your whole mode inside this function.

The main responsibility of a mode script is parsing the content of the editor. Depending on the language and the amount of functionality desired, this can be done in really easy or extremely complicated ways. Some parsers can be stateless, meaning that they look at one element (token) of the code at a time, with no memory of what came before. Most, however, will need to remember something. This is done by using a state object, which is an object that is always passed when reading a token, and which can be mutated by the tokenizer.

Modes that use a state must define a startState method on their mode object. This is a function of no arguments that produces a state object to be used at the start of a document.

The most important part of a mode object is its token(stream, state) method. All modes must define this method. It should read one token from the stream it is given as an argument, optionally update its state, and return a style string, or null for tokens that do not have to be styled. For your styles, you are encouraged to use the 'standard' names defined in the themes (without the cm- prefix). If that fails, it is also possible to come up with your own and write your own CSS theme file.

A typical token string would be "variable" or "comment". Multiple styles can be returned (separated by spaces), for example "string error" for a thing that looks like a string but is invalid somehow (say, missing its closing quote). When a style is prefixed by "line-" or "line-background-", the style will be applied to the whole line, analogous to what the addLineClass method does—styling the "text" in the simple case, and the "background" element when "line-background-" is prefixed.

The stream object that's passed to token encapsulates a line of code (tokens may never span lines) and our current position in that line. It has the following API:

eol() → boolean
Returns true only if the stream is at the end of the line.
sol() → boolean
Returns true only if the stream is at the start of the line.
peek() → string
Returns the next character in the stream without advancing it. Will return a null at the end of the line.
next() → string
Returns the next character in the stream and advances it. Also returns null when no more characters are available.
eat(match: string|regexp|function(char: string) → boolean) → string
match can be a character, a regular expression, or a function that takes a character and returns a boolean. If the next character in the stream 'matches' the given argument, it is consumed and returned. Otherwise, undefined is returned.
eatWhile(match: string|regexp|function(char: string) → boolean) → boolean
Repeatedly calls eat with the given argument, until it fails. Returns true if any characters were eaten.
eatSpace() → boolean
Shortcut for eatWhile when matching white-space.
skipToEnd()
Moves the position to the end of the line.
skipTo(str: string) → boolean
Skips to the start of the next occurrence of the given string, if found on the current line (doesn't advance the stream if the string does not occur on the line). Returns true if the string was found.
match(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean
match(pattern: regexp, ?consume: boolean) → array<string>
Act like a multi-character eat—if consume is true or not given—or a look-ahead that doesn't update the stream position—if it is false. pattern can be either a string or a regular expression starting with ^. When it is a string, caseFold can be set to true to make the match case-insensitive. When successfully matching a regular expression, the returned value will be the array returned by match, in case you need to extract matched groups.
backUp(n: integer)
Backs up the stream n characters. Backing it up further than the start of the current token will cause things to break, so be careful.
column() → integer
Returns the column (taking into account tabs) at which the current token starts.
indentation() → integer
Tells you how far the current line has been indented, in spaces. Corrects for tab characters.
current() → string
Get the string between the start of the current token and the current stream position.
lookAhead(n: number) → ?string
Get the line n (>0) lines after the current one, in order to scan ahead across line boundaries. Note that you want to do this carefully, since looking far ahead will make mode state caching much less effective.
baseToken() → ?{type: ?string, size: number}
Modes added through addOverlay (and only such modes) can use this method to inspect the current token produced by the underlying mode.

By default, blank lines are simply skipped when tokenizing a document. For languages that have significant blank lines, you can define a blankLine(state) method on your mode that will get called whenever a blank line is passed over, so that it can update the parser state.

Because state object are mutated, and CodeMirror needs to keep valid versions of a state around so that it can restart a parse at any line, copies must be made of state objects. The default algorithm used is that a new state object is created, which gets all the properties of the old object. Any properties which hold arrays get a copy of these arrays (since arrays tend to be used as mutable stacks). When this is not correct, for example because a mode mutates non-array properties of its state object, a mode object should define a copyState method, which is given a state and should return a safe copy of that state.

If you want your mode to provide smart indentation (through the indentLine method and the indentAuto and newlineAndIndent commands, to which keys can be bound), you must define an indent(state, textAfter) method on your mode object.

The indentation method should inspect the given state object, and optionally the textAfter string, which contains the text on the line that is being indented, and return an integer, the amount of spaces to indent. It should usually take the indentUnit option into account. An indentation method may return CodeMirror.Pass to indicate that it could not come up with a precise indentation.

To work well with the commenting addon, a mode may define lineComment (string that starts a line comment), blockCommentStart, blockCommentEnd (strings that start and end block comments), and blockCommentLead (a string to put at the start of continued lines in a block comment). All of these are optional.

Finally, a mode may define either an electricChars or an electricInput property, which are used to automatically reindent the line when certain patterns are typed and the electricChars option is enabled. electricChars may be a string, and will trigger a reindent whenever one of the characters in that string are typed. Often, it is more appropriate to use electricInput, which should hold a regular expression, and will trigger indentation when the part of the line before the cursor matches the expression. It should usually end with a $ character, so that it only matches when the indentation-changing pattern was just typed, not when something was typed after the pattern.

So, to summarize, a mode must provide a token method, and it may provide startState, copyState, and indent methods. For an example of a trivial mode, see the diff mode, for a more involved example, see the C-like mode.

Sometimes, it is useful for modes to nest—to have one mode delegate work to another mode. An example of this kind of mode is the mixed-mode HTML mode. To implement such nesting, it is usually necessary to create mode objects and copy states yourself. To create a mode object, there are CodeMirror.getMode(options, parserConfig), where the first argument is a configuration object as passed to the mode constructor function, and the second argument is a mode specification as in the mode option. To copy a state object, call CodeMirror.copyState(mode, state), where mode is the mode that created the given state.

In a nested mode, it is recommended to add an extra method, innerMode which, given a state object, returns a {state, mode} object with the inner mode and its state for the current position. These are used by utility scripts such as the tag closer to get context information. Use the CodeMirror.innerMode helper function to, starting from a mode and a state, recursively walk down to the innermost mode and state.

To make indentation work properly in a nested parser, it is advisable to give the startState method of modes that are intended to be nested an optional argument that provides the base indentation for the block of code. The JavaScript and CSS parser do this, for example, to allow JavaScript and CSS code inside the mixed-mode HTML mode to be properly indented.

It is possible, and encouraged, to associate your mode, or a certain configuration of your mode, with a MIME type. For example, the JavaScript mode associates itself with text/javascript, and its JSON variant with application/json. To do this, call CodeMirror.defineMIME(mime, modeSpec), where modeSpec can be a string or object specifying a mode, as in the mode option.

If a mode specification wants to add some properties to the resulting mode object, typically for use with getHelpers, it may contain a modeProps property, which holds an object. This object's properties will be copied to the actual mode object.

Sometimes, it is useful to add or override mode object properties from external code. The CodeMirror.extendMode function can be used to add properties to mode objects produced for a specific mode. Its first argument is the name of the mode, its second an object that specifies the properties that should be added. This is mostly useful to add utilities that can later be looked up through getMode.

VIM Mode API

CodeMirror has a robust VIM mode that attempts to faithfully emulate VIM's most useful features. It can be enabled by including keymap/vim.js and setting the keyMap option to "vim".

Configuration

VIM mode accepts configuration options for customizing behavior at run time. These methods can be called at any time and will affect all existing CodeMirror instances unless specified otherwise. The methods are exposed on the CodeMirror.Vim object.

setOption(name: string, value: any, ?cm: CodeMirror, ?cfg: object)
Sets the value of a VIM option. name should be the name of an option. If cfg.scope is not set and cm is provided, then sets the global and instance values of the option. Otherwise, sets either the global or instance value of the option depending on whether cfg.scope is global or local.
getOption(name: string, ?cm: CodeMirror: ?cfg: object)
Gets the current value of a VIM option. If cfg.scope is not set and cm is provided, then gets the instance value of the option, falling back to the global value if not set. If cfg.scope is provided, then gets the global or local value without checking the other.
map(lhs: string, rhs: string, ?context: string)
Maps a key sequence to another key sequence. Implements VIM's :map command. To map ; to : in VIM would be :map ; :. That would translate to CodeMirror.Vim.map(';', ':');. The context can be normal, visual, or insert, which correspond to :nmap, :vmap, and :imap respectively.
mapCommand(keys: string, type: string, name: string, ?args: object, ?extra: object)
Maps a key sequence to a motion, operator, or action type command. The args object is passed through to the command when it is invoked by the provided key sequence. extras.context can be normal, visual, or insert, to map the key sequence only in the corresponding mode. extras.isEdit is applicable only to actions, determining whether it is recorded for replay for the . single-repeat command.

Extending VIM

CodeMirror's VIM mode implements a large subset of VIM's core editing functionality. But since there's always more to be desired, there is a set of APIs for extending VIM's functionality. As with the configuration API, the methods are exposed on CodeMirror.Vim and may be called at any time.

defineOption(name: string, default: any, type: string, ?aliases: array<string>, ?callback: function (?value: any, ?cm: CodeMirror) → ?any)
Defines a VIM style option and makes it available to the :set command. Type can be boolean or string, used for validation and by :set to determine which syntax to accept. If a callback is passed in, VIM does not store the value of the option itself, but instead uses the callback as a setter/getter. If the first argument to the callback is undefined, then the callback should return the value of the option. Otherwise, it should set instead. Since VIM options have global and instance values, whether a CodeMirror instance is passed in denotes whether the global or local value should be used. Consequently, it's possible for the callback to be called twice for a single setOption or getOption call. Note that right now, VIM does not support defining buffer-local options that do not have global values. If an option should not have a global value, either always ignore the cm parameter in the callback, or always pass in a cfg.scope to setOption and getOption.
defineMotion(name: string, fn: function(cm: CodeMirror, head: {line, ch}, ?motionArgs: object}) → {line, ch})
Defines a motion command for VIM. The motion should return the desired result position of the cursor. head is the current position of the cursor. It can differ from cm.getCursor('head') if VIM is in visual mode. motionArgs is the object passed into mapCommand().
defineOperator(name: string, fn: function(cm: CodeMirror, ?operatorArgs: object, ranges: array<{anchor, head}>) → ?{line, ch})
Defines an operator command, similar to defineMotion. ranges is the range of text the operator should operate on. If the cursor should be set to a certain position after the operation finishes, it can return a cursor object.
defineAction(name: string, fn: function(cm: CodeMirror, ?actionArgs: object))
Defines an action command, similar to defineMotion. Action commands can have arbitrary behavior, making them more flexible than motions and operators, at the loss of orthogonality.
defineEx(name: string, ?prefix: string, fn: function(cm: CodeMirror, ?params: object))
Defines an Ex command, and maps it to :name. If a prefix is provided, it, and any prefixed substring of the name beginning with the prefix can be used to invoke the command. If the prefix is falsy, then name is used as the prefix. params.argString contains the part of the prompted string after the command name. params.args is params.argString split by whitespace. If the command was prefixed with a line range, params.line and params.lineEnd will be set.
================================================ FILE: third_party/CodeMirror/doc/realworld.html ================================================ CodeMirror: Real-world Uses

CodeMirror real-world uses

Create a pull request if you'd like your project to be added to this list.

================================================ FILE: third_party/CodeMirror/doc/releases.html ================================================ CodeMirror: Release History

Release notes and version history

Version 5.x

21-01-2019: Version 5.43.0:

  • Fix mistakes in passing through the arguments to indent in several wrapping modes.
  • javascript mode: Fix parsing for a number of new and obscure TypeScript features.
  • ruby mode: Support indented end tokens for heredoc strings.
  • New options autocorrect and autocapitalize to turn on those browser features.

21-12-2018: Version 5.42.2:

  • Fix problem where canceling a change via the "beforeChange" event could corrupt the textarea input.
  • Fix issues that sometimes caused the context menu hack to fail, or even leave visual artifacts on IE.
  • vim bindings: Make it possible to select text between angle brackets.
  • css mode: Fix tokenizing of CSS variables.
  • python mode: Fix another bug in tokenizing of format strings.
  • soy mode: More accurate highlighting.

20-11-2018: Version 5.42.0:

  • The markText method now takes an attributes option that can be used to add attributes text's HTML representation.
  • vim bindings: Add support for the = binding.
  • Fix an issue where wide characters could cause lines to be come wider than the editor's horizontal scroll width.
  • Optimize handling of window resize events.
  • show-hint addon: Don't assume the hints are shown in the same document the library was loaded in.
  • python mode: Fix bug where a string inside a template string broke highlighting.
  • swift mode: Support multi-line strings.

25-10-2018: Version 5.41.0:

  • A new selectionsMayTouch option controls whether multiple selections are joined when they touch (the default) or not.
  • vim bindings: Add noremap binding command.
  • Fix firing of "gutterContextMenu" event on Firefox.
  • Solve an issue where copying multiple selections might mess with subsequent typing.
  • Don't crash when endOperation is called with no operation active.
  • vim bindings: Fix insert mode repeat after visualBlock edits.
  • scheme mode: Improve highlighting of quoted expressions.
  • soy mode: Support injected data and @param in comments.
  • objective c mode: Improve conformance to the actual language.

20-09-2018: Version 5.40.2:

25-08-2018: Version 5.40.0:

  • New method phrase and option phrases to make translating UI text in addons easier.
  • closebrackets addon: Fix issue where bracket-closing wouldn't work before punctuation.
  • panel addon: Fix problem where replacing the last remaining panel dropped the newly added panel.
  • hardwrap addon: Fix an infinite loop when the indention is greater than the target column.
  • jinja2 and markdown modes: Add comment metadata.

20-07-2018: Version 5.39.2:

  • Fix issue where when you pass the document as a Doc instance to the CodeMirror constructor, the mode option was ignored.
  • Fix bug where line height could be computed wrong with a line widget below a collapsed line.
  • Fix overeager .npmignore dropping the bin/source-highlight utility from the distribution.
  • show-hint addon: Fix behavior when backspacing to the start of the line with completions open.

20-06-2018: Version 5.39.0:

  • Fix issue that in some circumstances caused content to be clipped off at the bottom after a resize.
  • markdown mode: Improve handling of blank lines in HTML tags.
  • stex mode: Add an inMathMode option to start the mode in math mode.

21-05-2018: Version 5.38.0:

  • Improve reliability of noticing a missing mouseup event during dragging.
  • Make sure getSelection is always called on the correct document.
  • Fix interpretation of line breaks and non-breaking spaces inserted by renderer in contentEditable mode.
  • Work around some browsers inexplicably making the fake scrollbars focusable.
  • Make sure coordsChar doesn't return positions inside collapsed ranges.
  • javascript mode: Support block scopes, bindingless catch, bignum suffix, s regexp flag.
  • markdown mode: Adjust a wasteful regexp.
  • show-hint addon: Allow opening the control without any item selected.
  • New theme: darcula.
  • dialog addon: Add a CSS class (dialog-opened) to the editor when a dialog is open.

20-04-2018: Version 5.37.0:

20-03-2018: Version 5.36.0:

  • Make sure all document-level event handlers are registered on the document that the editor is part of.
  • Fix issue that prevented edits whose origin starts with + from being combined in history events for an editor-less document.
  • multiplex addon: Improve handling of indentation.
  • merge addon: Use CSS :after element to style the scroll-lock icon.
  • javascript-hint addon: Don't provide completions in JSON mode.
  • continuelist addon: Fix numbering error.
  • show-hint addon: Make fromList completion strategy act on the current token up to the cursor, rather than the entire token.
  • markdown mode: Fix a regexp with potentially exponental complexity.
  • New theme: lucario.

20-02-2018: Version 5.35.0:

  • Fix problem where selection undo might change read-only documents.
  • Fix crash when calling addLineWidget on a document that has no attached editor.
  • searchcursor addon: Fix behavior of ^ in multiline regexp mode.
  • match-highlighter addon: Fix problem with matching words that have regexp special syntax in them.
  • sublime bindings: Fix addCursorToSelection for short lines.
  • vim bindings: Support alternative delimiters in replace command.
  • javascript mode: Support TypeScript intersection types, dynamic import.
  • stex mode: Fix parsing of \( \) delimiters, recognize more atom arguments.
  • haskell mode: Highlight more builtins, support <* and *>.
  • sql mode: Make it possible to disable backslash escapes in strings for dialects that don't have them, do this for MS SQL.
  • dockerfile mode: Highlight strings and ports, recognize more instructions.

29-01-2018: Version 5.34.0:

21-12-2017: Version 5.33.0:

22-11-2017: Version 5.32.0:

  • Increase contrast on default bracket-matching colors.
  • javascript mode: Recognize TypeScript type parameters for calls, type guards, and type parameter defaults. Improve handling of enum and module keywords.
  • comment addon: Fix bug when uncommenting a comment that spans all but the last selected line.
  • searchcursor addon: Fix bug in case folding.
  • emacs bindings: Prevent single-character deletions from resetting the kill ring.
  • closebrackets addon: Tweak quote matching behavior.
  • continuelist addon: Increment ordered list numbers when adding one.

20-10-2017: Version 5.31.0:

  • Modes added with addOverlay now have access to a baseToken method on their input stream, giving access to the tokens of the underlying mode.
  • Further improve selection drawing and cursor motion in right-to-left documents.
  • vim bindings: Fix ctrl-w behavior, support quote-dot and backtick-dot marks, make the wide cursor visible in contentEditable input mode.
  • continuecomment addon: Fix bug when pressing enter after a single-line block comment.
  • markdown mode: Fix issue with leaving indented fenced code blocks.
  • javascript mode: Fix bad parsing of operators without spaces between them. Fix some corner cases around semicolon insertion and regexps.

20-09-2017: Version 5.30.0:

  • Fixed a number of issues with drawing right-to-left selections and mouse selection in bidirectional text.
  • search addon: Fix crash when restarting search after doing empty search.
  • mark-selection addon: Fix off-by-one bug.
  • tern addon: Fix bad request made when editing at the bottom of a large document.
  • javascript mode: Improve parsing in a number of corner cases.
  • markdown mode: Fix crash when a sub-mode doesn't support indentation, allow uppercase X in task lists.
  • gfm mode: Don't highlight SHA1 'hashes' without numbers to avoid false positives.
  • soy mode: Support injected data and @param in comments.
  • simple mode addon: Allow groups in regexps when token isn't an array.

24-08-2017: Version 5.29.0:

  • Fix crash in contentEditable input style when editing near a bookmark.
  • Make sure change origins are preserved when splitting changes on read-only marks.
  • javascript mode: More support for TypeScript syntax.
  • d mode: Support nested comments.
  • python mode: Improve tokenizing of operators.
  • markdown mode: Further improve CommonMark conformance.
  • css mode: Don't run comment tokens through the mode's state machine.
  • shell mode: Allow strings to span lines.
  • search addon: Fix crash in persistent search when extraKeys is null.

21-07-2017: Version 5.28.0:

  • Fix copying of, or replacing editor content with, a single dash character when copying a big selection in some corner cases.
  • Make "goLineLeft"/"goLineRight" behave better on wrapped lines.
  • sql mode: Fix tokenizing of multi-dot operator and allow digits in subfield names.
  • searchcursor addon: Fix infinite loop on some composed character inputs.
  • markdown mode: Make list parsing more CommonMark-compliant.
  • gfm mode: Highlight colon syntax for emoji.

29-06-2017: Version 5.27.4:

  • Fix crash when using mode lookahead.
  • markdown mode: Don't block inner mode's indentation support.

22-06-2017: Version 5.27.2:

22-06-2017: Version 5.27.0:

  • Fix infinite loop in forced display update.
  • Properly disable the hidden textarea when readOnly is "nocursor".
  • Calling the Doc constructor without new works again.
  • sql mode: Handle nested comments.
  • javascript mode: Improve support for TypeScript syntax.
  • markdown mode: Fix bug where markup was ignored on indented paragraph lines.
  • vim bindings: Referencing invalid registers no longer causes an uncaught exception.
  • rust mode: Add the correct MIME type.
  • matchbrackets addon: Document options.
  • Mouse 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.
  • The behavior of mouse selection and dragging can now be customized with the configureMouse option.
  • Modes can now look ahead across line boundaries with the StringStream.lookahead method.
  • Introduces a "type" token type, makes modes that recognize types output it, and add styling for it to the themes.
  • New pasteLinesPerSelection option to control the behavior of pasting multiple lines into multiple selections.
  • searchcursor addon: Support multi-line regular expression matches, and normalize strings when matching.

22-05-2017: Version 5.26.0:

  • In textarea-mode, don't reset the input field during composition.
  • More careful restoration of selections in widgets, during editor redraw.
  • vim bindings: Parse line offsets in line or range specs.
  • javascript mode: More TypeScript parsing fixes.
  • julia mode: Fix issue where the mode gets stuck.
  • markdown mode: Understand cross-line links, parse all bracketed things as links.
  • soy mode: Support single-quoted strings.
  • go mode: Don't try to indent inside strings or comments.

20-04-2017: Version 5.25.2:

  • Better handling of selections that cover the whole viewport in contentEditable-mode.
  • No longer accidentally scroll the editor into view when calling setValue.
  • Work around Chrome Android bug when converting screen coordinates to editor positions.
  • Make sure long-clicking a selection sets a cursor and doesn't show the editor losing focus.
  • Fix issue where pointer events were incorrectly disabled on Chrome's overlay scrollbars.
  • javascript mode: Recognize annotations and TypeScript-style type parameters.
  • shell mode: Handle nested braces.
  • markdown mode: Make parsing of strong/em delimiters CommonMark-compliant.

20-03-2017: Version 5.25.0:

  • In contentEditable-mode, properly locate changes that repeat a character when inserted with IME.
  • Fix handling of selections bigger than the viewport in contentEditable mode.
  • Improve handling of changes that insert or delete lines in contentEditable mode.
  • Count Unicode control characters 0x80 to 0x9F as special (non-printing) chars.
  • Fix handling of shadow DOM roots when finding the active element.
  • Add role=presentation to more DOM elements to improve screen reader support.
  • merge addon: Make aligning of unchanged chunks more robust.
  • comment addon: Fix comment-toggling on a block of text that starts and ends in a (differnet) block comment.
  • javascript mode: Improve support for TypeScript syntax.
  • r mode: Fix indentation after semicolon-less statements.
  • shell mode: Properly handle escaped parentheses in parenthesized expressions.
  • markdown mode: Fix a few bugs around leaving fenced code blocks.
  • soy mode: Improve indentation.
  • lint addon: Support asynchronous linters that return promises.
  • continuelist addon: Support continuing task lists.
  • vim bindings: Make Y behave like yy.
  • sql mode: Support sqlite dialect.

22-02-2017: Version 5.24.2:

  • javascript mode: Support computed class method names.
  • merge addon: Improve aligning of unchanged code in the presence of marks and line widgets.

20-02-2017: Version 5.24.0:

  • Positions now support a sticky property which determines whether they should be associated with the character before (value "before") or after (value "after") them.
  • vim bindings: Make it possible to remove built-in bindings through the API.
  • comment addon: Support a per-mode useInnerComments option to optionally suppress descending to the inner modes to get comment strings.
  • A cursor directly before a line-wrapping break is now drawn before or after the line break depending on which direction you arrived from.
  • Visual cursor motion in line-wrapped right-to-left text should be much more correct.
  • Fix bug in handling of read-only marked text.
  • shell mode: Properly tokenize nested parentheses.
  • python mode: Support underscores in number literals.
  • sass mode: 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.
  • css mode: Expose lineComment property for LESS and SCSS dialects. Recognize vendor prefixes on pseudo-elements.
  • julia mode: Properly indent elseif lines.
  • markdown mode: Properly recognize the end of fenced code blocks when inside other markup.
  • scala mode: Improve handling of operators containing #, @, and : chars.
  • xml mode: Allow dashes in HTML tag names.
  • javascript mode: Improve parsing of async methods, TypeScript-style comma-separated superclass lists.
  • indent-fold addon: Ignore comment lines.

19-01-2017: Version 5.23.0:

  • Presentation-related elements DOM elements are now marked as such to help screen readers.
  • markdown mode: Be more picky about what HTML tags look like to avoid false positives.
  • findModeByMIME now understands +json and +xml MIME suffixes.
  • closebrackets addon: Add support for an override option to ignore language-specific defaults.
  • panel addon: Add a stable option that auto-scrolls the content to keep it in the same place when inserting/removing a panel.

20-12-2016: Version 5.22.0:

  • sublime bindings: Make selectBetweenBrackets work with multiple cursors.
  • javascript mode: Fix issues with parsing complex TypeScript types, imports, and exports.
  • A contentEditable editor instance with autofocus enabled no longer crashes during initializing.
  • emacs bindings: Export CodeMirror.emacs to allow other addons to hook into Emacs-style functionality.
  • active-line addon: Add nonEmpty option.
  • New event: optionChange.

21-11-2016: Version 5.21.0:

  • Tapping/clicking the editor in contentEditable mode on Chrome now puts the cursor at the tapped position.
  • Fix various crashes and misbehaviors when reading composition events in contentEditable mode.
  • Catches and ignores an IE 'Unspecified Error' when creating an editor in an iframe before there is a <body>.
  • merge addon: Fix several issues in the chunk-aligning feature.
  • verilog mode: Rewritten to address various issues.
  • julia mode: Recognize Julia 0.5 syntax.
  • swift mode: Various fixes and adjustments to current syntax.
  • markdown mode: Allow lists without a blank line above them.
  • The setGutterMarker, clearGutter, and lineInfo methods are now available on Doc objects.
  • The heightAtLine method now takes an extra argument to allow finding the height at the top of the line's line widgets.
  • ruby mode: else and elsif are now immediately indented.
  • vim bindings: Bind Ctrl-T and Ctrl-D to in- and dedent in insert mode.

20-10-2016: Version 5.20.0:

  • Make newlineAndIndent command work with multiple cursors on the same line.
  • Make sure keypress events for backspace are ignored.
  • Tokens styled with overlays no longer get a nonsense cm-cm-overlay class.
  • Line endings for pasted content are now normalized to the editor's preferred ending.
  • javascript mode: Improve support for class expressions. Support TypeScript optional class properties, the abstract keyword, and return type declarations for arrow functions.
  • css mode: Fix highlighting of mixed-case keywords.
  • closebrackets addon: Improve behavior when typing a quote before a string.
  • The 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).
  • The refresh event is now documented and stable.

20-09-2016: Version 5.19.0:

  • erlang mode: Fix mode crash when trying to read an empty context.
  • comment addon: Fix broken behavior when toggling comments inside a comment.
  • xml-fold addon: Fix a null-dereference bug.
  • Page up and page down now do something even in single-line documents.
  • Fix an issue where the cursor position could be off in really long (~8000 character) tokens.
  • javascript mode: Better indentation when semicolons are missing. Better support for TypeScript classes, optional parameters, and the type keyword.
  • The blur and focus events now pass the DOM event to their handlers.

23-08-2016: Version 5.18.2:

  • vue mode: Fix outdated references to renamed Pug mode dependency.

22-08-2016: Version 5.18.0:

  • Make sure gutter backgrounds stick to the rest of the gutter during horizontal scrolling.
  • The contenteditable inputStyle now properly supports pasting on pre-Edge IE versions.
  • javascript mode: Fix some small parsing bugs and improve TypeScript support.
  • matchbrackets addon: Fix bug where active highlighting was left in editor when the addon was disabled.
  • match-highlighter addon: Only start highlighting things when the editor gains focus.
  • javascript-hint addon: Also complete non-enumerable properties.
  • The addOverlay method now supports a priority option to control the order in which overlays are applied.
  • MIME types that end in +json now default to the JSON mode when the MIME itself is not defined.
  • The mode formerly known as Jade was renamed to Pug.
  • The Python mode now defaults to Python 3 (rather than 2) syntax.

19-07-2016: Version 5.17.0:

  • Fix problem with wrapped trailing whitespace displaying incorrectly.
  • Prevent IME dialog from overlapping typed content in Chrome.
  • Improve measuring of characters near a line wrap.
  • javascript mode: Improve support for async, allow trailing commas in import lists.
  • vim bindings: Fix backspace in replace mode.
  • sublime bindings: Fix some key bindings on OS X to match Sublime Text.
  • markdown mode: Add more classes to image links in highlight-formatting mode.

20-06-2016: Version 5.16.0:

  • Fix glitches when dragging content caused by the drop indicator receiving mouse events.
  • Make Control-drag work on Firefox.
  • Make clicking or selection-dragging at the end of a wrapped line select the right position.
  • show-hint addon: Prevent widget scrollbar from hiding part of the hint text.
  • rulers addon: Prevent rulers from forcing a horizontal editor scrollbar.
  • search addon: Automatically bind search-related keys in persistent dialog.
  • sublime keymap: Add a multi-cursor aware smart backspace binding.

20-05-2016: Version 5.15.2:

  • Fix a critical document corruption bug that occurs when a document is gradually grown.

20-05-2016: Version 5.15.0:

  • Fix bug that caused the selection to reset when focusing the editor in contentEditable input mode.
  • Fix issue where not all ASCII control characters were being replaced by placeholders.
  • Remove the assumption that all modes have a startState method from several wrapping modes.
  • Fix issue where the editor would complain about overlapping collapsed ranges when there weren't any.
  • Optimize document tree building when loading or pasting huge chunks of content.
  • Explicitly bind Ctrl-O on OS X to make that binding (“open line”) act as expected.
  • Pasting linewise-copied content when there is no selection now inserts the lines above the current line.
  • markdown mode: Fix several issues in matching link targets.
  • clike mode: Improve indentation of C++ template declarations.
  • javascript mode: Support async/await and improve support for TypeScript type syntax.

20-04-2016: Version 5.14.0:

21-03-2016: Version 5.13.2:

  • Solves a problem where the gutter would sometimes not extend all the way to the end of the document.

21-03-2016: Version 5.13:

19-02-2016: Version 5.12:

  • Vim bindings: Ctrl-Q is now an alias for Ctrl-V.
  • Vim bindings: The Vim API now exposes an unmap method to unmap bindings.
  • active-line addon: This addon can now style the active line's gutter.
  • FCL mode: Newly added.
  • SQL mode: Now has a Postgresql dialect.
  • Fix issue where trying to scroll to a horizontal position outside of the document's width could cause the gutter to be positioned incorrectly.
  • Use absolute, rather than fixed positioning in the context-menu intercept hack, to work around a problem when the editor is inside a transformed parent container.
  • Solve a problem where the horizontal scrollbar could hide text in Firefox.
  • Fix a bug that caused phantom scroll space under the text in some situations.
  • Sublime Text bindings: Bind delete-line to Shift-Ctrl-K on OS X.
  • Markdown mode: Fix issue where the mode would keep state related to fenced code blocks in an unsafe way, leading to occasional corrupted parses.
  • Markdown mode: Ignore backslashes in code fragments.
  • Markdown mode: Use whichever mode is registered as text/html to parse HTML.
  • Clike mode: Improve indentation of Scala => functions.
  • Python mode: Improve indentation of bracketed code.
  • HTMLMixed mode: Support multi-line opening tags for sub-languages (<script>, <style>, etc).
  • Spreadsheet mode: Fix bug where the mode did not advance the stream when finding a backslash.
  • XML mode: The mode now takes a matchClosing option to configure whether mismatched closing tags should be highlighted as errors.

20-01-2016: Version 5.11:

  • New modes: JSX, literate Haskell
  • The editor now forwards more DOM events: cut, copy, paste, and touchstart. It will also forward mousedown for drag events
  • Fixes a bug where bookmarks next to collapsed spans were not rendered
  • The Swift mode now supports auto-indentation
  • Frontmatters in the YAML frontmatter mode are now optional as intended
  • Full list of patches

21-12-2015: Version 5.10:

23-11-2015: Version 5.9:

  • Improve the way overlay (OS X-style) scrollbars are handled
  • Make annotatescrollbar and scrollpastend addons work properly together
  • Make show-hint addon select options on single click by default, move selection to hovered item
  • Properly fold comments that include block-comment-start markers
  • Many small language mode fixes
  • Full list of patches

20-10-2015: Version 5.8:

20-09-2015: Version 5.7:

20-08-2015: Version 5.6:

  • Fix bug where you could paste into a readOnly editor
  • Show a cursor at the drop location when dragging over the editor
  • The Rust mode was rewritten to handle modern Rust
  • The editor and theme CSS was cleaned up. Some selectors are now less specific than before
  • New theme: abcdef
  • Lines longer than maxHighlightLength are now less likely to mess up indentation
  • New addons: autorefresh for refreshing an editor the first time it becomes visible, and html-lint for using HTMLHint
  • The search addon now recognizes \r and \n in pattern and replacement input
  • Full list of patches

20-07-2015: Version 5.5:

25-06-2015: Version 5.4:

20-05-2015: Version 5.3:

20-04-2015: Version 5.2:

23-03-2015: Version 5.1:

20-02-2015: Version 5.0:

  • Experimental mobile support (tested on iOS, Android Chrome, stock Android browser)
  • New option inputStyle to switch between hidden textarea and contenteditable input.
  • The getInputField method is no longer guaranteed to return a textarea.
  • Full list of patches.

Version 4.x

20-02-2015: Version 4.13:

22-01-2015: Version 4.12:

9-01-2015: Version 4.11:

Unfortunately, 4.10 did not take care of the Firefox scrolling issue entirely. This release adds two more patches to address that.

29-12-2014: Version 4.10:

Emergency single-patch update to 4.9. Fixes Firefox-specific problem where the cursor could end up behind the horizontal scrollbar.

23-12-2014: Version 4.9:

22-11-2014: Version 4.8:

20-10-2014: Version 4.7:

  • Incompatible: The lint addon now passes the editor's value as first argument to asynchronous lint functions, for consistency. The editor is still passed, as fourth argument.
  • Improved handling of unicode identifiers in modes for languages that support them.
  • More mode improvements: CoffeeScript (indentation), Verilog (indentation), Scala (indentation, triple-quoted strings), and PHP (interpolated variables in heredoc strings).
  • New modes: Textile and Tornado templates.
  • Experimental new way to define modes.
  • Improvements to the Vim bindings: Arbitrary insert mode key mappings are now possible, and text objects are supported in visual mode.
  • The mode meta-information file now includes information about file extensions, and helper functions findModeByMIME and findModeByExtension.
  • New logo!
  • Full list of patches.

19-09-2014: Version 4.6:

21-08-2014: Version 4.5:

21-07-2014: Version 4.4:

  • Note: Some events might now fire in slightly different order ("change" is still guaranteed to fire before "cursorActivity")
  • Nested operations in multiple editors are now synced (complete at same time, reducing DOM reflows)
  • Visual block mode for vim (<C-v>) is nearly complete
  • New mode: Kotlin
  • Better multi-selection paste for text copied from multiple CodeMirror selections
  • Full list of patches.

23-06-2014: Version 4.3:

  • Several vim bindings improvements: search and exCommand history, global flag for :substitute, :global command.
  • Allow hiding the cursor by setting cursorBlinkRate to a negative value.
  • Make gutter markers themeable, use this in foldgutter.
  • Full list of patches.

19-05-2014: Version 4.2:

  • Fix problem where some modes were broken by the fact that empty tokens were forbidden.
  • Several fixes to context menu handling.
  • On undo, scroll change, not cursor, into view.
  • Rewritten Jade mode.
  • Various improvements to Shell (support for more syntax) and Python (better indentation) modes.
  • New mode: Cypher.
  • New theme: Neo.
  • Support direct styling options (color, line style, width) in the rulers addon.
  • Recognize per-editor configuration for the show-hint and foldcode addons.
  • More intelligent scanning for existing close tags in closetag addon.
  • In the Vim bindings: Fix bracket matching, support case conversion in visual mode, visual paste, append action.
  • Full list of patches.

22-04-2014: Version 4.1:

  • Slightly incompatible: The "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).
  • New command: insertSoftTab.
  • New mode: Django.
  • Improved modes: Verilog (rewritten), Jinja2, Haxe, PHP (string interpolation highlighted), JavaScript (indentation of trailing else, template strings), LiveScript (multi-line strings).
  • Many small issues from the 3.x→4.x transition were found and fixed.
  • Full list of patches.

20-03-2014: Version 4.0:

This is a new major version of CodeMirror. There are a few incompatible changes in the API. Upgrade with care, and read the upgrading guide.

Version 3.x

22-04-2014: Version 3.24:

Merges 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.

20-03-2014: Version 3.23:

  • In the XML mode, add brackets style to angle brackets, fix case-sensitivity of tags for HTML.
  • New mode: Dylan.
  • Many improvements to the Vim bindings.

21-02-2014: Version 3.22:

16-01-2014: Version 3.21:

  • Auto-indenting a block will no longer add trailing whitespace to blank lines.
  • Marking text has a new option clearWhenEmpty to control auto-removal.
  • Several bugfixes in the handling of bidirectional text.
  • The XML and CSS modes were largely rewritten. LESS support was added to the CSS mode.
  • The OCaml mode was moved to an mllike mode, F# support added.
  • Make it possible to fetch multiple applicable helper values with getHelpers, and to register helpers matched on predicates with registerGlobalHelper.
  • New theme pastel-on-dark.
  • Better ECMAScript 6 support in JavaScript mode.
  • Full list of patches.

21-11-2013: Version 3.20:

21-10-2013: Version 3.19:

23-09-2013: Version 3.18:

Emergency release to fix a problem in 3.17 where .setOption("lineNumbers", false) would raise an error.

23-09-2013: Version 3.17:

21-08-2013: Version 3.16:

29-07-2013: Version 3.15:

20-06-2013: Version 3.14:

20-05-2013: Version 3.13:

19-04-2013: Version 3.12:

20-03-2013: Version 3.11:

21-02-2013: Version 3.1:

25-01-2013: Version 3.02:

Single-bugfix release. Fixes a problem that prevents CodeMirror instances from being garbage-collected after they become unused.

21-01-2013: Version 3.01:

10-12-2012: Version 3.0:

New major version. Only partially backwards-compatible. See the upgrading guide for more information. Changes since release candidate 2:

  • Rewritten VIM mode.
  • Fix a few minor scrolling and sizing issues.
  • Work around Safari segfault when dragging.
  • Full list of patches.

20-11-2012: Version 3.0, release candidate 2:

  • New mode: HTTP.
  • Improved handling of selection anchor position.
  • Improve IE performance on longer lines.
  • Reduce gutter glitches during horiz. scrolling.
  • Add addKeyMap and removeKeyMap methods.
  • Rewrite formatting and closetag add-ons.
  • Full list of patches.

20-11-2012: Version 3.0, release candidate 1:

22-10-2012: Version 3.0, beta 2:

  • Fix page-based coordinate computation.
  • Fix firing of gutterClick event.
  • Add cursorHeight option.
  • Fix bi-directional text regression.
  • Add viewportMargin option.
  • Directly handle mousewheel events (again, hopefully better).
  • Make vertical cursor movement more robust (through widgets, big line gaps).
  • Add flattenSpans option.
  • Many optimizations. Poor responsiveness should be fixed.
  • Initialization in hidden state works again.
  • Full list of patches.

19-09-2012: Version 3.0, beta 1:

  • Bi-directional text support.
  • More powerful gutter model.
  • Support for arbitrary text/widget height.
  • In-line widgets.
  • Generalized event handling.

Version 2.x

21-01-2013: Version 2.38:

Integrate some bugfixes, enhancements to the vim keymap, and new modes (D, Sass, APL) from the v3 branch.

20-12-2012: Version 2.37:

  • New mode: SQL (will replace plsql and mysql modes).
  • Further work on the new VIM mode.
  • Fix Cmd/Ctrl keys on recent Operas on OS X.
  • Full list of patches.

20-11-2012: Version 2.36:

22-10-2012: Version 2.35:

19-09-2012: Version 2.34:

  • New mode: Common Lisp.
  • Fix right-click select-all on most browsers.
  • Change the way highlighting happens:
      Saves memory and CPU cycles.
      compareStates is no longer needed.
      onHighlightComplete no longer works.
  • Integrate mode (Markdown, XQuery, CSS, sTex) tests in central testsuite.
  • Add a CodeMirror.version property.
  • More robust handling of nested modes in formatting and closetag plug-ins.
  • Un/redo now preserves marked text and bookmarks.
  • Full list of patches.

23-08-2012: Version 2.33:

  • New mode: Sieve.
  • New getViewPort and onViewportChange API.
  • Configurable cursor blink rate.
  • Make binding a key to false disabling handling (again).
  • Show non-printing characters as red dots.
  • More tweaks to the scrolling model.
  • Expanded testsuite. Basic linter added.
  • Remove most uses of innerHTML. Remove CodeMirror.htmlEscape.
  • Full list of patches.

23-07-2012: Version 2.32:

Emergency fix for a bug where an editor with line wrapping on IE will break when there is no scrollbar.

20-07-2012: Version 2.31:

22-06-2012: Version 2.3:

  • New scrollbar implementation. Should flicker less. Changes DOM structure of the editor.
  • New theme: vibrant-ink.
  • Many extensions to the VIM keymap (including text objects).
  • Add mode-multiplexing utility script.
  • Fix bug where right-click paste works in read-only mode.
  • Add a getScrollInfo method.
  • Lots of other fixes.

23-05-2012: Version 2.25:

  • New mode: Erlang.
  • Remove xmlpure mode (use xml.js).
  • Fix line-wrapping in Opera.
  • Fix X Windows middle-click paste in Chrome.
  • Fix bug that broke pasting of huge documents.
  • Fix backspace and tab key repeat in Opera.

23-04-2012: Version 2.24:

  • Drop support for Internet Explorer 6.
  • New modes: Shell, Tiki wiki, Pig Latin.
  • New themes: Ambiance, Blackboard.
  • More control over drag/drop with dragDrop and onDragEvent options.
  • Make HTML mode a bit less pedantic.
  • Add compoundChange API method.
  • Several fixes in undo history and line hiding.
  • Remove (broken) support for catchall in key maps, add nofallthrough boolean field instead.

26-03-2012: Version 2.23:

  • Change default binding for tab [more]
  • New modes: XQuery and VBScript.
  • Two new themes: lesser-dark and xq-dark.
  • Differentiate between background and text styles in setLineClass.
  • Fix drag-and-drop in IE9+.
  • Extend charCoords and cursorCoords with a mode argument.
  • Add autofocus option.
  • Add findMarksAt method.

27-02-2012: Version 2.22:

27-01-2012: Version 2.21:

  • Added LESS, MySQL, Go, and Verilog modes.
  • Add smartIndent option.
  • Support a cursor in readOnly-mode.
  • Support assigning multiple styles to a token.
  • Use a new approach to drawing the selection.
  • Add scrollTo method.
  • Allow undo/redo events to span non-adjacent lines.
  • Lots and lots of bugfixes.

20-12-2011: Version 2.2:

21-11-2011: Version 2.18:

Fixes TextMarker.clear, which is broken in 2.17.

21-11-2011: Version 2.17:

  • Add support for line wrapping and code folding.
  • Add Github-style Markdown mode.
  • Add Monokai and Rubyblue themes.
  • Add setBookmark method.
  • Move some of the demo code into reusable components under lib/util.
  • Make screen-coord-finding code faster and more reliable.
  • Fix drag-and-drop in Firefox.
  • Improve support for IME.
  • Speed up content rendering.
  • Fix browser's built-in search in Webkit.
  • Make double- and triple-click work in IE.
  • Various fixes to modes.

27-10-2011: Version 2.16:

  • Add Perl, Rust, TiddlyWiki, and Groovy modes.
  • Dragging text inside the editor now moves, rather than copies.
  • Add a coordsFromIndex method.
  • API change: setValue now no longer clears history. Use clearHistory for that.
  • API change: markText now returns an object with clear and find methods. Marked text is now more robust when edited.
  • Fix editing code with tabs in Internet Explorer.

26-09-2011: Version 2.15:

Fix bug that snuck into 2.14: Clicking the character that currently has the cursor didn't re-focus the editor.

26-09-2011: Version 2.14:

23-08-2011: Version 2.13:

25-07-2011: Version 2.12:

  • Add a SPARQL mode.
  • Fix bug with cursor jumping around in an unfocused editor in IE.
  • Allow key and mouse events to bubble out of the editor. Ignore widget clicks.
  • Solve cursor flakiness after undo/redo.
  • Fix block-reindent ignoring the last few lines.
  • Fix parsing of multi-line attrs in XML mode.
  • Use innerHTML for HTML-escaping.
  • Some fixes to indentation in C-like mode.
  • Shrink horiz scrollbars when long lines removed.
  • Fix width feedback loop bug that caused the width of an inner DIV to shrink.

04-07-2011: Version 2.11:

  • Add a Scheme mode.
  • Add a replace method to search cursors, for cursor-preserving replacements.
  • Make the C-like mode mode more customizable.
  • Update XML mode to spot mismatched tags.
  • Add getStateAfter API and compareState mode API methods for finer-grained mode magic.
  • Add a getScrollerElement API method to manipulate the scrolling DIV.
  • Fix drag-and-drop for Firefox.
  • Add a C# configuration for the C-like mode.
  • Add full-screen editing and mode-changing demos.

07-06-2011: Version 2.1:

Add a theme system (demo). Note that this is not backwards-compatible—you'll have to update your styles and modes!

07-06-2011: Version 2.02:

  • Add a Lua mode.
  • Fix reverse-searching for a regexp.
  • Empty lines can no longer break highlighting.
  • Rework scrolling model (the outer wrapper no longer does the scrolling).
  • Solve horizontal jittering on long lines.
  • Add runmode.js.
  • Immediately re-highlight text when typing.
  • Fix problem with 'sticking' horizontal scrollbar.

26-05-2011: Version 2.01:

  • Add a Smalltalk mode.
  • Add a reStructuredText mode.
  • Add a Python mode.
  • Add a PL/SQL mode.
  • coordsChar now works
  • Fix a problem where onCursorActivity interfered with onChange.
  • Fix a number of scrolling and mouse-click-position glitches.
  • Pass information about the changed lines to onChange.
  • Support cmd-up/down on OS X.
  • Add triple-click line selection.
  • Don't handle shift when changing the selection through the API.
  • Support "nocursor" mode for readOnly option.
  • Add an onHighlightComplete option.
  • Fix the context menu for Firefox.

28-03-2011: Version 2.0:

CodeMirror 2 is a complete rewrite that's faster, smaller, simpler to use, and less dependent on browser quirks. See this and this for more information.

22-02-2011: Version 2.0 beta 2:

Somewhat more mature API, lots of bugs shaken out.

17-02-2011: Version 0.94:

  • tabMode: "spaces" was modified slightly (now indents when something is selected).
  • Fixes a bug that would cause the selection code to break on some IE versions.
  • Disabling spell-check on WebKit browsers now works.

08-02-2011: Version 2.0 beta 1:

CodeMirror 2 is a complete rewrite of CodeMirror, no longer depending on an editable frame.

19-01-2011: Version 0.93:

  • Added a Regular Expression parser.
  • Fixes to the PHP parser.
  • Support for regular expression in search/replace.
  • Add save method to instances created with fromTextArea.
  • Add support for MS T-SQL in the SQL parser.
  • Support use of CSS classes for highlighting brackets.
  • Fix yet another hang with line-numbering in hidden editors.

Version 0.x

28-03-2011: Version 1.0:

  • Fix error when debug history overflows.
  • Refine handling of C# verbatim strings.
  • Fix some issues with JavaScript indentation.

17-12-2010: Version 0.92:

  • Make CodeMirror work in XHTML documents.
  • Fix bug in handling of backslashes in Python strings.
  • The styleNumbers option is now officially supported and documented.
  • onLineNumberClick option added.
  • More consistent names onLoad and onCursorActivity callbacks. Old names still work, but are deprecated.
  • Add a Freemarker mode.

11-11-2010: Version 0.91:

  • Adds support for Java.
  • Small additions to the PHP and SQL parsers.
  • Work around various Webkit issues.
  • Fix toTextArea to update the code in the textarea.
  • Add a noScriptCaching option (hack to ease development).
  • Make sub-modes of HTML mixed mode configurable.

02-10-2010: Version 0.9:

  • Add support for searching backwards.
  • There are now parsers for Scheme, XQuery, and OmetaJS.
  • Makes height: "dynamic" more robust.
  • Fixes bug where paste did not work on OS X.
  • Add a enterMode and electricChars options to make indentation even more customizable.
  • Add firstLineNumber option.
  • Fix bad handling of @media rules by the CSS parser.
  • Take a new, more robust approach to working around the invisible-last-line bug in WebKit.

22-07-2010: Version 0.8:

  • Add a cursorCoords method to find the screen coordinates of the cursor.
  • A number of fixes and support for more syntax in the PHP parser.
  • Fix indentation problem with JSON-mode JS parser in Webkit.
  • Add a minification UI.
  • Support a height: dynamic mode, where the editor's height will adjust to the size of its content.
  • Better support for IME input mode.
  • Fix JavaScript parser getting confused when seeing a no-argument function call.
  • Have CSS parser see the difference between selectors and other identifiers.
  • Fix scrolling bug when pasting in a horizontally-scrolled editor.
  • Support toTextArea method in instances created with fromTextArea.
  • Work around new Opera cursor bug that causes the cursor to jump when pressing backspace at the end of a line.

27-04-2010: Version 0.67:

More consistent page-up/page-down behaviour across browsers. Fix some issues with hidden editors looping forever when line-numbers were enabled. Make PHP parser parse "\\" correctly. Have jumpToLine work on line handles, and add cursorLine function to fetch the line handle where the cursor currently is. Add new setStylesheet function to switch style-sheets in a running editor.

01-03-2010: Version 0.66:

Adds removeLine method to API. Introduces the PLSQL parser. Marks XML errors by adding (rather than replacing) a CSS class, so that they can be disabled by modifying their style. Fixes several selection bugs, and a number of small glitches.

12-11-2009: Version 0.65:

Add support for having both line-wrapping and line-numbers turned on, make paren-highlighting style customisable (markParen and unmarkParen config options), work around a selection bug that Opera reintroduced in version 10.

23-10-2009: Version 0.64:

Solves some issues introduced by the paste-handling changes from the previous release. Adds setSpellcheck, setTextWrapping, setIndentUnit, setUndoDepth, setTabMode, and setLineNumbers to customise a running editor. Introduces an SQL parser. Fixes a few small problems in the Python parser. And, as usual, add workarounds for various newly discovered browser incompatibilities.

31-08-2009: Version 0.63:

Overhaul of paste-handling (less fragile), fixes for several serious IE8 issues (cursor jumping, end-of-document bugs) and a number of small problems.

30-05-2009: Version 0.62:

Introduces Python and Lua parsers. Add setParser (on-the-fly mode changing) and clearHistory methods. Make parsing passes time-based instead of lines-based (see the passTime option).

================================================ FILE: third_party/CodeMirror/doc/reporting.html ================================================ CodeMirror: Reporting Bugs

Reporting bugs effectively

So you found a problem in CodeMirror. By all means, report it! Bug reports from users are the main drive behind improvements to CodeMirror. But first, please read over these points:

  1. CodeMirror is maintained by volunteers. They don't owe you anything, so be polite. Reports with an indignant or belligerent tone tend to be moved to the bottom of the pile.
  2. Include information about the browser in which the problem occurred. Even if you tested several browsers, and the problem occurred in all of them, mention this fact in the bug report. Also include browser version numbers and the operating system that you're on.
  3. Mention which release of CodeMirror you're using. Preferably, try also with the current development snapshot, to ensure the problem has not already been fixed.
  4. Mention very precisely what went wrong. "X is broken" is not a good bug report. What did you expect to happen? What happened instead? Describe the exact steps a maintainer has to take to reproduce the error. We can not fix something that we can not observe.
  5. If the problem can not be reproduced in any of the demos included in the CodeMirror distribution, please provide an HTML document that demonstrates the problem. The best way to do this is to go to jsbin.com, enter it there, press save, and include the resulting link in your bug report.
================================================ FILE: third_party/CodeMirror/doc/upgrade_v2.2.html ================================================ CodeMirror: Version 2.2 upgrade guide

Upgrading to v2.2

There are a few things in the 2.2 release that require some care when upgrading.

No more default.css

The default theme is now included in codemirror.css, so you do not have to included it separately anymore. (It was tiny, so even if you're not using it, the extra data overhead is negligible.)

Different key customization

CodeMirror has moved to a system where keymaps are used to bind behavior to keys. This means custom bindings are now possible.

Three options that influenced key behavior, tabMode, enterMode, and smartHome, are no longer supported. Instead, you can provide custom bindings to influence the way these keys act. This is done through the new extraKeys option, which can hold an object mapping key names to functionality. A simple example would be:

  extraKeys: {
    "Ctrl-S": function(instance) { saveText(instance.getValue()); },
    "Ctrl-/": "undo"
  }

Keys can be mapped either to functions, which will be given the editor instance as argument, or to strings, which are mapped through functions through the CodeMirror.commands table, which contains all the built-in editing commands, and can be inspected and extended by external code.

By default, the Home key is bound to the "goLineStartSmart" command, which moves the cursor to the first non-whitespace character on the line. You can set do this to make it always go to the very start instead:

  extraKeys: {"Home": "goLineStart"}

Similarly, Enter is bound to "newlineAndIndent" by default. You can bind it to something else to get different behavior. To disable special handling completely and only get a newline character inserted, you can bind it to false:

  extraKeys: {"Enter": false}

The same works for Tab. If you don't want CodeMirror to handle it, bind it to false. The default behaviour is to indent the current line more ("indentMore" command), and indent it less when shift is held ("indentLess"). There are also "indentAuto" (smart indent) and "insertTab" commands provided for alternate behaviors. Or you can write your own handler function to do something different altogether.

Tabs

Handling of tabs changed completely. The display width of tabs can now be set with the tabSize option, and tabs can be styled by setting CSS rules for the cm-tab class.

The default width for tabs is now 4, as opposed to the 8 that is hard-wired into browsers. If you are relying on 8-space tabs, make sure you explicitly set tabSize: 8 in your options.

================================================ FILE: third_party/CodeMirror/doc/upgrade_v3.html ================================================ CodeMirror: Version 3 upgrade guide

Upgrading to version 3

Version 3 does not depart too much from 2.x API, and sites that use CodeMirror in a very simple way might be able to upgrade without trouble. But it does introduce a number of incompatibilities. Please at least skim this text before upgrading.

Note that version 3 drops full support for Internet Explorer 7. The editor will mostly work on that browser, but it'll be significantly glitchy.

DOM structure

This one is the most likely to cause problems. The internal structure of the editor has changed quite a lot, mostly to implement a new scrolling model.

Editor height is now set on the outer wrapper element (CSS class CodeMirror), not on the scroller element (CodeMirror-scroll).

Other nodes were moved, dropped, and added. If you have any code that makes assumptions about the internal DOM structure of the editor, you'll have to re-test it and probably update it to work with v3.

See the styling section of the manual for more information.

Gutter model

In CodeMirror 2.x, there was a single gutter, and line markers created with setMarker would have to somehow coexist with the line numbers (if present). Version 3 allows you to specify an array of gutters, by class name, use setGutterMarker to add or remove markers in individual gutters, and clear whole gutters with clearGutter. Gutter markers are now specified as DOM nodes, rather than HTML snippets.

The gutters no longer horizontally scrolls along with the content. The fixedGutter option was removed (since it is now the only behavior).

<style>
  /* Define a gutter style */
  .note-gutter { width: 3em; background: cyan; }
</style>
<script>
  // Create an instance with two gutters -- line numbers and notes
  var cm = new CodeMirror(document.body, {
    gutters: ["note-gutter", "CodeMirror-linenumbers"],
    lineNumbers: true
  });
  // Add a note to line 0
  cm.setGutterMarker(0, "note-gutter", document.createTextNode("hi"));
</script>

Event handling

Most of the onXYZ options have been removed. The same effect is now obtained by calling the on method with a string identifying the event type. Multiple handlers can now be registered (and individually unregistered) for an event, and objects such as line handlers now also expose events. See the full list here.

(The onKeyEvent and onDragEvent options, which act more as hooks than as event handlers, are still there in their old form.)

cm.on("change", function(cm, change) {
  console.log("something changed! (" + change.origin + ")");
});

markText method arguments

The markText method (which has gained some interesting new features, such as creating atomic and read-only spans, or replacing spans with widgets) no longer takes the CSS class name as a separate argument, but makes it an optional field in the options object instead.

// Style first ten lines, and forbid the cursor from entering them
cm.markText({line: 0, ch: 0}, {line: 10, ch: 0}, {
  className: "magic-text",
  inclusiveLeft: true,
  atomic: true
});

Line folding

The interface for hiding lines has been removed. markText can now be used to do the same in a more flexible and powerful way.

The folding script has been updated to use the new interface, and should now be more robust.

// Fold a range, replacing it with the text "??"
var range = cm.markText({line: 4, ch: 2}, {line: 8, ch: 1}, {
  replacedWith: document.createTextNode("??"),
  // Auto-unfold when cursor moves into the range
  clearOnEnter: true
});
// Get notified when auto-unfolding
CodeMirror.on(range, "clear", function() {
  console.log("boom");
});

Line CSS classes

The setLineClass method has been replaced by addLineClass and removeLineClass, which allow more modular control over the classes attached to a line.

var marked = cm.addLineClass(10, "background", "highlighted-line");
setTimeout(function() {
  cm.removeLineClass(marked, "background", "highlighted-line");
});

Position properties

All methods that take or return objects that represent screen positions now use {left, top, bottom, right} properties (not always all of them) instead of the {x, y, yBot} used by some methods in v2.x.

Affected methods are cursorCoords, charCoords, coordsChar, and getScrollInfo.

Bracket matching no longer in core

The matchBrackets option is no longer defined in the core editor. Load addon/edit/matchbrackets.js to enable it.

Mode management

The CodeMirror.listModes and CodeMirror.listMIMEs functions, used for listing defined modes, are gone. You are now encouraged to simply inspect CodeMirror.modes (mapping mode names to mode constructors) and CodeMirror.mimeModes (mapping MIME strings to mode specs).

New features

Some more reasons to upgrade to version 3.

  • Bi-directional text support. CodeMirror will now mostly do the right thing when editing Arabic or Hebrew text.
  • Arbitrary line heights. Using fonts with different heights inside the editor (whether off by one pixel or fifty) is now supported and handled gracefully.
  • In-line widgets. See the demo and the docs.
  • Defining custom options with CodeMirror.defineOption.
================================================ FILE: third_party/CodeMirror/doc/upgrade_v4.html ================================================ CodeMirror: Version 4 upgrade guide

Upgrading to version 4

CodeMirror 4's interface is very close version 3, but it does fix a few awkward details in a backwards-incompatible ways. At least skim the text below before upgrading.

Multiple selections

The main new feature in version 4 is multiple selections. The single-selection variants of methods are still there, but now typically act only on the primary selection (usually the last one added).

The exception to this is getSelection, which will now return the content of all selections (separated by newlines, or whatever lineSep parameter you passed it).

The beforeSelectionChange event

This event still exists, but the object it is passed has a completely new interface, because such changes now concern multiple selections.

replaceSelection's collapsing behavior

By default, replaceSelection would leave the newly inserted text selected. This is only rarely what you want, and also (slightly) more expensive in the new model, so the default was changed to "end", meaning the old behavior must be explicitly specified by passing a second argument of "around".

change event data

Rather than forcing client code to follow next pointers from one change object to the next, the library will now simply fire multiple "change" events. Existing code will probably continue to work unmodified.

showIfHidden option to line widgets

This option, which conceptually caused line widgets to be visible even if their line was hidden, was never really well-defined, and was buggy from the start. It would be a rather expensive feature, both in code complexity and run-time performance, to implement properly. It has been dropped entirely in 4.0.

Module loaders

All modules in the CodeMirror distribution are now wrapped in a shim function to make them compatible with both AMD (requirejs) and CommonJS (as used by node and browserify) module loaders. When neither of these is present, they fall back to simply using the global CodeMirror variable.

If you have a module loader present in your environment, CodeMirror will attempt to use it, and you might need to change the way you load CodeMirror modules.

Mutating shared data structures

Data structures produced by the library should not be mutated unless explicitly allowed, in general. This is slightly more strict in 4.0 than it was in earlier versions, which copied the position objects returned by getCursor for nebulous, historic reasons. In 4.0, mutating these objects will corrupt your editor's selection.

Deprecated interfaces dropped

A few properties and methods that have been deprecated for a while are now gone. Most notably, the onKeyEvent and onDragEvent options (use the corresponding events instead).

Two silly methods, which were mostly there to stay close to the 0.x API, setLine and removeLine are now gone. Use the more flexible replaceRange method instead.

The long names for folding and completing functions (CodeMirror.braceRangeFinder, CodeMirror.javascriptHint, etc) are also gone (use CodeMirror.fold.brace, CodeMirror.hint.javascript).

The className property in the return value of getTokenAt, which has been superseded by the type property, is also no longer present.

================================================ FILE: third_party/CodeMirror/index.html ================================================ CodeMirror

CodeMirror is a versatile text editor implemented in JavaScript for the browser. It is specialized for editing code, and comes with a number of language modes and addons that implement more advanced editing functionality.

A rich programming API and a CSS theming system are available for customizing CodeMirror to fit your application, and extending it with new functionality.

This is CodeMirror

Get the current version: 5.43.0.
You can see the code,
read the release notes,
or study the user manual.
Software needs maintenance,
maintainers need to subsist.
You can help per month or once.

Features

Community

CodeMirror is an open-source project shared under an MIT license. It is the editor used in the dev tools for Firefox, Chrome, and Safari, in Light Table, Adobe Brackets, Bitbucket, and many other projects.

Development and bug tracking happens on github (alternate git repository). Please read these pointers before submitting a bug. Use pull requests to submit patches. All contributions must be released under the same MIT license that CodeMirror uses.

Discussion around the project is done on a discussion forum. Announcements related to the project, such as new versions, are posted in the forum's "announce" category. If needed, you can contact the maintainer directly. We aim to be an inclusive, welcoming community. To make that explicit, we have a code of conduct that applies to communication around the project.

A list of CodeMirror-related software that is not part of the main distribution is maintained on our wiki. Feel free to add your project.

Browser support

The desktop versions of the following browsers, in standards mode (HTML5 <!doctype html> recommended) are supported:

Firefoxversion 4 and up
Chromeany version
Safariversion 5.2 and up
Internet Explorer/Edgeversion 8 and up
Operaversion 9 and up

Support for modern mobile browsers is experimental. Recent versions of the iOS browser and Chrome on Android should work pretty well.

================================================ FILE: third_party/CodeMirror/keymap/emacs.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var Pos = CodeMirror.Pos; function posEq(a, b) { return a.line == b.line && a.ch == b.ch; } // Kill 'ring' var killRing = []; function addToRing(str) { killRing.push(str); if (killRing.length > 50) killRing.shift(); } function growRingTop(str) { if (!killRing.length) return addToRing(str); killRing[killRing.length - 1] += str; } function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; } function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); } var lastKill = null; function kill(cm, from, to, ring, text) { if (text == null) text = cm.getRange(from, to); if (ring == "grow" && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen)) growRingTop(text); else if (ring !== false) addToRing(text); cm.replaceRange("", from, to, "+delete"); if (ring == "grow") lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()}; else lastKill = null; } // Boundaries of various units function byChar(cm, pos, dir) { return cm.findPosH(pos, dir, "char", true); } function byWord(cm, pos, dir) { return cm.findPosH(pos, dir, "word", true); } function byLine(cm, pos, dir) { return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn); } function byPage(cm, pos, dir) { return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn); } function byParagraph(cm, pos, dir) { var no = pos.line, line = cm.getLine(no); var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch)); var fst = cm.firstLine(), lst = cm.lastLine(); for (;;) { no += dir; if (no < fst || no > lst) return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null)); line = cm.getLine(no); var hasText = /\S/.test(line); if (hasText) sawText = true; else if (sawText) return Pos(no, 0); } } function bySentence(cm, pos, dir) { var line = pos.line, ch = pos.ch; var text = cm.getLine(pos.line), sawWord = false; for (;;) { var next = text.charAt(ch + (dir < 0 ? -1 : 0)); if (!next) { // End/beginning of line reached if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch); text = cm.getLine(line + dir); if (!/\S/.test(text)) return Pos(line, ch); line += dir; ch = dir < 0 ? text.length : 0; continue; } if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0)); if (!sawWord) sawWord = /\w/.test(next); ch += dir; } } function byExpr(cm, pos, dir) { var wrap; if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, {strict: true})) && wrap.match && (wrap.forward ? 1 : -1) == dir) return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to; for (var first = true;; first = false) { var token = cm.getTokenAt(pos); var after = Pos(pos.line, dir < 0 ? token.start : token.end); if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) { var newPos = cm.findPosH(after, dir, "char"); if (posEq(after, newPos)) return pos; else pos = newPos; } else { return after; } } } // Prefixes (only crudely supported) function getPrefix(cm, precise) { var digits = cm.state.emacsPrefix; if (!digits) return precise ? null : 1; clearPrefix(cm); return digits == "-" ? -1 : Number(digits); } function repeated(cmd) { var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd; return function(cm) { var prefix = getPrefix(cm); f(cm); for (var i = 1; i < prefix; ++i) f(cm); }; } function findEnd(cm, pos, by, dir) { var prefix = getPrefix(cm); if (prefix < 0) { dir = -dir; prefix = -prefix; } for (var i = 0; i < prefix; ++i) { var newPos = by(cm, pos, dir); if (posEq(newPos, pos)) break; pos = newPos; } return pos; } function move(by, dir) { var f = function(cm) { cm.extendSelection(findEnd(cm, cm.getCursor(), by, dir)); }; f.motion = true; return f; } function killTo(cm, by, dir, ring) { var selections = cm.listSelections(), cursor; var i = selections.length; while (i--) { cursor = selections[i].head; kill(cm, cursor, findEnd(cm, cursor, by, dir), ring); } } function killRegion(cm, ring) { if (cm.somethingSelected()) { var selections = cm.listSelections(), selection; var i = selections.length; while (i--) { selection = selections[i]; kill(cm, selection.anchor, selection.head, ring); } return true; } } function addPrefix(cm, digit) { if (cm.state.emacsPrefix) { if (digit != "-") cm.state.emacsPrefix += digit; return; } // Not active yet cm.state.emacsPrefix = digit; cm.on("keyHandled", maybeClearPrefix); cm.on("inputRead", maybeDuplicateInput); } var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true}; function maybeClearPrefix(cm, arg) { if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg)) clearPrefix(cm); } function clearPrefix(cm) { cm.state.emacsPrefix = null; cm.off("keyHandled", maybeClearPrefix); cm.off("inputRead", maybeDuplicateInput); } function maybeDuplicateInput(cm, event) { var dup = getPrefix(cm); if (dup > 1 && event.origin == "+input") { var one = event.text.join("\n"), txt = ""; for (var i = 1; i < dup; ++i) txt += one; cm.replaceSelection(txt); } } function addPrefixMap(cm) { cm.state.emacsPrefixMap = true; cm.addKeyMap(prefixMap); cm.on("keyHandled", maybeRemovePrefixMap); cm.on("inputRead", maybeRemovePrefixMap); } function maybeRemovePrefixMap(cm, arg) { if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return; cm.removeKeyMap(prefixMap); cm.state.emacsPrefixMap = false; cm.off("keyHandled", maybeRemovePrefixMap); cm.off("inputRead", maybeRemovePrefixMap); } // Utilities function setMark(cm) { cm.setCursor(cm.getCursor()); cm.setExtending(!cm.getExtending()); cm.on("change", function() { cm.setExtending(false); }); } function clearMark(cm) { cm.setExtending(false); cm.setCursor(cm.getCursor()); } function getInput(cm, msg, f) { if (cm.openDialog) cm.openDialog(msg + ": ", f, {bottom: true}); else f(prompt(msg, "")); } function operateOnWord(cm, op) { var start = cm.getCursor(), end = cm.findPosH(start, 1, "word"); cm.replaceRange(op(cm.getRange(start, end)), start, end); cm.setCursor(end); } function toEnclosingExpr(cm) { var pos = cm.getCursor(), line = pos.line, ch = pos.ch; var stack = []; while (line >= cm.firstLine()) { var text = cm.getLine(line); for (var i = ch == null ? text.length : ch; i > 0;) { var ch = text.charAt(--i); if (ch == ")") stack.push("("); else if (ch == "]") stack.push("["); else if (ch == "}") stack.push("{"); else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch)) return cm.extendSelection(Pos(line, i)); } --line; ch = null; } } function quit(cm) { cm.execCommand("clearSearch"); clearMark(cm); } CodeMirror.emacs = {kill: kill, killRegion: killRegion, repeated: repeated}; // Actual keymap var keyMap = CodeMirror.keyMap.emacs = CodeMirror.normalizeKeyMap({ "Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"), true);}, "Ctrl-K": repeated(function(cm) { var start = cm.getCursor(), end = cm.clipPos(Pos(start.line)); var text = cm.getRange(start, end); if (!/\S/.test(text)) { text += "\n"; end = Pos(start.line + 1, 0); } kill(cm, start, end, "grow", text); }), "Alt-W": function(cm) { addToRing(cm.getSelection()); clearMark(cm); }, "Ctrl-Y": function(cm) { var start = cm.getCursor(); cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste"); cm.setSelection(start, cm.getCursor()); }, "Alt-Y": function(cm) {cm.replaceSelection(popFromRing(), "around", "paste");}, "Ctrl-Space": setMark, "Ctrl-Shift-2": setMark, "Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1), "Right": move(byChar, 1), "Left": move(byChar, -1), "Ctrl-D": function(cm) { killTo(cm, byChar, 1, false); }, "Delete": function(cm) { killRegion(cm, false) || killTo(cm, byChar, 1, false); }, "Ctrl-H": function(cm) { killTo(cm, byChar, -1, false); }, "Backspace": function(cm) { killRegion(cm, false) || killTo(cm, byChar, -1, false); }, "Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1), "Alt-Right": move(byWord, 1), "Alt-Left": move(byWord, -1), "Alt-D": function(cm) { killTo(cm, byWord, 1, "grow"); }, "Alt-Backspace": function(cm) { killTo(cm, byWord, -1, "grow"); }, "Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1), "Down": move(byLine, 1), "Up": move(byLine, -1), "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "End": "goLineEnd", "Home": "goLineStart", "Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1), "PageUp": move(byPage, -1), "PageDown": move(byPage, 1), "Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1), "Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1), "Alt-K": function(cm) { killTo(cm, bySentence, 1, "grow"); }, "Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1, "grow"); }, "Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1, "grow"); }, "Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1, "grow"), "Shift-Ctrl-Alt-2": function(cm) { var cursor = cm.getCursor(); cm.setSelection(findEnd(cm, cursor, byExpr, 1), cursor); }, "Ctrl-Alt-T": function(cm) { var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1); var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1); cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) + cm.getRange(leftStart, leftEnd), leftStart, rightEnd); }, "Ctrl-Alt-U": repeated(toEnclosingExpr), "Alt-Space": function(cm) { var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line); while (from && /\s/.test(text.charAt(from - 1))) --from; while (to < text.length && /\s/.test(text.charAt(to))) ++to; cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to)); }, "Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }), "Ctrl-T": repeated(function(cm) { cm.execCommand("transposeChars"); }), "Alt-C": repeated(function(cm) { operateOnWord(cm, function(w) { var letter = w.search(/\w/); if (letter == -1) return w; return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase(); }); }), "Alt-U": repeated(function(cm) { operateOnWord(cm, function(w) { return w.toUpperCase(); }); }), "Alt-L": repeated(function(cm) { operateOnWord(cm, function(w) { return w.toLowerCase(); }); }), "Alt-;": "toggleComment", "Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"), "Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"), "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd", "Ctrl-S": "findPersistentNext", "Ctrl-R": "findPersistentPrev", "Ctrl-G": quit, "Shift-Alt-5": "replace", "Alt-/": "autocomplete", "Enter": "newlineAndIndent", "Ctrl-J": repeated(function(cm) { cm.replaceSelection("\n", "end"); }), "Tab": "indentAuto", "Alt-G G": function(cm) { var prefix = getPrefix(cm, true); if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1); getInput(cm, "Goto line", function(str) { var num; if (str && !isNaN(num = Number(str)) && num == (num|0) && num > 0) cm.setCursor(num - 1); }); }, "Ctrl-X Tab": function(cm) { cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit")); }, "Ctrl-X Ctrl-X": function(cm) { cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor")); }, "Ctrl-X Ctrl-S": "save", "Ctrl-X Ctrl-W": "save", "Ctrl-X S": "saveAll", "Ctrl-X F": "open", "Ctrl-X U": repeated("undo"), "Ctrl-X K": "close", "Ctrl-X Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), "grow"); }, "Ctrl-X H": "selectAll", "Ctrl-Q Tab": repeated("insertTab"), "Ctrl-U": addPrefixMap }); var prefixMap = {"Ctrl-G": clearPrefix}; function regPrefix(d) { prefixMap[d] = function(cm) { addPrefix(cm, d); }; keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); }; prefixPreservingKeys["Ctrl-" + d] = true; } for (var i = 0; i < 10; ++i) regPrefix(String(i)); regPrefix("-"); }); ================================================ FILE: third_party/CodeMirror/keymap/sublime.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // A rough approximation of Sublime Text's keybindings // Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets")); else if (typeof define == "function" && define.amd) // AMD define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var cmds = CodeMirror.commands; var Pos = CodeMirror.Pos; // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that. function findPosSubword(doc, start, dir) { if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1)); var line = doc.getLine(start.line); if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0)); var state = "start", type; for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) { var next = line.charAt(dir < 0 ? pos - 1 : pos); var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o"; if (cat == "w" && next.toUpperCase() == next) cat = "W"; if (state == "start") { if (cat != "o") { state = "in"; type = cat; } } else if (state == "in") { if (type != cat) { if (type == "w" && cat == "W" && dir < 0) pos--; if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; } break; } } } return Pos(start.line, pos); } function moveSubword(cm, dir) { cm.extendSelectionsBy(function(range) { if (cm.display.shift || cm.doc.extend || range.empty()) return findPosSubword(cm.doc, range.head, dir); else return dir < 0 ? range.from() : range.to(); }); } cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); }; cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); }; cmds.scrollLineUp = function(cm) { var info = cm.getScrollInfo(); if (!cm.somethingSelected()) { var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local"); if (cm.getCursor().line >= visibleBottomLine) cm.execCommand("goLineUp"); } cm.scrollTo(null, info.top - cm.defaultTextHeight()); }; cmds.scrollLineDown = function(cm) { var info = cm.getScrollInfo(); if (!cm.somethingSelected()) { var visibleTopLine = cm.lineAtHeight(info.top, "local")+1; if (cm.getCursor().line <= visibleTopLine) cm.execCommand("goLineDown"); } cm.scrollTo(null, info.top + cm.defaultTextHeight()); }; cmds.splitSelectionByLine = function(cm) { var ranges = cm.listSelections(), lineRanges = []; for (var i = 0; i < ranges.length; i++) { var from = ranges[i].from(), to = ranges[i].to(); for (var line = from.line; line <= to.line; ++line) if (!(to.line > from.line && line == to.line && to.ch == 0)) lineRanges.push({anchor: line == from.line ? from : Pos(line, 0), head: line == to.line ? to : Pos(line)}); } cm.setSelections(lineRanges, 0); }; cmds.singleSelectionTop = function(cm) { var range = cm.listSelections()[0]; cm.setSelection(range.anchor, range.head, {scroll: false}); }; cmds.selectLine = function(cm) { var ranges = cm.listSelections(), extended = []; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; extended.push({anchor: Pos(range.from().line, 0), head: Pos(range.to().line + 1, 0)}); } cm.setSelections(extended); }; function insertLine(cm, above) { if (cm.isReadOnly()) return CodeMirror.Pass cm.operation(function() { var len = cm.listSelections().length, newSelection = [], last = -1; for (var i = 0; i < len; i++) { var head = cm.listSelections()[i].head; if (head.line <= last) continue; var at = Pos(head.line + (above ? 0 : 1), 0); cm.replaceRange("\n", at, null, "+insertLine"); cm.indentLine(at.line, null, true); newSelection.push({head: at, anchor: at}); last = head.line + 1; } cm.setSelections(newSelection); }); cm.execCommand("indentAuto"); } cmds.insertLineAfter = function(cm) { return insertLine(cm, false); }; cmds.insertLineBefore = function(cm) { return insertLine(cm, true); }; function wordAt(cm, pos) { var start = pos.ch, end = start, line = cm.getLine(pos.line); while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start; while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end; return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)}; } cmds.selectNextOccurrence = function(cm) { var from = cm.getCursor("from"), to = cm.getCursor("to"); var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel; if (CodeMirror.cmpPos(from, to) == 0) { var word = wordAt(cm, from); if (!word.word) return; cm.setSelection(word.from, word.to); fullWord = true; } else { var text = cm.getRange(from, to); var query = fullWord ? new RegExp("\\b" + text + "\\b") : text; var cur = cm.getSearchCursor(query, to); var found = cur.findNext(); if (!found) { cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0)); found = cur.findNext(); } if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return CodeMirror.Pass cm.addSelection(cur.from(), cur.to()); } if (fullWord) cm.state.sublimeFindFullWord = cm.doc.sel; }; function addCursorToSelection(cm, dir) { var ranges = cm.listSelections(), newRanges = []; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; var newAnchor = cm.findPosV( range.anchor, dir, "line", range.anchor.goalColumn); var newHead = cm.findPosV( range.head, dir, "line", range.head.goalColumn); newAnchor.goalColumn = range.anchor.goalColumn != null ? range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left; newHead.goalColumn = range.head.goalColumn != null ? range.head.goalColumn : cm.cursorCoords(range.head, "div").left; var newRange = {anchor: newAnchor, head: newHead}; newRanges.push(range); newRanges.push(newRange); } cm.setSelections(newRanges); } cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); }; cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); }; function isSelectedRange(ranges, from, to) { for (var i = 0; i < ranges.length; i++) if (ranges[i].from() == from && ranges[i].to() == to) return true return false } var mirror = "(){}[]"; function selectBetweenBrackets(cm) { var ranges = cm.listSelections(), newRanges = [] for (var i = 0; i < ranges.length; i++) { var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1); if (!opening) return false; for (;;) { var closing = cm.scanForBracket(pos, 1); if (!closing) return false; if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) { var startPos = Pos(opening.pos.line, opening.pos.ch + 1); if (CodeMirror.cmpPos(startPos, range.from()) == 0 && CodeMirror.cmpPos(closing.pos, range.to()) == 0) { opening = cm.scanForBracket(opening.pos, -1); if (!opening) return false; } else { newRanges.push({anchor: startPos, head: closing.pos}); break; } } pos = Pos(closing.pos.line, closing.pos.ch + 1); } } cm.setSelections(newRanges); return true; } cmds.selectScope = function(cm) { selectBetweenBrackets(cm) || cm.execCommand("selectAll"); }; cmds.selectBetweenBrackets = function(cm) { if (!selectBetweenBrackets(cm)) return CodeMirror.Pass; }; cmds.goToBracket = function(cm) { cm.extendSelectionsBy(function(range) { var next = cm.scanForBracket(range.head, 1); if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos; var prev = cm.scanForBracket(range.head, -1); return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head; }); }; cmds.swapLineUp = function(cm) { if (cm.isReadOnly()) return CodeMirror.Pass var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = []; for (var i = 0; i < ranges.length; i++) { var range = ranges[i], from = range.from().line - 1, to = range.to().line; newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch), head: Pos(range.head.line - 1, range.head.ch)}); if (range.to().ch == 0 && !range.empty()) --to; if (from > at) linesToMove.push(from, to); else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; at = to; } cm.operation(function() { for (var i = 0; i < linesToMove.length; i += 2) { var from = linesToMove[i], to = linesToMove[i + 1]; var line = cm.getLine(from); cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); if (to > cm.lastLine()) cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine"); else cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); } cm.setSelections(newSels); cm.scrollIntoView(); }); }; cmds.swapLineDown = function(cm) { if (cm.isReadOnly()) return CodeMirror.Pass var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1; for (var i = ranges.length - 1; i >= 0; i--) { var range = ranges[i], from = range.to().line + 1, to = range.from().line; if (range.to().ch == 0 && !range.empty()) from--; if (from < at) linesToMove.push(from, to); else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to; at = to; } cm.operation(function() { for (var i = linesToMove.length - 2; i >= 0; i -= 2) { var from = linesToMove[i], to = linesToMove[i + 1]; var line = cm.getLine(from); if (from == cm.lastLine()) cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine"); else cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine"); cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine"); } cm.scrollIntoView(); }); }; cmds.toggleCommentIndented = function(cm) { cm.toggleComment({ indent: true }); } cmds.joinLines = function(cm) { var ranges = cm.listSelections(), joined = []; for (var i = 0; i < ranges.length; i++) { var range = ranges[i], from = range.from(); var start = from.line, end = range.to().line; while (i < ranges.length - 1 && ranges[i + 1].from().line == end) end = ranges[++i].to().line; joined.push({start: start, end: end, anchor: !range.empty() && from}); } cm.operation(function() { var offset = 0, ranges = []; for (var i = 0; i < joined.length; i++) { var obj = joined[i]; var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head; for (var line = obj.start; line <= obj.end; line++) { var actual = line - offset; if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1); if (actual < cm.lastLine()) { cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length)); ++offset; } } ranges.push({anchor: anchor || head, head: head}); } cm.setSelections(ranges, 0); }); }; cmds.duplicateLine = function(cm) { cm.operation(function() { var rangeCount = cm.listSelections().length; for (var i = 0; i < rangeCount; i++) { var range = cm.listSelections()[i]; if (range.empty()) cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0)); else cm.replaceRange(cm.getRange(range.from(), range.to()), range.from()); } cm.scrollIntoView(); }); }; function sortLines(cm, caseSensitive) { if (cm.isReadOnly()) return CodeMirror.Pass var ranges = cm.listSelections(), toSort = [], selected; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (range.empty()) continue; var from = range.from().line, to = range.to().line; while (i < ranges.length - 1 && ranges[i + 1].from().line == to) to = ranges[++i].to().line; if (!ranges[i].to().ch) to--; toSort.push(from, to); } if (toSort.length) selected = true; else toSort.push(cm.firstLine(), cm.lastLine()); cm.operation(function() { var ranges = []; for (var i = 0; i < toSort.length; i += 2) { var from = toSort[i], to = toSort[i + 1]; var start = Pos(from, 0), end = Pos(to); var lines = cm.getRange(start, end, false); if (caseSensitive) lines.sort(); else lines.sort(function(a, b) { var au = a.toUpperCase(), bu = b.toUpperCase(); if (au != bu) { a = au; b = bu; } return a < b ? -1 : a == b ? 0 : 1; }); cm.replaceRange(lines, start, end); if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)}); } if (selected) cm.setSelections(ranges, 0); }); } cmds.sortLines = function(cm) { sortLines(cm, true); }; cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); }; cmds.nextBookmark = function(cm) { var marks = cm.state.sublimeBookmarks; if (marks) while (marks.length) { var current = marks.shift(); var found = current.find(); if (found) { marks.push(current); return cm.setSelection(found.from, found.to); } } }; cmds.prevBookmark = function(cm) { var marks = cm.state.sublimeBookmarks; if (marks) while (marks.length) { marks.unshift(marks.pop()); var found = marks[marks.length - 1].find(); if (!found) marks.pop(); else return cm.setSelection(found.from, found.to); } }; cmds.toggleBookmark = function(cm) { var ranges = cm.listSelections(); var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []); for (var i = 0; i < ranges.length; i++) { var from = ranges[i].from(), to = ranges[i].to(); var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to); for (var j = 0; j < found.length; j++) { if (found[j].sublimeBookmark) { found[j].clear(); for (var k = 0; k < marks.length; k++) if (marks[k] == found[j]) marks.splice(k--, 1); break; } } if (j == found.length) marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false})); } }; cmds.clearBookmarks = function(cm) { var marks = cm.state.sublimeBookmarks; if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear(); marks.length = 0; }; cmds.selectBookmarks = function(cm) { var marks = cm.state.sublimeBookmarks, ranges = []; if (marks) for (var i = 0; i < marks.length; i++) { var found = marks[i].find(); if (!found) marks.splice(i--, 0); else ranges.push({anchor: found.from, head: found.to}); } if (ranges.length) cm.setSelections(ranges, 0); }; function modifyWordOrSelection(cm, mod) { cm.operation(function() { var ranges = cm.listSelections(), indices = [], replacements = []; for (var i = 0; i < ranges.length; i++) { var range = ranges[i]; if (range.empty()) { indices.push(i); replacements.push(""); } else replacements.push(mod(cm.getRange(range.from(), range.to()))); } cm.replaceSelections(replacements, "around", "case"); for (var i = indices.length - 1, at; i >= 0; i--) { var range = ranges[indices[i]]; if (at && CodeMirror.cmpPos(range.head, at) > 0) continue; var word = wordAt(cm, range.head); at = word.from; cm.replaceRange(mod(word.word), word.from, word.to); } }); } cmds.smartBackspace = function(cm) { if (cm.somethingSelected()) return CodeMirror.Pass; cm.operation(function() { var cursors = cm.listSelections(); var indentUnit = cm.getOption("indentUnit"); for (var i = cursors.length - 1; i >= 0; i--) { var cursor = cursors[i].head; var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor); var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize")); // Delete by one character by default var deletePos = cm.findPosH(cursor, -1, "char", false); if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) { var prevIndent = new Pos(cursor.line, CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit)); // Smart delete only if we found a valid prevIndent location if (prevIndent.ch != cursor.ch) deletePos = prevIndent; } cm.replaceRange("", deletePos, cursor, "+delete"); } }); }; cmds.delLineRight = function(cm) { cm.operation(function() { var ranges = cm.listSelections(); for (var i = ranges.length - 1; i >= 0; i--) cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete"); cm.scrollIntoView(); }); }; cmds.upcaseAtCursor = function(cm) { modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); }); }; cmds.downcaseAtCursor = function(cm) { modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); }); }; cmds.setSublimeMark = function(cm) { if (cm.state.sublimeMark) cm.state.sublimeMark.clear(); cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); }; cmds.selectToSublimeMark = function(cm) { var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); if (found) cm.setSelection(cm.getCursor(), found); }; cmds.deleteToSublimeMark = function(cm) { var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); if (found) { var from = cm.getCursor(), to = found; if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; } cm.state.sublimeKilled = cm.getRange(from, to); cm.replaceRange("", from, to); } }; cmds.swapWithSublimeMark = function(cm) { var found = cm.state.sublimeMark && cm.state.sublimeMark.find(); if (found) { cm.state.sublimeMark.clear(); cm.state.sublimeMark = cm.setBookmark(cm.getCursor()); cm.setCursor(found); } }; cmds.sublimeYank = function(cm) { if (cm.state.sublimeKilled != null) cm.replaceSelection(cm.state.sublimeKilled, null, "paste"); }; cmds.showInCenter = function(cm) { var pos = cm.cursorCoords(null, "local"); cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2); }; function getTarget(cm) { var from = cm.getCursor("from"), to = cm.getCursor("to"); if (CodeMirror.cmpPos(from, to) == 0) { var word = wordAt(cm, from); if (!word.word) return; from = word.from; to = word.to; } return {from: from, to: to, query: cm.getRange(from, to), word: word}; } function findAndGoTo(cm, forward) { var target = getTarget(cm); if (!target) return; var query = target.query; var cur = cm.getSearchCursor(query, forward ? target.to : target.from); if (forward ? cur.findNext() : cur.findPrevious()) { cm.setSelection(cur.from(), cur.to()); } else { cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0) : cm.clipPos(Pos(cm.lastLine()))); if (forward ? cur.findNext() : cur.findPrevious()) cm.setSelection(cur.from(), cur.to()); else if (target.word) cm.setSelection(target.from, target.to); } }; cmds.findUnder = function(cm) { findAndGoTo(cm, true); }; cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); }; cmds.findAllUnder = function(cm) { var target = getTarget(cm); if (!target) return; var cur = cm.getSearchCursor(target.query); var matches = []; var primaryIndex = -1; while (cur.findNext()) { matches.push({anchor: cur.from(), head: cur.to()}); if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch) primaryIndex++; } cm.setSelections(matches, primaryIndex); }; var keyMap = CodeMirror.keyMap; keyMap.macSublime = { "Cmd-Left": "goLineStartSmart", "Shift-Tab": "indentLess", "Shift-Ctrl-K": "deleteLine", "Alt-Q": "wrapLines", "Ctrl-Left": "goSubwordLeft", "Ctrl-Right": "goSubwordRight", "Ctrl-Alt-Up": "scrollLineUp", "Ctrl-Alt-Down": "scrollLineDown", "Cmd-L": "selectLine", "Shift-Cmd-L": "splitSelectionByLine", "Esc": "singleSelectionTop", "Cmd-Enter": "insertLineAfter", "Shift-Cmd-Enter": "insertLineBefore", "Cmd-D": "selectNextOccurrence", "Shift-Cmd-Space": "selectScope", "Shift-Cmd-M": "selectBetweenBrackets", "Cmd-M": "goToBracket", "Cmd-Ctrl-Up": "swapLineUp", "Cmd-Ctrl-Down": "swapLineDown", "Cmd-/": "toggleCommentIndented", "Cmd-J": "joinLines", "Shift-Cmd-D": "duplicateLine", "F9": "sortLines", "Cmd-F9": "sortLinesInsensitive", "F2": "nextBookmark", "Shift-F2": "prevBookmark", "Cmd-F2": "toggleBookmark", "Shift-Cmd-F2": "clearBookmarks", "Alt-F2": "selectBookmarks", "Backspace": "smartBackspace", "Cmd-K Cmd-K": "delLineRight", "Cmd-K Cmd-U": "upcaseAtCursor", "Cmd-K Cmd-L": "downcaseAtCursor", "Cmd-K Cmd-Space": "setSublimeMark", "Cmd-K Cmd-A": "selectToSublimeMark", "Cmd-K Cmd-W": "deleteToSublimeMark", "Cmd-K Cmd-X": "swapWithSublimeMark", "Cmd-K Cmd-Y": "sublimeYank", "Cmd-K Cmd-C": "showInCenter", "Cmd-K Cmd-G": "clearBookmarks", "Cmd-K Cmd-Backspace": "delLineLeft", "Cmd-K Cmd-0": "unfoldAll", "Cmd-K Cmd-J": "unfoldAll", "Ctrl-Shift-Up": "addCursorToPrevLine", "Ctrl-Shift-Down": "addCursorToNextLine", "Cmd-F3": "findUnder", "Shift-Cmd-F3": "findUnderPrevious", "Alt-F3": "findAllUnder", "Shift-Cmd-[": "fold", "Shift-Cmd-]": "unfold", "Cmd-I": "findIncremental", "Shift-Cmd-I": "findIncrementalReverse", "Cmd-H": "replace", "F3": "findNext", "Shift-F3": "findPrev", "fallthrough": "macDefault" }; CodeMirror.normalizeKeyMap(keyMap.macSublime); keyMap.pcSublime = { "Shift-Tab": "indentLess", "Shift-Ctrl-K": "deleteLine", "Alt-Q": "wrapLines", "Ctrl-T": "transposeChars", "Alt-Left": "goSubwordLeft", "Alt-Right": "goSubwordRight", "Ctrl-Up": "scrollLineUp", "Ctrl-Down": "scrollLineDown", "Ctrl-L": "selectLine", "Shift-Ctrl-L": "splitSelectionByLine", "Esc": "singleSelectionTop", "Ctrl-Enter": "insertLineAfter", "Shift-Ctrl-Enter": "insertLineBefore", "Ctrl-D": "selectNextOccurrence", "Shift-Ctrl-Space": "selectScope", "Shift-Ctrl-M": "selectBetweenBrackets", "Ctrl-M": "goToBracket", "Shift-Ctrl-Up": "swapLineUp", "Shift-Ctrl-Down": "swapLineDown", "Ctrl-/": "toggleCommentIndented", "Ctrl-J": "joinLines", "Shift-Ctrl-D": "duplicateLine", "F9": "sortLines", "Ctrl-F9": "sortLinesInsensitive", "F2": "nextBookmark", "Shift-F2": "prevBookmark", "Ctrl-F2": "toggleBookmark", "Shift-Ctrl-F2": "clearBookmarks", "Alt-F2": "selectBookmarks", "Backspace": "smartBackspace", "Ctrl-K Ctrl-K": "delLineRight", "Ctrl-K Ctrl-U": "upcaseAtCursor", "Ctrl-K Ctrl-L": "downcaseAtCursor", "Ctrl-K Ctrl-Space": "setSublimeMark", "Ctrl-K Ctrl-A": "selectToSublimeMark", "Ctrl-K Ctrl-W": "deleteToSublimeMark", "Ctrl-K Ctrl-X": "swapWithSublimeMark", "Ctrl-K Ctrl-Y": "sublimeYank", "Ctrl-K Ctrl-C": "showInCenter", "Ctrl-K Ctrl-G": "clearBookmarks", "Ctrl-K Ctrl-Backspace": "delLineLeft", "Ctrl-K Ctrl-0": "unfoldAll", "Ctrl-K Ctrl-J": "unfoldAll", "Ctrl-Alt-Up": "addCursorToPrevLine", "Ctrl-Alt-Down": "addCursorToNextLine", "Ctrl-F3": "findUnder", "Shift-Ctrl-F3": "findUnderPrevious", "Alt-F3": "findAllUnder", "Shift-Ctrl-[": "fold", "Shift-Ctrl-]": "unfold", "Ctrl-I": "findIncremental", "Shift-Ctrl-I": "findIncrementalReverse", "Ctrl-H": "replace", "F3": "findNext", "Shift-F3": "findPrev", "fallthrough": "pcDefault" }; CodeMirror.normalizeKeyMap(keyMap.pcSublime); var mac = keyMap.default == keyMap.macDefault; keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime; }); ================================================ FILE: third_party/CodeMirror/keymap/vim.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /** * Supported keybindings: * Too many to list. Refer to defaultKeymap below. * * Supported Ex commands: * Refer to defaultExCommandMap below. * * Registers: unnamed, -, a-z, A-Z, 0-9 * (Does not respect the special case for number registers when delete * operator is made with these commands: %, (, ), , /, ?, n, N, {, } ) * TODO: Implement the remaining registers. * * Marks: a-z, A-Z, and 0-9 * TODO: Implement the remaining special marks. They have more complex * behavior. * * Events: * 'vim-mode-change' - raised on the editor anytime the current mode changes, * Event object: {mode: "visual", subMode: "linewise"} * * Code structure: * 1. Default keymap * 2. Variable declarations and short basic helpers * 3. Instance (External API) implementation * 4. Internal state tracking objects (input state, counter) implementation * and instantiation * 5. Key handler (the main command dispatcher) implementation * 6. Motion, operator, and action implementations * 7. Helper functions for the key handler, motions, operators, and actions * 8. Set up Vim to work as a keymap for CodeMirror. * 9. Ex command implementations. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js")); else if (typeof define == "function" && define.amd) // AMD define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { 'use strict'; var defaultKeymap = [ // Key to key mapping. This goes first to make it possible to override // existing mappings. { keys: '', type: 'keyToKey', toKeys: 'h' }, { keys: '', type: 'keyToKey', toKeys: 'l' }, { keys: '', type: 'keyToKey', toKeys: 'k' }, { keys: '', type: 'keyToKey', toKeys: 'j' }, { keys: '', type: 'keyToKey', toKeys: 'l' }, { keys: '', type: 'keyToKey', toKeys: 'h', context: 'normal'}, { keys: '', type: 'keyToKey', toKeys: 'W' }, { keys: '', type: 'keyToKey', toKeys: 'B', context: 'normal' }, { keys: '', type: 'keyToKey', toKeys: 'w' }, { keys: '', type: 'keyToKey', toKeys: 'b', context: 'normal' }, { keys: '', type: 'keyToKey', toKeys: 'j' }, { keys: '', type: 'keyToKey', toKeys: 'k' }, { keys: '', type: 'keyToKey', toKeys: '' }, { keys: '', type: 'keyToKey', toKeys: '' }, { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, { keys: '', type: 'keyToKey', toKeys: '', context: 'insert' }, { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' }, { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'}, { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' }, { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' }, { keys: '', type: 'keyToKey', toKeys: '0' }, { keys: '', type: 'keyToKey', toKeys: '$' }, { keys: '', type: 'keyToKey', toKeys: '' }, { keys: '', type: 'keyToKey', toKeys: '' }, { keys: '', type: 'keyToKey', toKeys: 'j^', context: 'normal' }, { keys: '', type: 'action', action: 'toggleOverwrite', context: 'insert' }, // Motions { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }}, { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }}, { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }}, { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }}, { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }}, { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }}, { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }}, { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }}, { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }}, { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }}, { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }}, { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }}, { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }}, { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }}, { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }}, { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }}, { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }}, { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }}, { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }}, { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }}, { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }}, { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }}, { keys: '', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }}, { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }}, { keys: '', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }}, { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }}, { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }}, { keys: '0', type: 'motion', motion: 'moveToStartOfLine' }, { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' }, { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }}, { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }}, { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }}, { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }}, { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }}, { keys: 'f', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }}, { keys: 'F', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }}, { keys: 't', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }}, { keys: 'T', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }}, { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }}, { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }}, { keys: '\'', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}}, { keys: '`', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}}, { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } }, { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } }, { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } }, { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } }, // the next two aren't motions but must come before more general motion declarations { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}}, { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}}, { keys: ']', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}}, { keys: '[', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}}, { keys: '|', type: 'motion', motion: 'moveToColumn'}, { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'}, { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'}, // Operators { keys: 'd', type: 'operator', operator: 'delete' }, { keys: 'y', type: 'operator', operator: 'yank' }, { keys: 'c', type: 'operator', operator: 'change' }, { keys: '=', type: 'operator', operator: 'indentAuto' }, { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }}, { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }}, { keys: 'g~', type: 'operator', operator: 'changeCase' }, { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true }, { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true }, { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }}, { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }}, // Operator-Motion dual commands { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }}, { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }}, { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'}, { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'}, { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'}, { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'}, { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'}, { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'}, { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'}, { keys: '', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' }, //ignore C-w in normal mode { keys: '', type: 'idle', context: 'normal' }, // Actions { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }}, { keys: '', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }}, { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }}, { keys: '', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }}, { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' }, { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' }, { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' }, { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' }, { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' }, { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' }, { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' }, { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' }, { keys: 'v', type: 'action', action: 'toggleVisualMode' }, { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }}, { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, { keys: '', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }}, { keys: 'gv', type: 'action', action: 'reselectLastSelection' }, { keys: 'J', type: 'action', action: 'joinLines', isEdit: true }, { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }}, { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }}, { keys: 'r', type: 'action', action: 'replace', isEdit: true }, { keys: '@', type: 'action', action: 'replayMacro' }, { keys: 'q', type: 'action', action: 'enterMacroRecordMode' }, // Handle Replace-mode as a special case of insert mode. { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }}, { keys: 'u', type: 'action', action: 'undo', context: 'normal' }, { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true }, { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true }, { keys: '', type: 'action', action: 'redo' }, { keys: 'm', type: 'action', action: 'setMark' }, { keys: '"', type: 'action', action: 'setRegister' }, { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }}, { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }}, { keys: 'z', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }}, { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' }, { keys: '.', type: 'action', action: 'repeatLastEdit' }, { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}}, { keys: '', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}}, { keys: '', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' }, { keys: '', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' }, // Text object motions { keys: 'a', type: 'motion', motion: 'textObjectManipulation' }, { keys: 'i', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }}, // Search { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }}, { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }}, { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }}, { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }}, { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }}, // Ex command { keys: ':', type: 'ex' } ]; var defaultKeymapLength = defaultKeymap.length; /** * Ex commands * Care must be taken when adding to the default Ex command map. For any * pair of commands that have a shared prefix, at least one of their * shortNames must not match the prefix of the other command. */ var defaultExCommandMap = [ { name: 'colorscheme', shortName: 'colo' }, { name: 'map' }, { name: 'imap', shortName: 'im' }, { name: 'nmap', shortName: 'nm' }, { name: 'vmap', shortName: 'vm' }, { name: 'unmap' }, { name: 'write', shortName: 'w' }, { name: 'undo', shortName: 'u' }, { name: 'redo', shortName: 'red' }, { name: 'set', shortName: 'se' }, { name: 'set', shortName: 'se' }, { name: 'setlocal', shortName: 'setl' }, { name: 'setglobal', shortName: 'setg' }, { name: 'sort', shortName: 'sor' }, { name: 'substitute', shortName: 's', possiblyAsync: true }, { name: 'nohlsearch', shortName: 'noh' }, { name: 'yank', shortName: 'y' }, { name: 'delmarks', shortName: 'delm' }, { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true }, { name: 'global', shortName: 'g' } ]; var Pos = CodeMirror.Pos; var Vim = function() { function enterVimMode(cm) { cm.setOption('disableInput', true); cm.setOption('showCursorWhenSelecting', false); CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); cm.on('cursorActivity', onCursorActivity); maybeInitVimState(cm); CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm)); } function leaveVimMode(cm) { cm.setOption('disableInput', false); cm.off('cursorActivity', onCursorActivity); CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm)); cm.state.vim = null; } function detachVimMap(cm, next) { if (this == CodeMirror.keyMap.vim) { CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor"); if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) { disableFatCursorMark(cm); cm.getInputField().style.caretColor = ""; } } if (!next || next.attach != attachVimMap) leaveVimMode(cm); } function attachVimMap(cm, prev) { if (this == CodeMirror.keyMap.vim) { CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor"); if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) { enableFatCursorMark(cm); cm.getInputField().style.caretColor = "transparent"; } } if (!prev || prev.attach != attachVimMap) enterVimMode(cm); } function fatCursorMarks(cm) { var ranges = cm.listSelections(), result = [] for (var i = 0; i < ranges.length; i++) { var range = ranges[i] if (range.empty()) { if (range.anchor.ch < cm.getLine(range.anchor.line).length) { result.push(cm.markText(range.anchor, Pos(range.anchor.line, range.anchor.ch + 1), {className: "cm-fat-cursor-mark"})) } else { var widget = document.createElement("span") widget.textContent = "\u00a0" widget.className = "cm-fat-cursor-mark" result.push(cm.setBookmark(range.anchor, {widget: widget})) } } } return result } function updateFatCursorMark(cm) { var marks = cm.state.fatCursorMarks if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear() cm.state.fatCursorMarks = fatCursorMarks(cm) } function enableFatCursorMark(cm) { cm.state.fatCursorMarks = fatCursorMarks(cm) cm.on("cursorActivity", updateFatCursorMark) } function disableFatCursorMark(cm) { var marks = cm.state.fatCursorMarks if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear() cm.state.fatCursorMarks = null cm.off("cursorActivity", updateFatCursorMark) } // Deprecated, simply setting the keymap works again. CodeMirror.defineOption('vimMode', false, function(cm, val, prev) { if (val && cm.getOption("keyMap") != "vim") cm.setOption("keyMap", "vim"); else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap"))) cm.setOption("keyMap", "default"); }); function cmKey(key, cm) { if (!cm) { return undefined; } if (this[key]) { return this[key]; } var vimKey = cmKeyToVimKey(key); if (!vimKey) { return false; } var cmd = CodeMirror.Vim.findKey(cm, vimKey); if (typeof cmd == 'function') { CodeMirror.signal(cm, 'vim-keypress', vimKey); } return cmd; } var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'}; var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'}; function cmKeyToVimKey(key) { if (key.charAt(0) == '\'') { // Keypress character binding of format "'a'" return key.charAt(1); } var pieces = key.split(/-(?!$)/); var lastPiece = pieces[pieces.length - 1]; if (pieces.length == 1 && pieces[0].length == 1) { // No-modifier bindings use literal character bindings above. Skip. return false; } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) { // Ignore Shift+char bindings as they should be handled by literal character. return false; } var hasCharacter = false; for (var i = 0; i < pieces.length; i++) { var piece = pieces[i]; if (piece in modifiers) { pieces[i] = modifiers[piece]; } else { hasCharacter = true; } if (piece in specialKeys) { pieces[i] = specialKeys[piece]; } } if (!hasCharacter) { // Vim does not support modifier only keys. return false; } // TODO: Current bindings expect the character to be lower case, but // it looks like vim key notation uses upper case. if (isUpperCase(lastPiece)) { pieces[pieces.length - 1] = lastPiece.toLowerCase(); } return '<' + pieces.join('-') + '>'; } function getOnPasteFn(cm) { var vim = cm.state.vim; if (!vim.onPasteFn) { vim.onPasteFn = function() { if (!vim.insertMode) { cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); actions.enterInsertMode(cm, {}, vim); } }; } return vim.onPasteFn; } var numberRegex = /[\d]/; var wordCharTest = [CodeMirror.isWordChar, function(ch) { return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch); }], bigWordCharTest = [function(ch) { return /\S/.test(ch); }]; function makeKeyRange(start, size) { var keys = []; for (var i = start; i < start + size; i++) { keys.push(String.fromCharCode(i)); } return keys; } var upperCaseAlphabet = makeKeyRange(65, 26); var lowerCaseAlphabet = makeKeyRange(97, 26); var numbers = makeKeyRange(48, 10); var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']); var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']); function isLine(cm, line) { return line >= cm.firstLine() && line <= cm.lastLine(); } function isLowerCase(k) { return (/^[a-z]$/).test(k); } function isMatchableSymbol(k) { return '()[]{}'.indexOf(k) != -1; } function isNumber(k) { return numberRegex.test(k); } function isUpperCase(k) { return (/^[A-Z]$/).test(k); } function isWhiteSpaceString(k) { return (/^\s*$/).test(k); } function isEndOfSentenceSymbol(k) { return '.?!'.indexOf(k) != -1; } function inArray(val, arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == val) { return true; } } return false; } var options = {}; function defineOption(name, defaultValue, type, aliases, callback) { if (defaultValue === undefined && !callback) { throw Error('defaultValue is required unless callback is provided'); } if (!type) { type = 'string'; } options[name] = { type: type, defaultValue: defaultValue, callback: callback }; if (aliases) { for (var i = 0; i < aliases.length; i++) { options[aliases[i]] = options[name]; } } if (defaultValue) { setOption(name, defaultValue); } } function setOption(name, value, cm, cfg) { var option = options[name]; cfg = cfg || {}; var scope = cfg.scope; if (!option) { return new Error('Unknown option: ' + name); } if (option.type == 'boolean') { if (value && value !== true) { return new Error('Invalid argument: ' + name + '=' + value); } else if (value !== false) { // Boolean options are set to true if value is not defined. value = true; } } if (option.callback) { if (scope !== 'local') { option.callback(value, undefined); } if (scope !== 'global' && cm) { option.callback(value, cm); } } else { if (scope !== 'local') { option.value = option.type == 'boolean' ? !!value : value; } if (scope !== 'global' && cm) { cm.state.vim.options[name] = {value: value}; } } } function getOption(name, cm, cfg) { var option = options[name]; cfg = cfg || {}; var scope = cfg.scope; if (!option) { return new Error('Unknown option: ' + name); } if (option.callback) { var local = cm && option.callback(undefined, cm); if (scope !== 'global' && local !== undefined) { return local; } if (scope !== 'local') { return option.callback(); } return; } else { var local = (scope !== 'global') && (cm && cm.state.vim.options[name]); return (local || (scope !== 'local') && option || {}).value; } } defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) { // Option is local. Do nothing for global. if (cm === undefined) { return; } // The 'filetype' option proxies to the CodeMirror 'mode' option. if (name === undefined) { var mode = cm.getOption('mode'); return mode == 'null' ? '' : mode; } else { var mode = name == '' ? 'null' : name; cm.setOption('mode', mode); } }); var createCircularJumpList = function() { var size = 100; var pointer = -1; var head = 0; var tail = 0; var buffer = new Array(size); function add(cm, oldCur, newCur) { var current = pointer % size; var curMark = buffer[current]; function useNextSlot(cursor) { var next = ++pointer % size; var trashMark = buffer[next]; if (trashMark) { trashMark.clear(); } buffer[next] = cm.setBookmark(cursor); } if (curMark) { var markPos = curMark.find(); // avoid recording redundant cursor position if (markPos && !cursorEqual(markPos, oldCur)) { useNextSlot(oldCur); } } else { useNextSlot(oldCur); } useNextSlot(newCur); head = pointer; tail = pointer - size + 1; if (tail < 0) { tail = 0; } } function move(cm, offset) { pointer += offset; if (pointer > head) { pointer = head; } else if (pointer < tail) { pointer = tail; } var mark = buffer[(size + pointer) % size]; // skip marks that are temporarily removed from text buffer if (mark && !mark.find()) { var inc = offset > 0 ? 1 : -1; var newCur; var oldCur = cm.getCursor(); do { pointer += inc; mark = buffer[(size + pointer) % size]; // skip marks that are the same as current position if (mark && (newCur = mark.find()) && !cursorEqual(oldCur, newCur)) { break; } } while (pointer < head && pointer > tail); } return mark; } return { cachedCursor: undefined, //used for # and * jumps add: add, move: move }; }; // Returns an object to track the changes associated insert mode. It // clones the object that is passed in, or creates an empty object one if // none is provided. var createInsertModeChanges = function(c) { if (c) { // Copy construction return { changes: c.changes, expectCursorActivityForChange: c.expectCursorActivityForChange }; } return { // Change list changes: [], // Set to true on change, false on cursorActivity. expectCursorActivityForChange: false }; }; function MacroModeState() { this.latestRegister = undefined; this.isPlaying = false; this.isRecording = false; this.replaySearchQueries = []; this.onRecordingDone = undefined; this.lastInsertModeChanges = createInsertModeChanges(); } MacroModeState.prototype = { exitMacroRecordMode: function() { var macroModeState = vimGlobalState.macroModeState; if (macroModeState.onRecordingDone) { macroModeState.onRecordingDone(); // close dialog } macroModeState.onRecordingDone = undefined; macroModeState.isRecording = false; }, enterMacroRecordMode: function(cm, registerName) { var register = vimGlobalState.registerController.getRegister(registerName); if (register) { register.clear(); this.latestRegister = registerName; if (cm.openDialog) { this.onRecordingDone = cm.openDialog( '(recording)['+registerName+']', null, {bottom:true}); } this.isRecording = true; } } }; function maybeInitVimState(cm) { if (!cm.state.vim) { // Store instance state in the CodeMirror object. cm.state.vim = { inputState: new InputState(), // Vim's input state that triggered the last edit, used to repeat // motions and operators with '.'. lastEditInputState: undefined, // Vim's action command before the last edit, used to repeat actions // with '.' and insert mode repeat. lastEditActionCommand: undefined, // When using jk for navigation, if you move from a longer line to a // shorter line, the cursor may clip to the end of the shorter line. // If j is pressed again and cursor goes to the next line, the // cursor should go back to its horizontal position on the longer // line if it can. This is to keep track of the horizontal position. lastHPos: -1, // Doing the same with screen-position for gj/gk lastHSPos: -1, // The last motion command run. Cleared if a non-motion command gets // executed in between. lastMotion: null, marks: {}, // Mark for rendering fake cursor for visual mode. fakeCursor: null, insertMode: false, // Repeat count for changes made in insert mode, triggered by key // sequences like 3,i. Only exists when insertMode is true. insertModeRepeat: undefined, visualMode: false, // If we are in visual line mode. No effect if visualMode is false. visualLine: false, visualBlock: false, lastSelection: null, lastPastedText: null, sel: {}, // Buffer-local/window-local values of vim options. options: {} }; } return cm.state.vim; } var vimGlobalState; function resetVimGlobalState() { vimGlobalState = { // The current search query. searchQuery: null, // Whether we are searching backwards. searchIsReversed: false, // Replace part of the last substituted pattern lastSubstituteReplacePart: undefined, jumpList: createCircularJumpList(), macroModeState: new MacroModeState, // Recording latest f, t, F or T motion command. lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''}, registerController: new RegisterController({}), // search history buffer searchHistoryController: new HistoryController(), // ex Command history buffer exCommandHistoryController : new HistoryController() }; for (var optionName in options) { var option = options[optionName]; option.value = option.defaultValue; } } var lastInsertModeKeyTimer; var vimApi= { buildKeyMap: function() { // TODO: Convert keymap into dictionary format for fast lookup. }, // Testing hook, though it might be useful to expose the register // controller anyways. getRegisterController: function() { return vimGlobalState.registerController; }, // Testing hook. resetVimGlobalState_: resetVimGlobalState, // Testing hook. getVimGlobalState_: function() { return vimGlobalState; }, // Testing hook. maybeInitVimState_: maybeInitVimState, suppressErrorLogging: false, InsertModeKey: InsertModeKey, map: function(lhs, rhs, ctx) { // Add user defined key bindings. exCommandDispatcher.map(lhs, rhs, ctx); }, unmap: function(lhs, ctx) { exCommandDispatcher.unmap(lhs, ctx); }, // Non-recursive map function. // NOTE: This will not create mappings to key maps that aren't present // in the default key map. See TODO at bottom of function. noremap: function(lhs, rhs, ctx) { function toCtxArray(ctx) { return ctx ? [ctx] : ['normal', 'insert', 'visual']; } var ctxsToMap = toCtxArray(ctx); // Look through all actual defaults to find a map candidate. var actualLength = defaultKeymap.length, origLength = defaultKeymapLength; for (var i = actualLength - origLength; i < actualLength && ctxsToMap.length; i++) { var mapping = defaultKeymap[i]; // Omit mappings that operate in the wrong context(s) and those of invalid type. if (mapping.keys == rhs && (!ctx || !mapping.context || mapping.context === ctx) && mapping.type.substr(0, 2) !== 'ex' && mapping.type.substr(0, 3) !== 'key') { // Make a shallow copy of the original keymap entry. var newMapping = {}; for (var key in mapping) { newMapping[key] = mapping[key]; } // Modify it point to the new mapping with the proper context. newMapping.keys = lhs; if (ctx && !newMapping.context) { newMapping.context = ctx; } // Add it to the keymap with a higher priority than the original. this._mapCommand(newMapping); // Record the mapped contexts as complete. var mappedCtxs = toCtxArray(mapping.context); ctxsToMap = ctxsToMap.filter(function(el) { return mappedCtxs.indexOf(el) === -1; }); } } // TODO: Create non-recursive keyToKey mappings for the unmapped contexts once those exist. }, // Remove all user-defined mappings for the provided context. mapclear: function(ctx) { // Partition the existing keymap into user-defined and true defaults. var actualLength = defaultKeymap.length, origLength = defaultKeymapLength; var userKeymap = defaultKeymap.slice(0, actualLength - origLength); defaultKeymap = defaultKeymap.slice(actualLength - origLength); if (ctx) { // If a specific context is being cleared, we need to keep mappings // from all other contexts. for (var i = userKeymap.length - 1; i >= 0; i--) { var mapping = userKeymap[i]; if (ctx !== mapping.context) { if (mapping.context) { this._mapCommand(mapping); } else { // `mapping` applies to all contexts so create keymap copies // for each context except the one being cleared. var contexts = ['normal', 'insert', 'visual']; for (var j in contexts) { if (contexts[j] !== ctx) { var newMapping = {}; for (var key in mapping) { newMapping[key] = mapping[key]; } newMapping.context = contexts[j]; this._mapCommand(newMapping); } } } } } } }, // TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace // them, or somehow make them work with the existing CodeMirror setOption/getOption API. setOption: setOption, getOption: getOption, defineOption: defineOption, defineEx: function(name, prefix, func){ if (!prefix) { prefix = name; } else if (name.indexOf(prefix) !== 0) { throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered'); } exCommands[name]=func; exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; }, handleKey: function (cm, key, origin) { var command = this.findKey(cm, key, origin); if (typeof command === 'function') { return command(); } }, /** * This is the outermost function called by CodeMirror, after keys have * been mapped to their Vim equivalents. * * Finds a command based on the key (and cached keys if there is a * multi-key sequence). Returns `undefined` if no key is matched, a noop * function if a partial match is found (multi-key), and a function to * execute the bound command if a a key is matched. The function always * returns true. */ findKey: function(cm, key, origin) { var vim = maybeInitVimState(cm); function handleMacroRecording() { var macroModeState = vimGlobalState.macroModeState; if (macroModeState.isRecording) { if (key == 'q') { macroModeState.exitMacroRecordMode(); clearInputState(cm); return true; } if (origin != 'mapping') { logKey(macroModeState, key); } } } function handleEsc() { if (key == '') { // Clear input state and get back to normal mode. clearInputState(cm); if (vim.visualMode) { exitVisualMode(cm); } else if (vim.insertMode) { exitInsertMode(cm); } return true; } } function doKeyToKey(keys) { // TODO: prevent infinite recursion. var match; while (keys) { // Pull off one command key, which is either a single character // or a special sequence wrapped in '<' and '>', e.g. ''. match = (/<\w+-.+?>|<\w+>|./).exec(keys); key = match[0]; keys = keys.substring(match.index + key.length); CodeMirror.Vim.handleKey(cm, key, 'mapping'); } } function handleKeyInsertMode() { if (handleEsc()) { return true; } var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; var keysAreChars = key.length == 1; var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); // Need to check all key substrings in insert mode. while (keys.length > 1 && match.type != 'full') { var keys = vim.inputState.keyBuffer = keys.slice(1); var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert'); if (thisMatch.type != 'none') { match = thisMatch; } } if (match.type == 'none') { clearInputState(cm); return false; } else if (match.type == 'partial') { if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } lastInsertModeKeyTimer = window.setTimeout( function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } }, getOption('insertModeEscKeysTimeout')); return !keysAreChars; } if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); } if (keysAreChars) { var selections = cm.listSelections(); for (var i = 0; i < selections.length; i++) { var here = selections[i].head; cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input'); } vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop(); } clearInputState(cm); return match.command; } function handleKeyNonInsertMode() { if (handleMacroRecording() || handleEsc()) { return true; } var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key; if (/^[1-9]\d*$/.test(keys)) { return true; } var keysMatcher = /^(\d*)(.*)$/.exec(keys); if (!keysMatcher) { clearInputState(cm); return false; } var context = vim.visualMode ? 'visual' : 'normal'; var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context); if (match.type == 'none') { clearInputState(cm); return false; } else if (match.type == 'partial') { return true; } vim.inputState.keyBuffer = ''; var keysMatcher = /^(\d*)(.*)$/.exec(keys); if (keysMatcher[1] && keysMatcher[1] != '0') { vim.inputState.pushRepeatDigit(keysMatcher[1]); } return match.command; } var command; if (vim.insertMode) { command = handleKeyInsertMode(); } else { command = handleKeyNonInsertMode(); } if (command === false) { return !vim.insertMode && key.length === 1 ? function() { return true; } : undefined; } else if (command === true) { // TODO: Look into using CodeMirror's multi-key handling. // Return no-op since we are caching the key. Counts as handled, but // don't want act on it just yet. return function() { return true; }; } else { return function() { return cm.operation(function() { cm.curOp.isVimOp = true; try { if (command.type == 'keyToKey') { doKeyToKey(command.toKeys); } else { commandDispatcher.processCommand(cm, vim, command); } } catch (e) { // clear VIM state in case it's in a bad state. cm.state.vim = undefined; maybeInitVimState(cm); if (!CodeMirror.Vim.suppressErrorLogging) { console['log'](e); } throw e; } return true; }); }; } }, handleEx: function(cm, input) { exCommandDispatcher.processCommand(cm, input); }, defineMotion: defineMotion, defineAction: defineAction, defineOperator: defineOperator, mapCommand: mapCommand, _mapCommand: _mapCommand, defineRegister: defineRegister, exitVisualMode: exitVisualMode, exitInsertMode: exitInsertMode }; // Represents the current input state. function InputState() { this.prefixRepeat = []; this.motionRepeat = []; this.operator = null; this.operatorArgs = null; this.motion = null; this.motionArgs = null; this.keyBuffer = []; // For matching multi-key commands. this.registerName = null; // Defaults to the unnamed register. } InputState.prototype.pushRepeatDigit = function(n) { if (!this.operator) { this.prefixRepeat = this.prefixRepeat.concat(n); } else { this.motionRepeat = this.motionRepeat.concat(n); } }; InputState.prototype.getRepeat = function() { var repeat = 0; if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) { repeat = 1; if (this.prefixRepeat.length > 0) { repeat *= parseInt(this.prefixRepeat.join(''), 10); } if (this.motionRepeat.length > 0) { repeat *= parseInt(this.motionRepeat.join(''), 10); } } return repeat; }; function clearInputState(cm, reason) { cm.state.vim.inputState = new InputState(); CodeMirror.signal(cm, 'vim-command-done', reason); } /* * Register stores information about copy and paste registers. Besides * text, a register must store whether it is linewise (i.e., when it is * pasted, should it insert itself into a new line, or should the text be * inserted at the cursor position.) */ function Register(text, linewise, blockwise) { this.clear(); this.keyBuffer = [text || '']; this.insertModeChanges = []; this.searchQueries = []; this.linewise = !!linewise; this.blockwise = !!blockwise; } Register.prototype = { setText: function(text, linewise, blockwise) { this.keyBuffer = [text || '']; this.linewise = !!linewise; this.blockwise = !!blockwise; }, pushText: function(text, linewise) { // if this register has ever been set to linewise, use linewise. if (linewise) { if (!this.linewise) { this.keyBuffer.push('\n'); } this.linewise = true; } this.keyBuffer.push(text); }, pushInsertModeChanges: function(changes) { this.insertModeChanges.push(createInsertModeChanges(changes)); }, pushSearchQuery: function(query) { this.searchQueries.push(query); }, clear: function() { this.keyBuffer = []; this.insertModeChanges = []; this.searchQueries = []; this.linewise = false; }, toString: function() { return this.keyBuffer.join(''); } }; /** * Defines an external register. * * The name should be a single character that will be used to reference the register. * The register should support setText, pushText, clear, and toString(). See Register * for a reference implementation. */ function defineRegister(name, register) { var registers = vimGlobalState.registerController.registers; if (!name || name.length != 1) { throw Error('Register name must be 1 character'); } if (registers[name]) { throw Error('Register already defined ' + name); } registers[name] = register; validRegisters.push(name); } /* * vim registers allow you to keep many independent copy and paste buffers. * See http://usevim.com/2012/04/13/registers/ for an introduction. * * RegisterController keeps the state of all the registers. An initial * state may be passed in. The unnamed register '"' will always be * overridden. */ function RegisterController(registers) { this.registers = registers; this.unnamedRegister = registers['"'] = new Register(); registers['.'] = new Register(); registers[':'] = new Register(); registers['/'] = new Register(); } RegisterController.prototype = { pushText: function(registerName, operator, text, linewise, blockwise) { if (linewise && text.charAt(text.length - 1) !== '\n'){ text += '\n'; } // Lowercase and uppercase registers refer to the same register. // Uppercase just means append. var register = this.isValidRegister(registerName) ? this.getRegister(registerName) : null; // if no register/an invalid register was specified, things go to the // default registers if (!register) { switch (operator) { case 'yank': // The 0 register contains the text from the most recent yank. this.registers['0'] = new Register(text, linewise, blockwise); break; case 'delete': case 'change': if (text.indexOf('\n') == -1) { // Delete less than 1 line. Update the small delete register. this.registers['-'] = new Register(text, linewise); } else { // Shift down the contents of the numbered registers and put the // deleted text into register 1. this.shiftNumericRegisters_(); this.registers['1'] = new Register(text, linewise); } break; } // Make sure the unnamed register is set to what just happened this.unnamedRegister.setText(text, linewise, blockwise); return; } // If we've gotten to this point, we've actually specified a register var append = isUpperCase(registerName); if (append) { register.pushText(text, linewise); } else { register.setText(text, linewise, blockwise); } // The unnamed register always has the same value as the last used // register. this.unnamedRegister.setText(register.toString(), linewise); }, // Gets the register named @name. If one of @name doesn't already exist, // create it. If @name is invalid, return the unnamedRegister. getRegister: function(name) { if (!this.isValidRegister(name)) { return this.unnamedRegister; } name = name.toLowerCase(); if (!this.registers[name]) { this.registers[name] = new Register(); } return this.registers[name]; }, isValidRegister: function(name) { return name && inArray(name, validRegisters); }, shiftNumericRegisters_: function() { for (var i = 9; i >= 2; i--) { this.registers[i] = this.getRegister('' + (i - 1)); } } }; function HistoryController() { this.historyBuffer = []; this.iterator = 0; this.initialPrefix = null; } HistoryController.prototype = { // the input argument here acts a user entered prefix for a small time // until we start autocompletion in which case it is the autocompleted. nextMatch: function (input, up) { var historyBuffer = this.historyBuffer; var dir = up ? -1 : 1; if (this.initialPrefix === null) this.initialPrefix = input; for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) { var element = historyBuffer[i]; for (var j = 0; j <= element.length; j++) { if (this.initialPrefix == element.substring(0, j)) { this.iterator = i; return element; } } } // should return the user input in case we reach the end of buffer. if (i >= historyBuffer.length) { this.iterator = historyBuffer.length; return this.initialPrefix; } // return the last autocompleted query or exCommand as it is. if (i < 0 ) return input; }, pushInput: function(input) { var index = this.historyBuffer.indexOf(input); if (index > -1) this.historyBuffer.splice(index, 1); if (input.length) this.historyBuffer.push(input); }, reset: function() { this.initialPrefix = null; this.iterator = this.historyBuffer.length; } }; var commandDispatcher = { matchCommand: function(keys, keyMap, inputState, context) { var matches = commandMatches(keys, keyMap, context, inputState); if (!matches.full && !matches.partial) { return {type: 'none'}; } else if (!matches.full && matches.partial) { return {type: 'partial'}; } var bestMatch; for (var i = 0; i < matches.full.length; i++) { var match = matches.full[i]; if (!bestMatch) { bestMatch = match; } } if (bestMatch.keys.slice(-11) == '') { var character = lastChar(keys); if (!character) return {type: 'none'}; inputState.selectedCharacter = character; } return {type: 'full', command: bestMatch}; }, processCommand: function(cm, vim, command) { vim.inputState.repeatOverride = command.repeatOverride; switch (command.type) { case 'motion': this.processMotion(cm, vim, command); break; case 'operator': this.processOperator(cm, vim, command); break; case 'operatorMotion': this.processOperatorMotion(cm, vim, command); break; case 'action': this.processAction(cm, vim, command); break; case 'search': this.processSearch(cm, vim, command); break; case 'ex': case 'keyToEx': this.processEx(cm, vim, command); break; default: break; } }, processMotion: function(cm, vim, command) { vim.inputState.motion = command.motion; vim.inputState.motionArgs = copyArgs(command.motionArgs); this.evalInput(cm, vim); }, processOperator: function(cm, vim, command) { var inputState = vim.inputState; if (inputState.operator) { if (inputState.operator == command.operator) { // Typing an operator twice like 'dd' makes the operator operate // linewise inputState.motion = 'expandToLine'; inputState.motionArgs = { linewise: true }; this.evalInput(cm, vim); return; } else { // 2 different operators in a row doesn't make sense. clearInputState(cm); } } inputState.operator = command.operator; inputState.operatorArgs = copyArgs(command.operatorArgs); if (vim.visualMode) { // Operating on a selection in visual mode. We don't need a motion. this.evalInput(cm, vim); } }, processOperatorMotion: function(cm, vim, command) { var visualMode = vim.visualMode; var operatorMotionArgs = copyArgs(command.operatorMotionArgs); if (operatorMotionArgs) { // Operator motions may have special behavior in visual mode. if (visualMode && operatorMotionArgs.visualLine) { vim.visualLine = true; } } this.processOperator(cm, vim, command); if (!visualMode) { this.processMotion(cm, vim, command); } }, processAction: function(cm, vim, command) { var inputState = vim.inputState; var repeat = inputState.getRepeat(); var repeatIsExplicit = !!repeat; var actionArgs = copyArgs(command.actionArgs) || {}; if (inputState.selectedCharacter) { actionArgs.selectedCharacter = inputState.selectedCharacter; } // Actions may or may not have motions and operators. Do these first. if (command.operator) { this.processOperator(cm, vim, command); } if (command.motion) { this.processMotion(cm, vim, command); } if (command.motion || command.operator) { this.evalInput(cm, vim); } actionArgs.repeat = repeat || 1; actionArgs.repeatIsExplicit = repeatIsExplicit; actionArgs.registerName = inputState.registerName; clearInputState(cm); vim.lastMotion = null; if (command.isEdit) { this.recordLastEdit(vim, inputState, command); } actions[command.action](cm, actionArgs, vim); }, processSearch: function(cm, vim, command) { if (!cm.getSearchCursor) { // Search depends on SearchCursor. return; } var forward = command.searchArgs.forward; var wholeWordOnly = command.searchArgs.wholeWordOnly; getSearchState(cm).setReversed(!forward); var promptPrefix = (forward) ? '/' : '?'; var originalQuery = getSearchState(cm).getQuery(); var originalScrollPos = cm.getScrollInfo(); function handleQuery(query, ignoreCase, smartCase) { vimGlobalState.searchHistoryController.pushInput(query); vimGlobalState.searchHistoryController.reset(); try { updateSearchQuery(cm, query, ignoreCase, smartCase); } catch (e) { showConfirm(cm, 'Invalid regex: ' + query); clearInputState(cm); return; } commandDispatcher.processMotion(cm, vim, { type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist } }); } function onPromptClose(query) { cm.scrollTo(originalScrollPos.left, originalScrollPos.top); handleQuery(query, true /** ignoreCase */, true /** smartCase */); var macroModeState = vimGlobalState.macroModeState; if (macroModeState.isRecording) { logSearchQuery(macroModeState, query); } } function onPromptKeyUp(e, query, close) { var keyName = CodeMirror.keyName(e), up, offset; if (keyName == 'Up' || keyName == 'Down') { up = keyName == 'Up' ? true : false; offset = e.target ? e.target.selectionEnd : 0; query = vimGlobalState.searchHistoryController.nextMatch(query, up) || ''; close(query); if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length); } else { if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') vimGlobalState.searchHistoryController.reset(); } var parsedQuery; try { parsedQuery = updateSearchQuery(cm, query, true /** ignoreCase */, true /** smartCase */); } catch (e) { // Swallow bad regexes for incremental search. } if (parsedQuery) { cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30); } else { clearSearchHighlight(cm); cm.scrollTo(originalScrollPos.left, originalScrollPos.top); } } function onPromptKeyDown(e, query, close) { var keyName = CodeMirror.keyName(e); if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || (keyName == 'Backspace' && query == '')) { vimGlobalState.searchHistoryController.pushInput(query); vimGlobalState.searchHistoryController.reset(); updateSearchQuery(cm, originalQuery); clearSearchHighlight(cm); cm.scrollTo(originalScrollPos.left, originalScrollPos.top); CodeMirror.e_stop(e); clearInputState(cm); close(); cm.focus(); } else if (keyName == 'Up' || keyName == 'Down') { CodeMirror.e_stop(e); } else if (keyName == 'Ctrl-U') { // Ctrl-U clears input. CodeMirror.e_stop(e); close(''); } } switch (command.searchArgs.querySrc) { case 'prompt': var macroModeState = vimGlobalState.macroModeState; if (macroModeState.isPlaying) { var query = macroModeState.replaySearchQueries.shift(); handleQuery(query, true /** ignoreCase */, false /** smartCase */); } else { showPrompt(cm, { onClose: onPromptClose, prefix: promptPrefix, desc: searchPromptDesc, onKeyUp: onPromptKeyUp, onKeyDown: onPromptKeyDown }); } break; case 'wordUnderCursor': var word = expandWordUnderCursor(cm, false /** inclusive */, true /** forward */, false /** bigWord */, true /** noSymbol */); var isKeyword = true; if (!word) { word = expandWordUnderCursor(cm, false /** inclusive */, true /** forward */, false /** bigWord */, false /** noSymbol */); isKeyword = false; } if (!word) { return; } var query = cm.getLine(word.start.line).substring(word.start.ch, word.end.ch); if (isKeyword && wholeWordOnly) { query = '\\b' + query + '\\b'; } else { query = escapeRegex(query); } // cachedCursor is used to save the old position of the cursor // when * or # causes vim to seek for the nearest word and shift // the cursor before entering the motion. vimGlobalState.jumpList.cachedCursor = cm.getCursor(); cm.setCursor(word.start); handleQuery(query, true /** ignoreCase */, false /** smartCase */); break; } }, processEx: function(cm, vim, command) { function onPromptClose(input) { // Give the prompt some time to close so that if processCommand shows // an error, the elements don't overlap. vimGlobalState.exCommandHistoryController.pushInput(input); vimGlobalState.exCommandHistoryController.reset(); exCommandDispatcher.processCommand(cm, input); } function onPromptKeyDown(e, input, close) { var keyName = CodeMirror.keyName(e), up, offset; if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' || (keyName == 'Backspace' && input == '')) { vimGlobalState.exCommandHistoryController.pushInput(input); vimGlobalState.exCommandHistoryController.reset(); CodeMirror.e_stop(e); clearInputState(cm); close(); cm.focus(); } if (keyName == 'Up' || keyName == 'Down') { CodeMirror.e_stop(e); up = keyName == 'Up' ? true : false; offset = e.target ? e.target.selectionEnd : 0; input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || ''; close(input); if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length); } else if (keyName == 'Ctrl-U') { // Ctrl-U clears input. CodeMirror.e_stop(e); close(''); } else { if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift') vimGlobalState.exCommandHistoryController.reset(); } } if (command.type == 'keyToEx') { // Handle user defined Ex to Ex mappings exCommandDispatcher.processCommand(cm, command.exArgs.input); } else { if (vim.visualMode) { showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>', onKeyDown: onPromptKeyDown, selectValueOnOpen: false}); } else { showPrompt(cm, { onClose: onPromptClose, prefix: ':', onKeyDown: onPromptKeyDown}); } } }, evalInput: function(cm, vim) { // If the motion command is set, execute both the operator and motion. // Otherwise return. var inputState = vim.inputState; var motion = inputState.motion; var motionArgs = inputState.motionArgs || {}; var operator = inputState.operator; var operatorArgs = inputState.operatorArgs || {}; var registerName = inputState.registerName; var sel = vim.sel; // TODO: Make sure cm and vim selections are identical outside visual mode. var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head')); var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor')); var oldHead = copyCursor(origHead); var oldAnchor = copyCursor(origAnchor); var newHead, newAnchor; var repeat; if (operator) { this.recordLastEdit(vim, inputState); } if (inputState.repeatOverride !== undefined) { // If repeatOverride is specified, that takes precedence over the // input state's repeat. Used by Ex mode and can be user defined. repeat = inputState.repeatOverride; } else { repeat = inputState.getRepeat(); } if (repeat > 0 && motionArgs.explicitRepeat) { motionArgs.repeatIsExplicit = true; } else if (motionArgs.noRepeat || (!motionArgs.explicitRepeat && repeat === 0)) { repeat = 1; motionArgs.repeatIsExplicit = false; } if (inputState.selectedCharacter) { // If there is a character input, stick it in all of the arg arrays. motionArgs.selectedCharacter = operatorArgs.selectedCharacter = inputState.selectedCharacter; } motionArgs.repeat = repeat; clearInputState(cm); if (motion) { var motionResult = motions[motion](cm, origHead, motionArgs, vim); vim.lastMotion = motions[motion]; if (!motionResult) { return; } if (motionArgs.toJumplist) { var jumpList = vimGlobalState.jumpList; // if the current motion is # or *, use cachedCursor var cachedCursor = jumpList.cachedCursor; if (cachedCursor) { recordJumpPosition(cm, cachedCursor, motionResult); delete jumpList.cachedCursor; } else { recordJumpPosition(cm, origHead, motionResult); } } if (motionResult instanceof Array) { newAnchor = motionResult[0]; newHead = motionResult[1]; } else { newHead = motionResult; } // TODO: Handle null returns from motion commands better. if (!newHead) { newHead = copyCursor(origHead); } if (vim.visualMode) { if (!(vim.visualBlock && newHead.ch === Infinity)) { newHead = clipCursorToContent(cm, newHead, vim.visualBlock); } if (newAnchor) { newAnchor = clipCursorToContent(cm, newAnchor, true); } newAnchor = newAnchor || oldAnchor; sel.anchor = newAnchor; sel.head = newHead; updateCmSelection(cm); updateMark(cm, vim, '<', cursorIsBefore(newAnchor, newHead) ? newAnchor : newHead); updateMark(cm, vim, '>', cursorIsBefore(newAnchor, newHead) ? newHead : newAnchor); } else if (!operator) { newHead = clipCursorToContent(cm, newHead); cm.setCursor(newHead.line, newHead.ch); } } if (operator) { if (operatorArgs.lastSel) { // Replaying a visual mode operation newAnchor = oldAnchor; var lastSel = operatorArgs.lastSel; var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line); var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch); if (lastSel.visualLine) { // Linewise Visual mode: The same number of lines. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); } else if (lastSel.visualBlock) { // Blockwise Visual mode: The same number of lines and columns. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset); } else if (lastSel.head.line == lastSel.anchor.line) { // Normal Visual mode within one line: The same number of characters. newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset); } else { // Normal Visual mode with several lines: The same number of lines, in the // last line the same number of characters as in the last line the last time. newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch); } vim.visualMode = true; vim.visualLine = lastSel.visualLine; vim.visualBlock = lastSel.visualBlock; sel = vim.sel = { anchor: newAnchor, head: newHead }; updateCmSelection(cm); } else if (vim.visualMode) { operatorArgs.lastSel = { anchor: copyCursor(sel.anchor), head: copyCursor(sel.head), visualBlock: vim.visualBlock, visualLine: vim.visualLine }; } var curStart, curEnd, linewise, mode; var cmSel; if (vim.visualMode) { // Init visual op curStart = cursorMin(sel.head, sel.anchor); curEnd = cursorMax(sel.head, sel.anchor); linewise = vim.visualLine || operatorArgs.linewise; mode = vim.visualBlock ? 'block' : linewise ? 'line' : 'char'; cmSel = makeCmSelection(cm, { anchor: curStart, head: curEnd }, mode); if (linewise) { var ranges = cmSel.ranges; if (mode == 'block') { // Linewise operators in visual block mode extend to end of line for (var i = 0; i < ranges.length; i++) { ranges[i].head.ch = lineLength(cm, ranges[i].head.line); } } else if (mode == 'line') { ranges[0].head = Pos(ranges[0].head.line + 1, 0); } } } else { // Init motion op curStart = copyCursor(newAnchor || oldAnchor); curEnd = copyCursor(newHead || oldHead); if (cursorIsBefore(curEnd, curStart)) { var tmp = curStart; curStart = curEnd; curEnd = tmp; } linewise = motionArgs.linewise || operatorArgs.linewise; if (linewise) { // Expand selection to entire line. expandSelectionToLine(cm, curStart, curEnd); } else if (motionArgs.forward) { // Clip to trailing newlines only if the motion goes forward. clipToLine(cm, curStart, curEnd); } mode = 'char'; var exclusive = !motionArgs.inclusive || linewise; cmSel = makeCmSelection(cm, { anchor: curStart, head: curEnd }, mode, exclusive); } cm.setSelections(cmSel.ranges, cmSel.primary); vim.lastMotion = null; operatorArgs.repeat = repeat; // For indent in visual mode. operatorArgs.registerName = registerName; // Keep track of linewise as it affects how paste and change behave. operatorArgs.linewise = linewise; var operatorMoveTo = operators[operator]( cm, operatorArgs, cmSel.ranges, oldAnchor, newHead); if (vim.visualMode) { exitVisualMode(cm, operatorMoveTo != null); } if (operatorMoveTo) { cm.setCursor(operatorMoveTo); } } }, recordLastEdit: function(vim, inputState, actionCommand) { var macroModeState = vimGlobalState.macroModeState; if (macroModeState.isPlaying) { return; } vim.lastEditInputState = inputState; vim.lastEditActionCommand = actionCommand; macroModeState.lastInsertModeChanges.changes = []; macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false; } }; /** * typedef {Object{line:number,ch:number}} Cursor An object containing the * position of the cursor. */ // All of the functions below return Cursor objects. var motions = { moveToTopLine: function(cm, _head, motionArgs) { var line = getUserVisibleLines(cm).top + motionArgs.repeat -1; return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); }, moveToMiddleLine: function(cm) { var range = getUserVisibleLines(cm); var line = Math.floor((range.top + range.bottom) * 0.5); return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); }, moveToBottomLine: function(cm, _head, motionArgs) { var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1; return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line))); }, expandToLine: function(_cm, head, motionArgs) { // Expands forward to end of line, and then to next line if repeat is // >1. Does not handle backward motion! var cur = head; return Pos(cur.line + motionArgs.repeat - 1, Infinity); }, findNext: function(cm, _head, motionArgs) { var state = getSearchState(cm); var query = state.getQuery(); if (!query) { return; } var prev = !motionArgs.forward; // If search is initiated with ? instead of /, negate direction. prev = (state.isReversed()) ? !prev : prev; highlightSearchMatches(cm, query); return findNext(cm, prev/** prev */, query, motionArgs.repeat); }, goToMark: function(cm, _head, motionArgs, vim) { var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter); if (pos) { return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos; } return null; }, moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) { if (vim.visualBlock && motionArgs.sameLine) { var sel = vim.sel; return [ clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)), clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch)) ]; } else { return ([vim.sel.head, vim.sel.anchor]); } }, jumpToMark: function(cm, head, motionArgs, vim) { var best = head; for (var i = 0; i < motionArgs.repeat; i++) { var cursor = best; for (var key in vim.marks) { if (!isLowerCase(key)) { continue; } var mark = vim.marks[key].find(); var isWrongDirection = (motionArgs.forward) ? cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark); if (isWrongDirection) { continue; } if (motionArgs.linewise && (mark.line == cursor.line)) { continue; } var equal = cursorEqual(cursor, best); var between = (motionArgs.forward) ? cursorIsBetween(cursor, mark, best) : cursorIsBetween(best, mark, cursor); if (equal || between) { best = mark; } } } if (motionArgs.linewise) { // Vim places the cursor on the first non-whitespace character of // the line if there is one, else it places the cursor at the end // of the line, regardless of whether a mark was found. best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line))); } return best; }, moveByCharacters: function(_cm, head, motionArgs) { var cur = head; var repeat = motionArgs.repeat; var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; return Pos(cur.line, ch); }, moveByLines: function(cm, head, motionArgs, vim) { var cur = head; var endCh = cur.ch; // Depending what our last motion was, we may want to do different // things. If our last motion was moving vertically, we want to // preserve the HPos from our last horizontal move. If our last motion // was going to the end of a line, moving vertically we should go to // the end of the line, etc. switch (vim.lastMotion) { case this.moveByLines: case this.moveByDisplayLines: case this.moveByScroll: case this.moveToColumn: case this.moveToEol: endCh = vim.lastHPos; break; default: vim.lastHPos = endCh; } var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0); var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; var first = cm.firstLine(); var last = cm.lastLine(); // Vim go to line begin or line end when cursor at first/last line and // move to previous/next line is triggered. if (line < first && cur.line == first){ return this.moveToStartOfLine(cm, head, motionArgs, vim); }else if (line > last && cur.line == last){ return this.moveToEol(cm, head, motionArgs, vim); } if (motionArgs.toFirstChar){ endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line)); vim.lastHPos = endCh; } vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left; return Pos(line, endCh); }, moveByDisplayLines: function(cm, head, motionArgs, vim) { var cur = head; switch (vim.lastMotion) { case this.moveByDisplayLines: case this.moveByScroll: case this.moveByLines: case this.moveToColumn: case this.moveToEol: break; default: vim.lastHSPos = cm.charCoords(cur,'div').left; } var repeat = motionArgs.repeat; var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos); if (res.hitSide) { if (motionArgs.forward) { var lastCharCoords = cm.charCoords(res, 'div'); var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos }; var res = cm.coordsChar(goalCoords, 'div'); } else { var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div'); resCoords.left = vim.lastHSPos; res = cm.coordsChar(resCoords, 'div'); } } vim.lastHPos = res.ch; return res; }, moveByPage: function(cm, head, motionArgs) { // CodeMirror only exposes functions that move the cursor page down, so // doing this bad hack to move the cursor and move it back. evalInput // will move the cursor to where it should be in the end. var curStart = head; var repeat = motionArgs.repeat; return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page'); }, moveByParagraph: function(cm, head, motionArgs) { var dir = motionArgs.forward ? 1 : -1; return findParagraph(cm, head, motionArgs.repeat, dir); }, moveBySentence: function(cm, head, motionArgs) { var dir = motionArgs.forward ? 1 : -1; return findSentence(cm, head, motionArgs.repeat, dir); }, moveByScroll: function(cm, head, motionArgs, vim) { var scrollbox = cm.getScrollInfo(); var curEnd = null; var repeat = motionArgs.repeat; if (!repeat) { repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight()); } var orig = cm.charCoords(head, 'local'); motionArgs.repeat = repeat; var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim); if (!curEnd) { return null; } var dest = cm.charCoords(curEnd, 'local'); cm.scrollTo(null, scrollbox.top + dest.top - orig.top); return curEnd; }, moveByWords: function(cm, head, motionArgs) { return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward, !!motionArgs.wordEnd, !!motionArgs.bigWord); }, moveTillCharacter: function(cm, _head, motionArgs) { var repeat = motionArgs.repeat; var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter); var increment = motionArgs.forward ? -1 : 1; recordLastCharacterSearch(increment, motionArgs); if (!curEnd) return null; curEnd.ch += increment; return curEnd; }, moveToCharacter: function(cm, head, motionArgs) { var repeat = motionArgs.repeat; recordLastCharacterSearch(0, motionArgs); return moveToCharacter(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter) || head; }, moveToSymbol: function(cm, head, motionArgs) { var repeat = motionArgs.repeat; return findSymbol(cm, repeat, motionArgs.forward, motionArgs.selectedCharacter) || head; }, moveToColumn: function(cm, head, motionArgs, vim) { var repeat = motionArgs.repeat; // repeat is equivalent to which column we want to move to! vim.lastHPos = repeat - 1; vim.lastHSPos = cm.charCoords(head,'div').left; return moveToColumn(cm, repeat); }, moveToEol: function(cm, head, motionArgs, vim) { var cur = head; vim.lastHPos = Infinity; var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity); var end=cm.clipPos(retval); end.ch--; vim.lastHSPos = cm.charCoords(end,'div').left; return retval; }, moveToFirstNonWhiteSpaceCharacter: function(cm, head) { // Go to the start of the line where the text begins, or the end for // whitespace-only lines var cursor = head; return Pos(cursor.line, findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line))); }, moveToMatchedSymbol: function(cm, head) { var cursor = head; var line = cursor.line; var ch = cursor.ch; var lineText = cm.getLine(line); var symbol; for (; ch < lineText.length; ch++) { symbol = lineText.charAt(ch); if (symbol && isMatchableSymbol(symbol)) { var style = cm.getTokenTypeAt(Pos(line, ch + 1)); if (style !== "string" && style !== "comment") { break; } } } if (ch < lineText.length) { var matched = cm.findMatchingBracket(Pos(line, ch), {bracketRegex: /[(){}[\]<>]/}); return matched.to; } else { return cursor; } }, moveToStartOfLine: function(_cm, head) { return Pos(head.line, 0); }, moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) { var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine(); if (motionArgs.repeatIsExplicit) { lineNum = motionArgs.repeat - cm.getOption('firstLineNumber'); } return Pos(lineNum, findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum))); }, textObjectManipulation: function(cm, head, motionArgs, vim) { // TODO: lots of possible exceptions that can be thrown here. Try da( // outside of a () block. var mirroredPairs = {'(': ')', ')': '(', '{': '}', '}': '{', '[': ']', ']': '[', '<': '>', '>': '<'}; var selfPaired = {'\'': true, '"': true}; var character = motionArgs.selectedCharacter; // 'b' refers to '()' block. // 'B' refers to '{}' block. if (character == 'b') { character = '('; } else if (character == 'B') { character = '{'; } // Inclusive is the difference between a and i // TODO: Instead of using the additional text object map to perform text // object operations, merge the map into the defaultKeyMap and use // motionArgs to define behavior. Define separate entries for 'aw', // 'iw', 'a[', 'i[', etc. var inclusive = !motionArgs.textObjectInner; var tmp; if (mirroredPairs[character]) { tmp = selectCompanionObject(cm, head, character, inclusive); } else if (selfPaired[character]) { tmp = findBeginningAndEnd(cm, head, character, inclusive); } else if (character === 'W') { tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, true /** bigWord */); } else if (character === 'w') { tmp = expandWordUnderCursor(cm, inclusive, true /** forward */, false /** bigWord */); } else if (character === 'p') { tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive); motionArgs.linewise = true; if (vim.visualMode) { if (!vim.visualLine) { vim.visualLine = true; } } else { var operatorArgs = vim.inputState.operatorArgs; if (operatorArgs) { operatorArgs.linewise = true; } tmp.end.line--; } } else { // No text object defined for this, don't move. return null; } if (!cm.state.vim.visualMode) { return [tmp.start, tmp.end]; } else { return expandSelection(cm, tmp.start, tmp.end); } }, repeatLastCharacterSearch: function(cm, head, motionArgs) { var lastSearch = vimGlobalState.lastCharacterSearch; var repeat = motionArgs.repeat; var forward = motionArgs.forward === lastSearch.forward; var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1); cm.moveH(-increment, 'char'); motionArgs.inclusive = forward ? true : false; var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter); if (!curEnd) { cm.moveH(increment, 'char'); return head; } curEnd.ch += increment; return curEnd; } }; function defineMotion(name, fn) { motions[name] = fn; } function fillArray(val, times) { var arr = []; for (var i = 0; i < times; i++) { arr.push(val); } return arr; } /** * An operator acts on a text selection. It receives the list of selections * as input. The corresponding CodeMirror selection is guaranteed to * match the input selection. */ var operators = { change: function(cm, args, ranges) { var finalHead, text; var vim = cm.state.vim; vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock = vim.visualBlock; if (!vim.visualMode) { var anchor = ranges[0].anchor, head = ranges[0].head; text = cm.getRange(anchor, head); var lastState = vim.lastEditInputState || {}; if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) { // Exclude trailing whitespace if the range is not all whitespace. var match = (/\s+$/).exec(text); if (match && lastState.motionArgs && lastState.motionArgs.forward) { head = offsetCursor(head, 0, - match[0].length); text = text.slice(0, - match[0].length); } } var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE); var wasLastLine = cm.firstLine() == cm.lastLine(); if (head.line > cm.lastLine() && args.linewise && !wasLastLine) { cm.replaceRange('', prevLineEnd, head); } else { cm.replaceRange('', anchor, head); } if (args.linewise) { // Push the next line back down, if there is a next line. if (!wasLastLine) { cm.setCursor(prevLineEnd); CodeMirror.commands.newlineAndIndent(cm); } // make sure cursor ends up at the end of the line. anchor.ch = Number.MAX_VALUE; } finalHead = anchor; } else { text = cm.getSelection(); var replacement = fillArray('', ranges.length); cm.replaceSelections(replacement); finalHead = cursorMin(ranges[0].head, ranges[0].anchor); } vimGlobalState.registerController.pushText( args.registerName, 'change', text, args.linewise, ranges.length > 1); actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim); }, // delete is a javascript keyword. 'delete': function(cm, args, ranges) { var finalHead, text; var vim = cm.state.vim; if (!vim.visualBlock) { var anchor = ranges[0].anchor, head = ranges[0].head; if (args.linewise && head.line != cm.firstLine() && anchor.line == cm.lastLine() && anchor.line == head.line - 1) { // Special case for dd on last line (and first line). if (anchor.line == cm.firstLine()) { anchor.ch = 0; } else { anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1)); } } text = cm.getRange(anchor, head); cm.replaceRange('', anchor, head); finalHead = anchor; if (args.linewise) { finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor); } } else { text = cm.getSelection(); var replacement = fillArray('', ranges.length); cm.replaceSelections(replacement); finalHead = ranges[0].anchor; } vimGlobalState.registerController.pushText( args.registerName, 'delete', text, args.linewise, vim.visualBlock); var includeLineBreak = vim.insertMode return clipCursorToContent(cm, finalHead, includeLineBreak); }, indent: function(cm, args, ranges) { var vim = cm.state.vim; var startLine = ranges[0].anchor.line; var endLine = vim.visualBlock ? ranges[ranges.length - 1].anchor.line : ranges[0].head.line; // In visual mode, n> shifts the selection right n times, instead of // shifting n lines right once. var repeat = (vim.visualMode) ? args.repeat : 1; if (args.linewise) { // The only way to delete a newline is to delete until the start of // the next line, so in linewise mode evalInput will include the next // line. We don't want this in indent, so we go back a line. endLine--; } for (var i = startLine; i <= endLine; i++) { for (var j = 0; j < repeat; j++) { cm.indentLine(i, args.indentRight); } } return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor); }, indentAuto: function(cm, _args, ranges) { cm.execCommand("indentAuto"); return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor); }, changeCase: function(cm, args, ranges, oldAnchor, newHead) { var selections = cm.getSelections(); var swapped = []; var toLower = args.toLower; for (var j = 0; j < selections.length; j++) { var toSwap = selections[j]; var text = ''; if (toLower === true) { text = toSwap.toLowerCase(); } else if (toLower === false) { text = toSwap.toUpperCase(); } else { for (var i = 0; i < toSwap.length; i++) { var character = toSwap.charAt(i); text += isUpperCase(character) ? character.toLowerCase() : character.toUpperCase(); } } swapped.push(text); } cm.replaceSelections(swapped); if (args.shouldMoveCursor){ return newHead; } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) { return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor); } else if (args.linewise){ return oldAnchor; } else { return cursorMin(ranges[0].anchor, ranges[0].head); } }, yank: function(cm, args, ranges, oldAnchor) { var vim = cm.state.vim; var text = cm.getSelection(); var endPos = vim.visualMode ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor) : oldAnchor; vimGlobalState.registerController.pushText( args.registerName, 'yank', text, args.linewise, vim.visualBlock); return endPos; } }; function defineOperator(name, fn) { operators[name] = fn; } var actions = { jumpListWalk: function(cm, actionArgs, vim) { if (vim.visualMode) { return; } var repeat = actionArgs.repeat; var forward = actionArgs.forward; var jumpList = vimGlobalState.jumpList; var mark = jumpList.move(cm, forward ? repeat : -repeat); var markPos = mark ? mark.find() : undefined; markPos = markPos ? markPos : cm.getCursor(); cm.setCursor(markPos); }, scroll: function(cm, actionArgs, vim) { if (vim.visualMode) { return; } var repeat = actionArgs.repeat || 1; var lineHeight = cm.defaultTextHeight(); var top = cm.getScrollInfo().top; var delta = lineHeight * repeat; var newPos = actionArgs.forward ? top + delta : top - delta; var cursor = copyCursor(cm.getCursor()); var cursorCoords = cm.charCoords(cursor, 'local'); if (actionArgs.forward) { if (newPos > cursorCoords.top) { cursor.line += (newPos - cursorCoords.top) / lineHeight; cursor.line = Math.ceil(cursor.line); cm.setCursor(cursor); cursorCoords = cm.charCoords(cursor, 'local'); cm.scrollTo(null, cursorCoords.top); } else { // Cursor stays within bounds. Just reposition the scroll window. cm.scrollTo(null, newPos); } } else { var newBottom = newPos + cm.getScrollInfo().clientHeight; if (newBottom < cursorCoords.bottom) { cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight; cursor.line = Math.floor(cursor.line); cm.setCursor(cursor); cursorCoords = cm.charCoords(cursor, 'local'); cm.scrollTo( null, cursorCoords.bottom - cm.getScrollInfo().clientHeight); } else { // Cursor stays within bounds. Just reposition the scroll window. cm.scrollTo(null, newPos); } } }, scrollToCursor: function(cm, actionArgs) { var lineNum = cm.getCursor().line; var charCoords = cm.charCoords(Pos(lineNum, 0), 'local'); var height = cm.getScrollInfo().clientHeight; var y = charCoords.top; var lineHeight = charCoords.bottom - y; switch (actionArgs.position) { case 'center': y = y - (height / 2) + lineHeight; break; case 'bottom': y = y - height + lineHeight; break; } cm.scrollTo(null, y); }, replayMacro: function(cm, actionArgs, vim) { var registerName = actionArgs.selectedCharacter; var repeat = actionArgs.repeat; var macroModeState = vimGlobalState.macroModeState; if (registerName == '@') { registerName = macroModeState.latestRegister; } while(repeat--){ executeMacroRegister(cm, vim, macroModeState, registerName); } }, enterMacroRecordMode: function(cm, actionArgs) { var macroModeState = vimGlobalState.macroModeState; var registerName = actionArgs.selectedCharacter; if (vimGlobalState.registerController.isValidRegister(registerName)) { macroModeState.enterMacroRecordMode(cm, registerName); } }, toggleOverwrite: function(cm) { if (!cm.state.overwrite) { cm.toggleOverwrite(true); cm.setOption('keyMap', 'vim-replace'); CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); } else { cm.toggleOverwrite(false); cm.setOption('keyMap', 'vim-insert'); CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); } }, enterInsertMode: function(cm, actionArgs, vim) { if (cm.getOption('readOnly')) { return; } vim.insertMode = true; vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1; var insertAt = (actionArgs) ? actionArgs.insertAt : null; var sel = vim.sel; var head = actionArgs.head || cm.getCursor('head'); var height = cm.listSelections().length; if (insertAt == 'eol') { head = Pos(head.line, lineLength(cm, head.line)); } else if (insertAt == 'charAfter') { head = offsetCursor(head, 0, 1); } else if (insertAt == 'firstNonBlank') { head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head); } else if (insertAt == 'startOfSelectedArea') { if (!vim.visualBlock) { if (sel.head.line < sel.anchor.line) { head = sel.head; } else { head = Pos(sel.anchor.line, 0); } } else { head = Pos( Math.min(sel.head.line, sel.anchor.line), Math.min(sel.head.ch, sel.anchor.ch)); height = Math.abs(sel.head.line - sel.anchor.line) + 1; } } else if (insertAt == 'endOfSelectedArea') { if (!vim.visualBlock) { if (sel.head.line >= sel.anchor.line) { head = offsetCursor(sel.head, 0, 1); } else { head = Pos(sel.anchor.line, 0); } } else { head = Pos( Math.min(sel.head.line, sel.anchor.line), Math.max(sel.head.ch + 1, sel.anchor.ch)); height = Math.abs(sel.head.line - sel.anchor.line) + 1; } } else if (insertAt == 'inplace') { if (vim.visualMode){ return; } } cm.setOption('disableInput', false); if (actionArgs && actionArgs.replace) { // Handle Replace-mode as a special case of insert mode. cm.toggleOverwrite(true); cm.setOption('keyMap', 'vim-replace'); CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"}); } else { cm.toggleOverwrite(false); cm.setOption('keyMap', 'vim-insert'); CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"}); } if (!vimGlobalState.macroModeState.isPlaying) { // Only record if not replaying. cm.on('change', onChange); CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); } if (vim.visualMode) { exitVisualMode(cm); } selectForInsert(cm, head, height); }, toggleVisualMode: function(cm, actionArgs, vim) { var repeat = actionArgs.repeat; var anchor = cm.getCursor(); var head; // TODO: The repeat should actually select number of characters/lines // equal to the repeat times the size of the previous visual // operation. if (!vim.visualMode) { // Entering visual mode vim.visualMode = true; vim.visualLine = !!actionArgs.linewise; vim.visualBlock = !!actionArgs.blockwise; head = clipCursorToContent( cm, Pos(anchor.line, anchor.ch + repeat - 1), true /** includeLineBreak */); vim.sel = { anchor: anchor, head: head }; CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); updateCmSelection(cm); updateMark(cm, vim, '<', cursorMin(anchor, head)); updateMark(cm, vim, '>', cursorMax(anchor, head)); } else if (vim.visualLine ^ actionArgs.linewise || vim.visualBlock ^ actionArgs.blockwise) { // Toggling between modes vim.visualLine = !!actionArgs.linewise; vim.visualBlock = !!actionArgs.blockwise; CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""}); updateCmSelection(cm); } else { exitVisualMode(cm); } }, reselectLastSelection: function(cm, _actionArgs, vim) { var lastSelection = vim.lastSelection; if (vim.visualMode) { updateLastSelection(cm, vim); } if (lastSelection) { var anchor = lastSelection.anchorMark.find(); var head = lastSelection.headMark.find(); if (!anchor || !head) { // If the marks have been destroyed due to edits, do nothing. return; } vim.sel = { anchor: anchor, head: head }; vim.visualMode = true; vim.visualLine = lastSelection.visualLine; vim.visualBlock = lastSelection.visualBlock; updateCmSelection(cm); updateMark(cm, vim, '<', cursorMin(anchor, head)); updateMark(cm, vim, '>', cursorMax(anchor, head)); CodeMirror.signal(cm, 'vim-mode-change', { mode: 'visual', subMode: vim.visualLine ? 'linewise' : vim.visualBlock ? 'blockwise' : ''}); } }, joinLines: function(cm, actionArgs, vim) { var curStart, curEnd; if (vim.visualMode) { curStart = cm.getCursor('anchor'); curEnd = cm.getCursor('head'); if (cursorIsBefore(curEnd, curStart)) { var tmp = curEnd; curEnd = curStart; curStart = tmp; } curEnd.ch = lineLength(cm, curEnd.line) - 1; } else { // Repeat is the number of lines to join. Minimum 2 lines. var repeat = Math.max(actionArgs.repeat, 2); curStart = cm.getCursor(); curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1, Infinity)); } var finalCh = 0; for (var i = curStart.line; i < curEnd.line; i++) { finalCh = lineLength(cm, curStart.line); var tmp = Pos(curStart.line + 1, lineLength(cm, curStart.line + 1)); var text = cm.getRange(curStart, tmp); text = text.replace(/\n\s*/g, ' '); cm.replaceRange(text, curStart, tmp); } var curFinalPos = Pos(curStart.line, finalCh); if (vim.visualMode) { exitVisualMode(cm, false); } cm.setCursor(curFinalPos); }, newLineAndEnterInsertMode: function(cm, actionArgs, vim) { vim.insertMode = true; var insertAt = copyCursor(cm.getCursor()); if (insertAt.line === cm.firstLine() && !actionArgs.after) { // Special case for inserting newline before start of document. cm.replaceRange('\n', Pos(cm.firstLine(), 0)); cm.setCursor(cm.firstLine(), 0); } else { insertAt.line = (actionArgs.after) ? insertAt.line : insertAt.line - 1; insertAt.ch = lineLength(cm, insertAt.line); cm.setCursor(insertAt); var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent; newlineFn(cm); } this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim); }, paste: function(cm, actionArgs, vim) { var cur = copyCursor(cm.getCursor()); var register = vimGlobalState.registerController.getRegister( actionArgs.registerName); var text = register.toString(); if (!text) { return; } if (actionArgs.matchIndent) { var tabSize = cm.getOption("tabSize"); // length that considers tabs and tabSize var whitespaceLength = function(str) { var tabs = (str.split("\t").length - 1); var spaces = (str.split(" ").length - 1); return tabs * tabSize + spaces * 1; }; var currentLine = cm.getLine(cm.getCursor().line); var indent = whitespaceLength(currentLine.match(/^\s*/)[0]); // chomp last newline b/c don't want it to match /^\s*/gm var chompedText = text.replace(/\n$/, ''); var wasChomped = text !== chompedText; var firstIndent = whitespaceLength(text.match(/^\s*/)[0]); var text = chompedText.replace(/^\s*/gm, function(wspace) { var newIndent = indent + (whitespaceLength(wspace) - firstIndent); if (newIndent < 0) { return ""; } else if (cm.getOption("indentWithTabs")) { var quotient = Math.floor(newIndent / tabSize); return Array(quotient + 1).join('\t'); } else { return Array(newIndent + 1).join(' '); } }); text += wasChomped ? "\n" : ""; } if (actionArgs.repeat > 1) { var text = Array(actionArgs.repeat + 1).join(text); } var linewise = register.linewise; var blockwise = register.blockwise; if (linewise) { if(vim.visualMode) { text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n'; } else if (actionArgs.after) { // Move the newline at the end to the start instead, and paste just // before the newline character of the line we are on right now. text = '\n' + text.slice(0, text.length - 1); cur.ch = lineLength(cm, cur.line); } else { cur.ch = 0; } } else { if (blockwise) { text = text.split('\n'); for (var i = 0; i < text.length; i++) { text[i] = (text[i] == '') ? ' ' : text[i]; } } cur.ch += actionArgs.after ? 1 : 0; } var curPosFinal; var idx; if (vim.visualMode) { // save the pasted text for reselection if the need arises vim.lastPastedText = text; var lastSelectionCurEnd; var selectedArea = getSelectedAreaRange(cm, vim); var selectionStart = selectedArea[0]; var selectionEnd = selectedArea[1]; var selectedText = cm.getSelection(); var selections = cm.listSelections(); var emptyStrings = new Array(selections.length).join('1').split('1'); // save the curEnd marker before it get cleared due to cm.replaceRange. if (vim.lastSelection) { lastSelectionCurEnd = vim.lastSelection.headMark.find(); } // push the previously selected text to unnamed register vimGlobalState.registerController.unnamedRegister.setText(selectedText); if (blockwise) { // first delete the selected text cm.replaceSelections(emptyStrings); // Set new selections as per the block length of the yanked text selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch); cm.setCursor(selectionStart); selectBlock(cm, selectionEnd); cm.replaceSelections(text); curPosFinal = selectionStart; } else if (vim.visualBlock) { cm.replaceSelections(emptyStrings); cm.setCursor(selectionStart); cm.replaceRange(text, selectionStart, selectionStart); curPosFinal = selectionStart; } else { cm.replaceRange(text, selectionStart, selectionEnd); curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1); } // restore the the curEnd marker if(lastSelectionCurEnd) { vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd); } if (linewise) { curPosFinal.ch=0; } } else { if (blockwise) { cm.setCursor(cur); for (var i = 0; i < text.length; i++) { var line = cur.line+i; if (line > cm.lastLine()) { cm.replaceRange('\n', Pos(line, 0)); } var lastCh = lineLength(cm, line); if (lastCh < cur.ch) { extendLineToColumn(cm, line, cur.ch); } } cm.setCursor(cur); selectBlock(cm, Pos(cur.line + text.length-1, cur.ch)); cm.replaceSelections(text); curPosFinal = cur; } else { cm.replaceRange(text, cur); // Now fine tune the cursor to where we want it. if (linewise && actionArgs.after) { curPosFinal = Pos( cur.line + 1, findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1))); } else if (linewise && !actionArgs.after) { curPosFinal = Pos( cur.line, findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line))); } else if (!linewise && actionArgs.after) { idx = cm.indexFromPos(cur); curPosFinal = cm.posFromIndex(idx + text.length - 1); } else { idx = cm.indexFromPos(cur); curPosFinal = cm.posFromIndex(idx + text.length); } } } if (vim.visualMode) { exitVisualMode(cm, false); } cm.setCursor(curPosFinal); }, undo: function(cm, actionArgs) { cm.operation(function() { repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); cm.setCursor(cm.getCursor('anchor')); }); }, redo: function(cm, actionArgs) { repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)(); }, setRegister: function(_cm, actionArgs, vim) { vim.inputState.registerName = actionArgs.selectedCharacter; }, setMark: function(cm, actionArgs, vim) { var markName = actionArgs.selectedCharacter; updateMark(cm, vim, markName, cm.getCursor()); }, replace: function(cm, actionArgs, vim) { var replaceWith = actionArgs.selectedCharacter; var curStart = cm.getCursor(); var replaceTo; var curEnd; var selections = cm.listSelections(); if (vim.visualMode) { curStart = cm.getCursor('start'); curEnd = cm.getCursor('end'); } else { var line = cm.getLine(curStart.line); replaceTo = curStart.ch + actionArgs.repeat; if (replaceTo > line.length) { replaceTo=line.length; } curEnd = Pos(curStart.line, replaceTo); } if (replaceWith=='\n') { if (!vim.visualMode) cm.replaceRange('', curStart, curEnd); // special case, where vim help says to replace by just one line-break (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm); } else { var replaceWithStr = cm.getRange(curStart, curEnd); //replace all characters in range by selected, but keep linebreaks replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith); if (vim.visualBlock) { // Tabs are split in visua block before replacing var spaces = new Array(cm.getOption("tabSize")+1).join(' '); replaceWithStr = cm.getSelection(); replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n'); cm.replaceSelections(replaceWithStr); } else { cm.replaceRange(replaceWithStr, curStart, curEnd); } if (vim.visualMode) { curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ? selections[0].anchor : selections[0].head; cm.setCursor(curStart); exitVisualMode(cm, false); } else { cm.setCursor(offsetCursor(curEnd, 0, -1)); } } }, incrementNumberToken: function(cm, actionArgs) { var cur = cm.getCursor(); var lineStr = cm.getLine(cur.line); var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi; var match; var start; var end; var numberStr; while ((match = re.exec(lineStr)) !== null) { start = match.index; end = start + match[0].length; if (cur.ch < end)break; } if (!actionArgs.backtrack && (end <= cur.ch))return; if (match) { var baseStr = match[2] || match[4] var digits = match[3] || match[5] var increment = actionArgs.increase ? 1 : -1; var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()]; var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat); numberStr = number.toString(base); var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : '' if (numberStr.charAt(0) === '-') { numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1); } else { numberStr = baseStr + zeroPadding + numberStr; } var from = Pos(cur.line, start); var to = Pos(cur.line, end); cm.replaceRange(numberStr, from, to); } else { return; } cm.setCursor(Pos(cur.line, start + numberStr.length - 1)); }, repeatLastEdit: function(cm, actionArgs, vim) { var lastEditInputState = vim.lastEditInputState; if (!lastEditInputState) { return; } var repeat = actionArgs.repeat; if (repeat && actionArgs.repeatIsExplicit) { vim.lastEditInputState.repeatOverride = repeat; } else { repeat = vim.lastEditInputState.repeatOverride || repeat; } repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */); }, indent: function(cm, actionArgs) { cm.indentLine(cm.getCursor().line, actionArgs.indentRight); }, exitInsertMode: exitInsertMode }; function defineAction(name, fn) { actions[name] = fn; } /* * Below are miscellaneous utility functions used by vim.js */ /** * Clips cursor to ensure that line is within the buffer's range * If includeLineBreak is true, then allow cur.ch == lineLength. */ function clipCursorToContent(cm, cur, includeLineBreak) { var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() ); var maxCh = lineLength(cm, line) - 1; maxCh = (includeLineBreak) ? maxCh + 1 : maxCh; var ch = Math.min(Math.max(0, cur.ch), maxCh); return Pos(line, ch); } function copyArgs(args) { var ret = {}; for (var prop in args) { if (args.hasOwnProperty(prop)) { ret[prop] = args[prop]; } } return ret; } function offsetCursor(cur, offsetLine, offsetCh) { if (typeof offsetLine === 'object') { offsetCh = offsetLine.ch; offsetLine = offsetLine.line; } return Pos(cur.line + offsetLine, cur.ch + offsetCh); } function getOffset(anchor, head) { return { line: head.line - anchor.line, ch: head.line - anchor.line }; } function commandMatches(keys, keyMap, context, inputState) { // Partial matches are not applied. They inform the key handler // that the current key sequence is a subsequence of a valid key // sequence, so that the key buffer is not cleared. var match, partial = [], full = []; for (var i = 0; i < keyMap.length; i++) { var command = keyMap[i]; if (context == 'insert' && command.context != 'insert' || command.context && command.context != context || inputState.operator && command.type == 'action' || !(match = commandMatch(keys, command.keys))) { continue; } if (match == 'partial') { partial.push(command); } if (match == 'full') { full.push(command); } } return { partial: partial.length && partial, full: full.length && full }; } function commandMatch(pressed, mapped) { if (mapped.slice(-11) == '') { // Last character matches anything. var prefixLen = mapped.length - 11; var pressedPrefix = pressed.slice(0, prefixLen); var mappedPrefix = mapped.slice(0, prefixLen); return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' : mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false; } else { return pressed == mapped ? 'full' : mapped.indexOf(pressed) == 0 ? 'partial' : false; } } function lastChar(keys) { var match = /^.*(<[^>]+>)$/.exec(keys); var selectedCharacter = match ? match[1] : keys.slice(-1); if (selectedCharacter.length > 1){ switch(selectedCharacter){ case '': selectedCharacter='\n'; break; case '': selectedCharacter=' '; break; default: selectedCharacter=''; break; } } return selectedCharacter; } function repeatFn(cm, fn, repeat) { return function() { for (var i = 0; i < repeat; i++) { fn(cm); } }; } function copyCursor(cur) { return Pos(cur.line, cur.ch); } function cursorEqual(cur1, cur2) { return cur1.ch == cur2.ch && cur1.line == cur2.line; } function cursorIsBefore(cur1, cur2) { if (cur1.line < cur2.line) { return true; } if (cur1.line == cur2.line && cur1.ch < cur2.ch) { return true; } return false; } function cursorMin(cur1, cur2) { if (arguments.length > 2) { cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1)); } return cursorIsBefore(cur1, cur2) ? cur1 : cur2; } function cursorMax(cur1, cur2) { if (arguments.length > 2) { cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1)); } return cursorIsBefore(cur1, cur2) ? cur2 : cur1; } function cursorIsBetween(cur1, cur2, cur3) { // returns true if cur2 is between cur1 and cur3. var cur1before2 = cursorIsBefore(cur1, cur2); var cur2before3 = cursorIsBefore(cur2, cur3); return cur1before2 && cur2before3; } function lineLength(cm, lineNum) { return cm.getLine(lineNum).length; } function trim(s) { if (s.trim) { return s.trim(); } return s.replace(/^\s+|\s+$/g, ''); } function escapeRegex(s) { return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1'); } function extendLineToColumn(cm, lineNum, column) { var endCh = lineLength(cm, lineNum); var spaces = new Array(column-endCh+1).join(' '); cm.setCursor(Pos(lineNum, endCh)); cm.replaceRange(spaces, cm.getCursor()); } // This functions selects a rectangular block // of text with selectionEnd as any of its corner // Height of block: // Difference in selectionEnd.line and first/last selection.line // Width of the block: // Distance between selectionEnd.ch and any(first considered here) selection.ch function selectBlock(cm, selectionEnd) { var selections = [], ranges = cm.listSelections(); var head = copyCursor(cm.clipPos(selectionEnd)); var isClipped = !cursorEqual(selectionEnd, head); var curHead = cm.getCursor('head'); var primIndex = getIndex(ranges, curHead); var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor); var max = ranges.length - 1; var index = max - primIndex > primIndex ? max : 0; var base = ranges[index].anchor; var firstLine = Math.min(base.line, head.line); var lastLine = Math.max(base.line, head.line); var baseCh = base.ch, headCh = head.ch; var dir = ranges[index].head.ch - baseCh; var newDir = headCh - baseCh; if (dir > 0 && newDir <= 0) { baseCh++; if (!isClipped) { headCh--; } } else if (dir < 0 && newDir >= 0) { baseCh--; if (!wasClipped) { headCh++; } } else if (dir < 0 && newDir == -1) { baseCh--; headCh++; } for (var line = firstLine; line <= lastLine; line++) { var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)}; selections.push(range); } cm.setSelections(selections); selectionEnd.ch = headCh; base.ch = baseCh; return base; } function selectForInsert(cm, head, height) { var sel = []; for (var i = 0; i < height; i++) { var lineHead = offsetCursor(head, i, 0); sel.push({anchor: lineHead, head: lineHead}); } cm.setSelections(sel, 0); } // getIndex returns the index of the cursor in the selections. function getIndex(ranges, cursor, end) { for (var i = 0; i < ranges.length; i++) { var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor); var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor); if (atAnchor || atHead) { return i; } } return -1; } function getSelectedAreaRange(cm, vim) { var lastSelection = vim.lastSelection; var getCurrentSelectedAreaRange = function() { var selections = cm.listSelections(); var start = selections[0]; var end = selections[selections.length-1]; var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head; var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor; return [selectionStart, selectionEnd]; }; var getLastSelectedAreaRange = function() { var selectionStart = cm.getCursor(); var selectionEnd = cm.getCursor(); var block = lastSelection.visualBlock; if (block) { var width = block.width; var height = block.height; selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width); var selections = []; // selectBlock creates a 'proper' rectangular block. // We do not want that in all cases, so we manually set selections. for (var i = selectionStart.line; i < selectionEnd.line; i++) { var anchor = Pos(i, selectionStart.ch); var head = Pos(i, selectionEnd.ch); var range = {anchor: anchor, head: head}; selections.push(range); } cm.setSelections(selections); } else { var start = lastSelection.anchorMark.find(); var end = lastSelection.headMark.find(); var line = end.line - start.line; var ch = end.ch - start.ch; selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch}; if (lastSelection.visualLine) { selectionStart = Pos(selectionStart.line, 0); selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line)); } cm.setSelection(selectionStart, selectionEnd); } return [selectionStart, selectionEnd]; }; if (!vim.visualMode) { // In case of replaying the action. return getLastSelectedAreaRange(); } else { return getCurrentSelectedAreaRange(); } } // Updates the previous selection with the current selection's values. This // should only be called in visual mode. function updateLastSelection(cm, vim) { var anchor = vim.sel.anchor; var head = vim.sel.head; // To accommodate the effect of lastPastedText in the last selection if (vim.lastPastedText) { head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length); vim.lastPastedText = null; } vim.lastSelection = {'anchorMark': cm.setBookmark(anchor), 'headMark': cm.setBookmark(head), 'anchor': copyCursor(anchor), 'head': copyCursor(head), 'visualMode': vim.visualMode, 'visualLine': vim.visualLine, 'visualBlock': vim.visualBlock}; } function expandSelection(cm, start, end) { var sel = cm.state.vim.sel; var head = sel.head; var anchor = sel.anchor; var tmp; if (cursorIsBefore(end, start)) { tmp = end; end = start; start = tmp; } if (cursorIsBefore(head, anchor)) { head = cursorMin(start, head); anchor = cursorMax(anchor, end); } else { anchor = cursorMin(start, anchor); head = cursorMax(head, end); head = offsetCursor(head, 0, -1); if (head.ch == -1 && head.line != cm.firstLine()) { head = Pos(head.line - 1, lineLength(cm, head.line - 1)); } } return [anchor, head]; } /** * Updates the CodeMirror selection to match the provided vim selection. * If no arguments are given, it uses the current vim selection state. */ function updateCmSelection(cm, sel, mode) { var vim = cm.state.vim; sel = sel || vim.sel; var mode = mode || vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char'; var cmSel = makeCmSelection(cm, sel, mode); cm.setSelections(cmSel.ranges, cmSel.primary); updateFakeCursor(cm); } function makeCmSelection(cm, sel, mode, exclusive) { var head = copyCursor(sel.head); var anchor = copyCursor(sel.anchor); if (mode == 'char') { var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0; head = offsetCursor(sel.head, 0, headOffset); anchor = offsetCursor(sel.anchor, 0, anchorOffset); return { ranges: [{anchor: anchor, head: head}], primary: 0 }; } else if (mode == 'line') { if (!cursorIsBefore(sel.head, sel.anchor)) { anchor.ch = 0; var lastLine = cm.lastLine(); if (head.line > lastLine) { head.line = lastLine; } head.ch = lineLength(cm, head.line); } else { head.ch = 0; anchor.ch = lineLength(cm, anchor.line); } return { ranges: [{anchor: anchor, head: head}], primary: 0 }; } else if (mode == 'block') { var top = Math.min(anchor.line, head.line), left = Math.min(anchor.ch, head.ch), bottom = Math.max(anchor.line, head.line), right = Math.max(anchor.ch, head.ch) + 1; var height = bottom - top + 1; var primary = head.line == top ? 0 : height - 1; var ranges = []; for (var i = 0; i < height; i++) { ranges.push({ anchor: Pos(top + i, left), head: Pos(top + i, right) }); } return { ranges: ranges, primary: primary }; } } function getHead(cm) { var cur = cm.getCursor('head'); if (cm.getSelection().length == 1) { // Small corner case when only 1 character is selected. The "real" // head is the left of head and anchor. cur = cursorMin(cur, cm.getCursor('anchor')); } return cur; } /** * If moveHead is set to false, the CodeMirror selection will not be * touched. The caller assumes the responsibility of putting the cursor * in the right place. */ function exitVisualMode(cm, moveHead) { var vim = cm.state.vim; if (moveHead !== false) { cm.setCursor(clipCursorToContent(cm, vim.sel.head)); } updateLastSelection(cm, vim); vim.visualMode = false; vim.visualLine = false; vim.visualBlock = false; CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); if (vim.fakeCursor) { vim.fakeCursor.clear(); } } // Remove any trailing newlines from the selection. For // example, with the caret at the start of the last word on the line, // 'dw' should word, but not the newline, while 'w' should advance the // caret to the first character of the next line. function clipToLine(cm, curStart, curEnd) { var selection = cm.getRange(curStart, curEnd); // Only clip if the selection ends with trailing newline + whitespace if (/\n\s*$/.test(selection)) { var lines = selection.split('\n'); // We know this is all whitespace. lines.pop(); // Cases: // 1. Last word is an empty line - do not clip the trailing '\n' // 2. Last word is not an empty line - clip the trailing '\n' var line; // Find the line containing the last word, and clip all whitespace up // to it. for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) { curEnd.line--; curEnd.ch = 0; } // If the last word is not an empty line, clip an additional newline if (line) { curEnd.line--; curEnd.ch = lineLength(cm, curEnd.line); } else { curEnd.ch = 0; } } } // Expand the selection to line ends. function expandSelectionToLine(_cm, curStart, curEnd) { curStart.ch = 0; curEnd.ch = 0; curEnd.line++; } function findFirstNonWhiteSpaceCharacter(text) { if (!text) { return 0; } var firstNonWS = text.search(/\S/); return firstNonWS == -1 ? text.length : firstNonWS; } function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) { var cur = getHead(cm); var line = cm.getLine(cur.line); var idx = cur.ch; // Seek to first word or non-whitespace character, depending on if // noSymbol is true. var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0]; while (!test(line.charAt(idx))) { idx++; if (idx >= line.length) { return null; } } if (bigWord) { test = bigWordCharTest[0]; } else { test = wordCharTest[0]; if (!test(line.charAt(idx))) { test = wordCharTest[1]; } } var end = idx, start = idx; while (test(line.charAt(end)) && end < line.length) { end++; } while (test(line.charAt(start)) && start >= 0) { start--; } start++; if (inclusive) { // If present, include all whitespace after word. // Otherwise, include all whitespace before word, except indentation. var wordEnd = end; while (/\s/.test(line.charAt(end)) && end < line.length) { end++; } if (wordEnd == end) { var wordStart = start; while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; } if (!start) { start = wordStart; } } } return { start: Pos(cur.line, start), end: Pos(cur.line, end) }; } function recordJumpPosition(cm, oldCur, newCur) { if (!cursorEqual(oldCur, newCur)) { vimGlobalState.jumpList.add(cm, oldCur, newCur); } } function recordLastCharacterSearch(increment, args) { vimGlobalState.lastCharacterSearch.increment = increment; vimGlobalState.lastCharacterSearch.forward = args.forward; vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter; } var symbolToMode = { '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket', '[': 'section', ']': 'section', '*': 'comment', '/': 'comment', 'm': 'method', 'M': 'method', '#': 'preprocess' }; var findSymbolModes = { bracket: { isComplete: function(state) { if (state.nextCh === state.symb) { state.depth++; if (state.depth >= 1)return true; } else if (state.nextCh === state.reverseSymb) { state.depth--; } return false; } }, section: { init: function(state) { state.curMoveThrough = true; state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}'; }, isComplete: function(state) { return state.index === 0 && state.nextCh === state.symb; } }, comment: { isComplete: function(state) { var found = state.lastCh === '*' && state.nextCh === '/'; state.lastCh = state.nextCh; return found; } }, // TODO: The original Vim implementation only operates on level 1 and 2. // The current implementation doesn't check for code block level and // therefore it operates on any levels. method: { init: function(state) { state.symb = (state.symb === 'm' ? '{' : '}'); state.reverseSymb = state.symb === '{' ? '}' : '{'; }, isComplete: function(state) { if (state.nextCh === state.symb)return true; return false; } }, preprocess: { init: function(state) { state.index = 0; }, isComplete: function(state) { if (state.nextCh === '#') { var token = state.lineText.match(/#(\w+)/)[1]; if (token === 'endif') { if (state.forward && state.depth === 0) { return true; } state.depth++; } else if (token === 'if') { if (!state.forward && state.depth === 0) { return true; } state.depth--; } if (token === 'else' && state.depth === 0)return true; } return false; } } }; function findSymbol(cm, repeat, forward, symb) { var cur = copyCursor(cm.getCursor()); var increment = forward ? 1 : -1; var endLine = forward ? cm.lineCount() : -1; var curCh = cur.ch; var line = cur.line; var lineText = cm.getLine(line); var state = { lineText: lineText, nextCh: lineText.charAt(curCh), lastCh: null, index: curCh, symb: symb, reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb], forward: forward, depth: 0, curMoveThrough: false }; var mode = symbolToMode[symb]; if (!mode)return cur; var init = findSymbolModes[mode].init; var isComplete = findSymbolModes[mode].isComplete; if (init) { init(state); } while (line !== endLine && repeat) { state.index += increment; state.nextCh = state.lineText.charAt(state.index); if (!state.nextCh) { line += increment; state.lineText = cm.getLine(line) || ''; if (increment > 0) { state.index = 0; } else { var lineLen = state.lineText.length; state.index = (lineLen > 0) ? (lineLen-1) : 0; } state.nextCh = state.lineText.charAt(state.index); } if (isComplete(state)) { cur.line = line; cur.ch = state.index; repeat--; } } if (state.nextCh || state.curMoveThrough) { return Pos(line, state.index); } return cur; } /* * Returns the boundaries of the next word. If the cursor in the middle of * the word, then returns the boundaries of the current word, starting at * the cursor. If the cursor is at the start/end of a word, and we are going * forward/backward, respectively, find the boundaries of the next word. * * @param {CodeMirror} cm CodeMirror object. * @param {Cursor} cur The cursor position. * @param {boolean} forward True to search forward. False to search * backward. * @param {boolean} bigWord True if punctuation count as part of the word. * False if only [a-zA-Z0-9] characters count as part of the word. * @param {boolean} emptyLineIsWord True if empty lines should be treated * as words. * @return {Object{from:number, to:number, line: number}} The boundaries of * the word, or null if there are no more words. */ function findWord(cm, cur, forward, bigWord, emptyLineIsWord) { var lineNum = cur.line; var pos = cur.ch; var line = cm.getLine(lineNum); var dir = forward ? 1 : -1; var charTests = bigWord ? bigWordCharTest: wordCharTest; if (emptyLineIsWord && line == '') { lineNum += dir; line = cm.getLine(lineNum); if (!isLine(cm, lineNum)) { return null; } pos = (forward) ? 0 : line.length; } while (true) { if (emptyLineIsWord && line == '') { return { from: 0, to: 0, line: lineNum }; } var stop = (dir > 0) ? line.length : -1; var wordStart = stop, wordEnd = stop; // Find bounds of next word. while (pos != stop) { var foundWord = false; for (var i = 0; i < charTests.length && !foundWord; ++i) { if (charTests[i](line.charAt(pos))) { wordStart = pos; // Advance to end of word. while (pos != stop && charTests[i](line.charAt(pos))) { pos += dir; } wordEnd = pos; foundWord = wordStart != wordEnd; if (wordStart == cur.ch && lineNum == cur.line && wordEnd == wordStart + dir) { // We started at the end of a word. Find the next one. continue; } else { return { from: Math.min(wordStart, wordEnd + 1), to: Math.max(wordStart, wordEnd), line: lineNum }; } } } if (!foundWord) { pos += dir; } } // Advance to next/prev line. lineNum += dir; if (!isLine(cm, lineNum)) { return null; } line = cm.getLine(lineNum); pos = (dir > 0) ? 0 : line.length; } } /** * @param {CodeMirror} cm CodeMirror object. * @param {Pos} cur The position to start from. * @param {int} repeat Number of words to move past. * @param {boolean} forward True to search forward. False to search * backward. * @param {boolean} wordEnd True to move to end of word. False to move to * beginning of word. * @param {boolean} bigWord True if punctuation count as part of the word. * False if only alphabet characters count as part of the word. * @return {Cursor} The position the cursor should move to. */ function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) { var curStart = copyCursor(cur); var words = []; if (forward && !wordEnd || !forward && wordEnd) { repeat++; } // For 'e', empty lines are not considered words, go figure. var emptyLineIsWord = !(forward && wordEnd); for (var i = 0; i < repeat; i++) { var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord); if (!word) { var eodCh = lineLength(cm, cm.lastLine()); words.push(forward ? {line: cm.lastLine(), from: eodCh, to: eodCh} : {line: 0, from: 0, to: 0}); break; } words.push(word); cur = Pos(word.line, forward ? (word.to - 1) : word.from); } var shortCircuit = words.length != repeat; var firstWord = words[0]; var lastWord = words.pop(); if (forward && !wordEnd) { // w if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) { // We did not start in the middle of a word. Discard the extra word at the end. lastWord = words.pop(); } return Pos(lastWord.line, lastWord.from); } else if (forward && wordEnd) { return Pos(lastWord.line, lastWord.to - 1); } else if (!forward && wordEnd) { // ge if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) { // We did not start in the middle of a word. Discard the extra word at the end. lastWord = words.pop(); } return Pos(lastWord.line, lastWord.to); } else { // b return Pos(lastWord.line, lastWord.from); } } function moveToCharacter(cm, repeat, forward, character) { var cur = cm.getCursor(); var start = cur.ch; var idx; for (var i = 0; i < repeat; i ++) { var line = cm.getLine(cur.line); idx = charIdxInLine(start, line, character, forward, true); if (idx == -1) { return null; } start = idx; } return Pos(cm.getCursor().line, idx); } function moveToColumn(cm, repeat) { // repeat is always >= 1, so repeat - 1 always corresponds // to the column we want to go to. var line = cm.getCursor().line; return clipCursorToContent(cm, Pos(line, repeat - 1)); } function updateMark(cm, vim, markName, pos) { if (!inArray(markName, validMarks)) { return; } if (vim.marks[markName]) { vim.marks[markName].clear(); } vim.marks[markName] = cm.setBookmark(pos); } function charIdxInLine(start, line, character, forward, includeChar) { // Search for char in line. // motion_options: {forward, includeChar} // If includeChar = true, include it too. // If forward = true, search forward, else search backwards. // If char is not found on this line, do nothing var idx; if (forward) { idx = line.indexOf(character, start + 1); if (idx != -1 && !includeChar) { idx -= 1; } } else { idx = line.lastIndexOf(character, start - 1); if (idx != -1 && !includeChar) { idx += 1; } } return idx; } function findParagraph(cm, head, repeat, dir, inclusive) { var line = head.line; var min = cm.firstLine(); var max = cm.lastLine(); var start, end, i = line; function isEmpty(i) { return !cm.getLine(i); } function isBoundary(i, dir, any) { if (any) { return isEmpty(i) != isEmpty(i + dir); } return !isEmpty(i) && isEmpty(i + dir); } if (dir) { while (min <= i && i <= max && repeat > 0) { if (isBoundary(i, dir)) { repeat--; } i += dir; } return new Pos(i, 0); } var vim = cm.state.vim; if (vim.visualLine && isBoundary(line, 1, true)) { var anchor = vim.sel.anchor; if (isBoundary(anchor.line, -1, true)) { if (!inclusive || anchor.line != line) { line += 1; } } } var startState = isEmpty(line); for (i = line; i <= max && repeat; i++) { if (isBoundary(i, 1, true)) { if (!inclusive || isEmpty(i) != startState) { repeat--; } } } end = new Pos(i, 0); // select boundary before paragraph for the last one if (i > max && !startState) { startState = true; } else { inclusive = false; } for (i = line; i > min; i--) { if (!inclusive || isEmpty(i) == startState || i == line) { if (isBoundary(i, -1, true)) { break; } } } start = new Pos(i, 0); return { start: start, end: end }; } function findSentence(cm, cur, repeat, dir) { /* Takes an index object { line: the line string, ln: line number, pos: index in line, dir: direction of traversal (-1 or 1) } and modifies the line, ln, and pos members to represent the next valid position or sets them to null if there are no more valid positions. */ function nextChar(cm, idx) { if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) { idx.ln += idx.dir; if (!isLine(cm, idx.ln)) { idx.line = null; idx.ln = null; idx.pos = null; return; } idx.line = cm.getLine(idx.ln); idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1; } else { idx.pos += idx.dir; } } /* Performs one iteration of traversal in forward direction Returns an index object of the new location */ function forward(cm, ln, pos, dir) { var line = cm.getLine(ln); var stop = (line === ""); var curr = { line: line, ln: ln, pos: pos, dir: dir, } var last_valid = { ln: curr.ln, pos: curr.pos, } var skip_empty_lines = (curr.line === ""); // Move one step to skip character we start on nextChar(cm, curr); while (curr.line !== null) { last_valid.ln = curr.ln; last_valid.pos = curr.pos; if (curr.line === "" && !skip_empty_lines) { return { ln: curr.ln, pos: curr.pos, }; } else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) { return { ln: curr.ln, pos: curr.pos, }; } else if (isEndOfSentenceSymbol(curr.line[curr.pos]) && !stop && (curr.pos === curr.line.length - 1 || isWhiteSpaceString(curr.line[curr.pos + 1]))) { stop = true; } nextChar(cm, curr); } /* Set the position to the last non whitespace character on the last valid line in the case that we reach the end of the document. */ var line = cm.getLine(last_valid.ln); last_valid.pos = 0; for(var i = line.length - 1; i >= 0; --i) { if (!isWhiteSpaceString(line[i])) { last_valid.pos = i; break; } } return last_valid; } /* Performs one iteration of traversal in reverse direction Returns an index object of the new location */ function reverse(cm, ln, pos, dir) { var line = cm.getLine(ln); var curr = { line: line, ln: ln, pos: pos, dir: dir, } var last_valid = { ln: curr.ln, pos: null, }; var skip_empty_lines = (curr.line === ""); // Move one step to skip character we start on nextChar(cm, curr); while (curr.line !== null) { if (curr.line === "" && !skip_empty_lines) { if (last_valid.pos !== null) { return last_valid; } else { return { ln: curr.ln, pos: curr.pos }; } } else if (isEndOfSentenceSymbol(curr.line[curr.pos]) && last_valid.pos !== null && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) { return last_valid; } else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) { skip_empty_lines = false; last_valid = { ln: curr.ln, pos: curr.pos } } nextChar(cm, curr); } /* Set the position to the first non whitespace character on the last valid line in the case that we reach the beginning of the document. */ var line = cm.getLine(last_valid.ln); last_valid.pos = 0; for(var i = 0; i < line.length; ++i) { if (!isWhiteSpaceString(line[i])) { last_valid.pos = i; break; } } return last_valid; } var curr_index = { ln: cur.line, pos: cur.ch, }; while (repeat > 0) { if (dir < 0) { curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir); } else { curr_index = forward(cm, curr_index.ln, curr_index.pos, dir); } repeat--; } return Pos(curr_index.ln, curr_index.pos); } // TODO: perhaps this finagling of start and end positions belonds // in codemirror/replaceRange? function selectCompanionObject(cm, head, symb, inclusive) { var cur = head, start, end; var bracketRegexp = ({ '(': /[()]/, ')': /[()]/, '[': /[[\]]/, ']': /[[\]]/, '{': /[{}]/, '}': /[{}]/, '<': /[<>]/, '>': /[<>]/})[symb]; var openSym = ({ '(': '(', ')': '(', '[': '[', ']': '[', '{': '{', '}': '{', '<': '<', '>': '<'})[symb]; var curChar = cm.getLine(cur.line).charAt(cur.ch); // Due to the behavior of scanForBracket, we need to add an offset if the // cursor is on a matching open bracket. var offset = curChar === openSym ? 1 : 0; start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp}); end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp}); if (!start || !end) { return { start: cur, end: cur }; } start = start.pos; end = end.pos; if ((start.line == end.line && start.ch > end.ch) || (start.line > end.line)) { var tmp = start; start = end; end = tmp; } if (inclusive) { end.ch += 1; } else { start.ch += 1; } return { start: start, end: end }; } // Takes in a symbol and a cursor and tries to simulate text objects that // have identical opening and closing symbols // TODO support across multiple lines function findBeginningAndEnd(cm, head, symb, inclusive) { var cur = copyCursor(head); var line = cm.getLine(cur.line); var chars = line.split(''); var start, end, i, len; var firstIndex = chars.indexOf(symb); // the decision tree is to always look backwards for the beginning first, // but if the cursor is in front of the first instance of the symb, // then move the cursor forward if (cur.ch < firstIndex) { cur.ch = firstIndex; // Why is this line even here??? // cm.setCursor(cur.line, firstIndex+1); } // otherwise if the cursor is currently on the closing symbol else if (firstIndex < cur.ch && chars[cur.ch] == symb) { end = cur.ch; // assign end to the current cursor --cur.ch; // make sure to look backwards } // if we're currently on the symbol, we've got a start if (chars[cur.ch] == symb && !end) { start = cur.ch + 1; // assign start to ahead of the cursor } else { // go backwards to find the start for (i = cur.ch; i > -1 && !start; i--) { if (chars[i] == symb) { start = i + 1; } } } // look forwards for the end symbol if (start && !end) { for (i = start, len = chars.length; i < len && !end; i++) { if (chars[i] == symb) { end = i; } } } // nothing found if (!start || !end) { return { start: cur, end: cur }; } // include the symbols if (inclusive) { --start; ++end; } return { start: Pos(cur.line, start), end: Pos(cur.line, end) }; } // Search functions defineOption('pcre', true, 'boolean'); function SearchState() {} SearchState.prototype = { getQuery: function() { return vimGlobalState.query; }, setQuery: function(query) { vimGlobalState.query = query; }, getOverlay: function() { return this.searchOverlay; }, setOverlay: function(overlay) { this.searchOverlay = overlay; }, isReversed: function() { return vimGlobalState.isReversed; }, setReversed: function(reversed) { vimGlobalState.isReversed = reversed; }, getScrollbarAnnotate: function() { return this.annotate; }, setScrollbarAnnotate: function(annotate) { this.annotate = annotate; } }; function getSearchState(cm) { var vim = cm.state.vim; return vim.searchState_ || (vim.searchState_ = new SearchState()); } function dialog(cm, template, shortText, onClose, options) { if (cm.openDialog) { cm.openDialog(template, onClose, { bottom: true, value: options.value, onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp, selectValueOnOpen: false}); } else { onClose(prompt(shortText, '')); } } function splitBySlash(argString) { return splitBySeparator(argString, '/'); } function findUnescapedSlashes(argString) { return findUnescapedSeparators(argString, '/'); } function splitBySeparator(argString, separator) { var slashes = findUnescapedSeparators(argString, separator) || []; if (!slashes.length) return []; var tokens = []; // in case of strings like foo/bar if (slashes[0] !== 0) return; for (var i = 0; i < slashes.length; i++) { if (typeof slashes[i] == 'number') tokens.push(argString.substring(slashes[i] + 1, slashes[i+1])); } return tokens; } function findUnescapedSeparators(str, separator) { if (!separator) separator = '/'; var escapeNextChar = false; var slashes = []; for (var i = 0; i < str.length; i++) { var c = str.charAt(i); if (!escapeNextChar && c == separator) { slashes.push(i); } escapeNextChar = !escapeNextChar && (c == '\\'); } return slashes; } // Translates a search string from ex (vim) syntax into javascript form. function translateRegex(str) { // When these match, add a '\' if unescaped or remove one if escaped. var specials = '|(){'; // Remove, but never add, a '\' for these. var unescape = '}'; var escapeNextChar = false; var out = []; for (var i = -1; i < str.length; i++) { var c = str.charAt(i) || ''; var n = str.charAt(i+1) || ''; var specialComesNext = (n && specials.indexOf(n) != -1); if (escapeNextChar) { if (c !== '\\' || !specialComesNext) { out.push(c); } escapeNextChar = false; } else { if (c === '\\') { escapeNextChar = true; // Treat the unescape list as special for removing, but not adding '\'. if (n && unescape.indexOf(n) != -1) { specialComesNext = true; } // Not passing this test means removing a '\'. if (!specialComesNext || n === '\\') { out.push(c); } } else { out.push(c); if (specialComesNext && n !== '\\') { out.push('\\'); } } } } return out.join(''); } // Translates the replace part of a search and replace from ex (vim) syntax into // javascript form. Similar to translateRegex, but additionally fixes back references // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'. var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'}; function translateRegexReplace(str) { var escapeNextChar = false; var out = []; for (var i = -1; i < str.length; i++) { var c = str.charAt(i) || ''; var n = str.charAt(i+1) || ''; if (charUnescapes[c + n]) { out.push(charUnescapes[c+n]); i++; } else if (escapeNextChar) { // At any point in the loop, escapeNextChar is true if the previous // character was a '\' and was not escaped. out.push(c); escapeNextChar = false; } else { if (c === '\\') { escapeNextChar = true; if ((isNumber(n) || n === '$')) { out.push('$'); } else if (n !== '/' && n !== '\\') { out.push('\\'); } } else { if (c === '$') { out.push('$'); } out.push(c); if (n === '/') { out.push('\\'); } } } } return out.join(''); } // Unescape \ and / in the replace part, for PCRE mode. var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t'}; function unescapeRegexReplace(str) { var stream = new CodeMirror.StringStream(str); var output = []; while (!stream.eol()) { // Search for \. while (stream.peek() && stream.peek() != '\\') { output.push(stream.next()); } var matched = false; for (var matcher in unescapes) { if (stream.match(matcher, true)) { matched = true; output.push(unescapes[matcher]); break; } } if (!matched) { // Don't change anything output.push(stream.next()); } } return output.join(''); } /** * Extract the regular expression from the query and return a Regexp object. * Returns null if the query is blank. * If ignoreCase is passed in, the Regexp object will have the 'i' flag set. * If smartCase is passed in, and the query contains upper case letters, * then ignoreCase is overridden, and the 'i' flag will not be set. * If the query contains the /i in the flag part of the regular expression, * then both ignoreCase and smartCase are ignored, and 'i' will be passed * through to the Regex object. */ function parseQuery(query, ignoreCase, smartCase) { // First update the last search register var lastSearchRegister = vimGlobalState.registerController.getRegister('/'); lastSearchRegister.setText(query); // Check if the query is already a regex. if (query instanceof RegExp) { return query; } // First try to extract regex + flags from the input. If no flags found, // extract just the regex. IE does not accept flags directly defined in // the regex string in the form /regex/flags var slashes = findUnescapedSlashes(query); var regexPart; var forceIgnoreCase; if (!slashes.length) { // Query looks like 'regexp' regexPart = query; } else { // Query looks like 'regexp/...' regexPart = query.substring(0, slashes[0]); var flagsPart = query.substring(slashes[0]); forceIgnoreCase = (flagsPart.indexOf('i') != -1); } if (!regexPart) { return null; } if (!getOption('pcre')) { regexPart = translateRegex(regexPart); } if (smartCase) { ignoreCase = (/^[^A-Z]*$/).test(regexPart); } var regexp = new RegExp(regexPart, (ignoreCase || forceIgnoreCase) ? 'i' : undefined); return regexp; } function showConfirm(cm, text) { if (cm.openNotification) { cm.openNotification('' + text + '', {bottom: true, duration: 5000}); } else { alert(text); } } function makePrompt(prefix, desc) { var raw = '' + (prefix || "") + ''; if (desc) raw += ' ' + desc + ''; return raw; } var searchPromptDesc = '(Javascript regexp)'; function showPrompt(cm, options) { var shortText = (options.prefix || '') + ' ' + (options.desc || ''); var prompt = makePrompt(options.prefix, options.desc); dialog(cm, prompt, shortText, options.onClose, options); } function regexEqual(r1, r2) { if (r1 instanceof RegExp && r2 instanceof RegExp) { var props = ['global', 'multiline', 'ignoreCase', 'source']; for (var i = 0; i < props.length; i++) { var prop = props[i]; if (r1[prop] !== r2[prop]) { return false; } } return true; } return false; } // Returns true if the query is valid. function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { if (!rawQuery) { return; } var state = getSearchState(cm); var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase); if (!query) { return; } highlightSearchMatches(cm, query); if (regexEqual(query, state.getQuery())) { return query; } state.setQuery(query); return query; } function searchOverlay(query) { if (query.source.charAt(0) == '^') { var matchSol = true; } return { token: function(stream) { if (matchSol && !stream.sol()) { stream.skipToEnd(); return; } var match = stream.match(query, false); if (match) { if (match[0].length == 0) { // Matched empty string, skip to next. stream.next(); return 'searching'; } if (!stream.sol()) { // Backtrack 1 to match \b stream.backUp(1); if (!query.exec(stream.next() + match[0])) { stream.next(); return null; } } stream.match(query); return 'searching'; } while (!stream.eol()) { stream.next(); if (stream.match(query, false)) break; } }, query: query }; } function highlightSearchMatches(cm, query) { var searchState = getSearchState(cm); var overlay = searchState.getOverlay(); if (!overlay || query != overlay.query) { if (overlay) { cm.removeOverlay(overlay); } overlay = searchOverlay(query); cm.addOverlay(overlay); if (cm.showMatchesOnScrollbar) { if (searchState.getScrollbarAnnotate()) { searchState.getScrollbarAnnotate().clear(); } searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query)); } searchState.setOverlay(overlay); } } function findNext(cm, prev, query, repeat) { if (repeat === undefined) { repeat = 1; } return cm.operation(function() { var pos = cm.getCursor(); var cursor = cm.getSearchCursor(query, pos); for (var i = 0; i < repeat; i++) { var found = cursor.find(prev); if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); } if (!found) { // SearchCursor may have returned null because it hit EOF, wrap // around and try again. cursor = cm.getSearchCursor(query, (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) ); if (!cursor.find(prev)) { return; } } } return cursor.from(); }); } function clearSearchHighlight(cm) { var state = getSearchState(cm); cm.removeOverlay(getSearchState(cm).getOverlay()); state.setOverlay(null); if (state.getScrollbarAnnotate()) { state.getScrollbarAnnotate().clear(); state.setScrollbarAnnotate(null); } } /** * Check if pos is in the specified range, INCLUSIVE. * Range can be specified with 1 or 2 arguments. * If the first range argument is an array, treat it as an array of line * numbers. Match pos against any of the lines. * If the first range argument is a number, * if there is only 1 range argument, check if pos has the same line * number * if there are 2 range arguments, then check if pos is in between the two * range arguments. */ function isInRange(pos, start, end) { if (typeof pos != 'number') { // Assume it is a cursor position. Get the line number. pos = pos.line; } if (start instanceof Array) { return inArray(pos, start); } else { if (end) { return (pos >= start && pos <= end); } else { return pos == start; } } } function getUserVisibleLines(cm) { var scrollInfo = cm.getScrollInfo(); var occludeToleranceTop = 6; var occludeToleranceBottom = 10; var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local'); var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top; var to = cm.coordsChar({left:0, top: bottomY}, 'local'); return {top: from.line, bottom: to.line}; } function getMarkPos(cm, vim, markName) { if (markName == '\'') { var history = cm.doc.history.done; var event = history[history.length - 2]; return event && event.ranges && event.ranges[0].head; } else if (markName == '.') { if (cm.doc.history.lastModTime == 0) { return // If no changes, bail out; don't bother to copy or reverse history array. } else { var changeHistory = cm.doc.history.done.filter(function(el){ if (el.changes !== undefined) { return el } }); changeHistory.reverse(); var lastEditPos = changeHistory[0].changes[0].to; } return lastEditPos; } var mark = vim.marks[markName]; return mark && mark.find(); } var ExCommandDispatcher = function() { this.buildCommandMap_(); }; ExCommandDispatcher.prototype = { processCommand: function(cm, input, opt_params) { var that = this; cm.operation(function () { cm.curOp.isVimOp = true; that._processCommand(cm, input, opt_params); }); }, _processCommand: function(cm, input, opt_params) { var vim = cm.state.vim; var commandHistoryRegister = vimGlobalState.registerController.getRegister(':'); var previousCommand = commandHistoryRegister.toString(); if (vim.visualMode) { exitVisualMode(cm); } var inputStream = new CodeMirror.StringStream(input); // update ": with the latest command whether valid or invalid commandHistoryRegister.setText(input); var params = opt_params || {}; params.input = input; try { this.parseInput_(cm, inputStream, params); } catch(e) { showConfirm(cm, e); throw e; } var command; var commandName; if (!params.commandName) { // If only a line range is defined, move to the line. if (params.line !== undefined) { commandName = 'move'; } } else { command = this.matchCommand_(params.commandName); if (command) { commandName = command.name; if (command.excludeFromCommandHistory) { commandHistoryRegister.setText(previousCommand); } this.parseCommandArgs_(inputStream, params, command); if (command.type == 'exToKey') { // Handle Ex to Key mapping. for (var i = 0; i < command.toKeys.length; i++) { CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping'); } return; } else if (command.type == 'exToEx') { // Handle Ex to Ex mapping. this.processCommand(cm, command.toInput); return; } } } if (!commandName) { showConfirm(cm, 'Not an editor command ":' + input + '"'); return; } try { exCommands[commandName](cm, params); // Possibly asynchronous commands (e.g. substitute, which might have a // user confirmation), are responsible for calling the callback when // done. All others have it taken care of for them here. if ((!command || !command.possiblyAsync) && params.callback) { params.callback(); } } catch(e) { showConfirm(cm, e); throw e; } }, parseInput_: function(cm, inputStream, result) { inputStream.eatWhile(':'); // Parse range. if (inputStream.eat('%')) { result.line = cm.firstLine(); result.lineEnd = cm.lastLine(); } else { result.line = this.parseLineSpec_(cm, inputStream); if (result.line !== undefined && inputStream.eat(',')) { result.lineEnd = this.parseLineSpec_(cm, inputStream); } } // Parse command name. var commandMatch = inputStream.match(/^(\w+)/); if (commandMatch) { result.commandName = commandMatch[1]; } else { result.commandName = inputStream.match(/.*/)[0]; } return result; }, parseLineSpec_: function(cm, inputStream) { var numberMatch = inputStream.match(/^(\d+)/); if (numberMatch) { // Absolute line number plus offset (N+M or N-M) is probably a typo, // not something the user actually wanted. (NB: vim does allow this.) return parseInt(numberMatch[1], 10) - 1; } switch (inputStream.next()) { case '.': return this.parseLineSpecOffset_(inputStream, cm.getCursor().line); case '$': return this.parseLineSpecOffset_(inputStream, cm.lastLine()); case '\'': var markName = inputStream.next(); var markPos = getMarkPos(cm, cm.state.vim, markName); if (!markPos) throw new Error('Mark not set'); return this.parseLineSpecOffset_(inputStream, markPos.line); case '-': case '+': inputStream.backUp(1); // Offset is relative to current line if not otherwise specified. return this.parseLineSpecOffset_(inputStream, cm.getCursor().line); default: inputStream.backUp(1); return undefined; } }, parseLineSpecOffset_: function(inputStream, line) { var offsetMatch = inputStream.match(/^([+-])?(\d+)/); if (offsetMatch) { var offset = parseInt(offsetMatch[2], 10); if (offsetMatch[1] == "-") { line -= offset; } else { line += offset; } } return line; }, parseCommandArgs_: function(inputStream, params, command) { if (inputStream.eol()) { return; } params.argString = inputStream.match(/.*/)[0]; // Parse command-line arguments var delim = command.argDelimiter || /\s+/; var args = trim(params.argString).split(delim); if (args.length && args[0]) { params.args = args; } }, matchCommand_: function(commandName) { // Return the command in the command map that matches the shortest // prefix of the passed in command name. The match is guaranteed to be // unambiguous if the defaultExCommandMap's shortNames are set up // correctly. (see @code{defaultExCommandMap}). for (var i = commandName.length; i > 0; i--) { var prefix = commandName.substring(0, i); if (this.commandMap_[prefix]) { var command = this.commandMap_[prefix]; if (command.name.indexOf(commandName) === 0) { return command; } } } return null; }, buildCommandMap_: function() { this.commandMap_ = {}; for (var i = 0; i < defaultExCommandMap.length; i++) { var command = defaultExCommandMap[i]; var key = command.shortName || command.name; this.commandMap_[key] = command; } }, map: function(lhs, rhs, ctx) { if (lhs != ':' && lhs.charAt(0) == ':') { if (ctx) { throw Error('Mode not supported for ex mappings'); } var commandName = lhs.substring(1); if (rhs != ':' && rhs.charAt(0) == ':') { // Ex to Ex mapping this.commandMap_[commandName] = { name: commandName, type: 'exToEx', toInput: rhs.substring(1), user: true }; } else { // Ex to key mapping this.commandMap_[commandName] = { name: commandName, type: 'exToKey', toKeys: rhs, user: true }; } } else { if (rhs != ':' && rhs.charAt(0) == ':') { // Key to Ex mapping. var mapping = { keys: lhs, type: 'keyToEx', exArgs: { input: rhs.substring(1) } }; if (ctx) { mapping.context = ctx; } defaultKeymap.unshift(mapping); } else { // Key to key mapping var mapping = { keys: lhs, type: 'keyToKey', toKeys: rhs }; if (ctx) { mapping.context = ctx; } defaultKeymap.unshift(mapping); } } }, unmap: function(lhs, ctx) { if (lhs != ':' && lhs.charAt(0) == ':') { // Ex to Ex or Ex to key mapping if (ctx) { throw Error('Mode not supported for ex mappings'); } var commandName = lhs.substring(1); if (this.commandMap_[commandName] && this.commandMap_[commandName].user) { delete this.commandMap_[commandName]; return; } } else { // Key to Ex or key to key mapping var keys = lhs; for (var i = 0; i < defaultKeymap.length; i++) { if (keys == defaultKeymap[i].keys && defaultKeymap[i].context === ctx) { defaultKeymap.splice(i, 1); return; } } } throw Error('No such mapping.'); } }; var exCommands = { colorscheme: function(cm, params) { if (!params.args || params.args.length < 1) { showConfirm(cm, cm.getOption('theme')); return; } cm.setOption('theme', params.args[0]); }, map: function(cm, params, ctx) { var mapArgs = params.args; if (!mapArgs || mapArgs.length < 2) { if (cm) { showConfirm(cm, 'Invalid mapping: ' + params.input); } return; } exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx); }, imap: function(cm, params) { this.map(cm, params, 'insert'); }, nmap: function(cm, params) { this.map(cm, params, 'normal'); }, vmap: function(cm, params) { this.map(cm, params, 'visual'); }, unmap: function(cm, params, ctx) { var mapArgs = params.args; if (!mapArgs || mapArgs.length < 1) { if (cm) { showConfirm(cm, 'No such mapping: ' + params.input); } return; } exCommandDispatcher.unmap(mapArgs[0], ctx); }, move: function(cm, params) { commandDispatcher.processCommand(cm, cm.state.vim, { type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true }, repeatOverride: params.line+1}); }, set: function(cm, params) { var setArgs = params.args; // Options passed through to the setOption/getOption calls. May be passed in by the // local/global versions of the set command var setCfg = params.setCfg || {}; if (!setArgs || setArgs.length < 1) { if (cm) { showConfirm(cm, 'Invalid mapping: ' + params.input); } return; } var expr = setArgs[0].split('='); var optionName = expr[0]; var value = expr[1]; var forceGet = false; if (optionName.charAt(optionName.length - 1) == '?') { // If post-fixed with ?, then the set is actually a get. if (value) { throw Error('Trailing characters: ' + params.argString); } optionName = optionName.substring(0, optionName.length - 1); forceGet = true; } if (value === undefined && optionName.substring(0, 2) == 'no') { // To set boolean options to false, the option name is prefixed with // 'no'. optionName = optionName.substring(2); value = false; } var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean'; if (optionIsBoolean && value == undefined) { // Calling set with a boolean option sets it to true. value = true; } // If no value is provided, then we assume this is a get. if (!optionIsBoolean && value === undefined || forceGet) { var oldValue = getOption(optionName, cm, setCfg); if (oldValue instanceof Error) { showConfirm(cm, oldValue.message); } else if (oldValue === true || oldValue === false) { showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName); } else { showConfirm(cm, ' ' + optionName + '=' + oldValue); } } else { var setOptionReturn = setOption(optionName, value, cm, setCfg); if (setOptionReturn instanceof Error) { showConfirm(cm, setOptionReturn.message); } } }, setlocal: function (cm, params) { // setCfg is passed through to setOption params.setCfg = {scope: 'local'}; this.set(cm, params); }, setglobal: function (cm, params) { // setCfg is passed through to setOption params.setCfg = {scope: 'global'}; this.set(cm, params); }, registers: function(cm, params) { var regArgs = params.args; var registers = vimGlobalState.registerController.registers; var regInfo = '----------Registers----------

'; if (!regArgs) { for (var registerName in registers) { var text = registers[registerName].toString(); if (text.length) { regInfo += '"' + registerName + ' ' + text + '
'; } } } else { var registerName; regArgs = regArgs.join(''); for (var i = 0; i < regArgs.length; i++) { registerName = regArgs.charAt(i); if (!vimGlobalState.registerController.isValidRegister(registerName)) { continue; } var register = registers[registerName] || new Register(); regInfo += '"' + registerName + ' ' + register.toString() + '
'; } } showConfirm(cm, regInfo); }, sort: function(cm, params) { var reverse, ignoreCase, unique, number, pattern; function parseArgs() { if (params.argString) { var args = new CodeMirror.StringStream(params.argString); if (args.eat('!')) { reverse = true; } if (args.eol()) { return; } if (!args.eatSpace()) { return 'Invalid arguments'; } var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/); if (!opts && !args.eol()) { return 'Invalid arguments'; } if (opts[1]) { ignoreCase = opts[1].indexOf('i') != -1; unique = opts[1].indexOf('u') != -1; var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1; var hex = opts[1].indexOf('x') != -1 && 1; var octal = opts[1].indexOf('o') != -1 && 1; if (decimal + hex + octal > 1) { return 'Invalid arguments'; } number = decimal && 'decimal' || hex && 'hex' || octal && 'octal'; } if (opts[2]) { pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : ''); } } } var err = parseArgs(); if (err) { showConfirm(cm, err + ': ' + params.argString); return; } var lineStart = params.line || cm.firstLine(); var lineEnd = params.lineEnd || params.line || cm.lastLine(); if (lineStart == lineEnd) { return; } var curStart = Pos(lineStart, 0); var curEnd = Pos(lineEnd, lineLength(cm, lineEnd)); var text = cm.getRange(curStart, curEnd).split('\n'); var numberRegex = pattern ? pattern : (number == 'decimal') ? /(-?)([\d]+)/ : (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i : (number == 'octal') ? /([0-7]+)/ : null; var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null; var numPart = [], textPart = []; if (number || pattern) { for (var i = 0; i < text.length; i++) { var matchPart = pattern ? text[i].match(pattern) : null; if (matchPart && matchPart[0] != '') { numPart.push(matchPart); } else if (!pattern && numberRegex.exec(text[i])) { numPart.push(text[i]); } else { textPart.push(text[i]); } } } else { textPart = text; } function compareFn(a, b) { if (reverse) { var tmp; tmp = a; a = b; b = tmp; } if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); } var anum = number && numberRegex.exec(a); var bnum = number && numberRegex.exec(b); if (!anum) { return a < b ? -1 : 1; } anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix); bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix); return anum - bnum; } function comparePatternFn(a, b) { if (reverse) { var tmp; tmp = a; a = b; b = tmp; } if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); } return (a[0] < b[0]) ? -1 : 1; } numPart.sort(pattern ? comparePatternFn : compareFn); if (pattern) { for (var i = 0; i < numPart.length; i++) { numPart[i] = numPart[i].input; } } else if (!number) { textPart.sort(compareFn); } text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart); if (unique) { // Remove duplicate lines var textOld = text; var lastLine; text = []; for (var i = 0; i < textOld.length; i++) { if (textOld[i] != lastLine) { text.push(textOld[i]); } lastLine = textOld[i]; } } cm.replaceRange(text.join('\n'), curStart, curEnd); }, global: function(cm, params) { // a global command is of the form // :[range]g/pattern/[cmd] // argString holds the string /pattern/[cmd] var argString = params.argString; if (!argString) { showConfirm(cm, 'Regular Expression missing from global'); return; } // range is specified here var lineStart = (params.line !== undefined) ? params.line : cm.firstLine(); var lineEnd = params.lineEnd || params.line || cm.lastLine(); // get the tokens from argString var tokens = splitBySlash(argString); var regexPart = argString, cmd; if (tokens.length) { regexPart = tokens[0]; cmd = tokens.slice(1, tokens.length).join('/'); } if (regexPart) { // If regex part is empty, then use the previous query. Otherwise // use the regex part as the new query. try { updateSearchQuery(cm, regexPart, true /** ignoreCase */, true /** smartCase */); } catch (e) { showConfirm(cm, 'Invalid regex: ' + regexPart); return; } } // now that we have the regexPart, search for regex matches in the // specified range of lines var query = getSearchState(cm).getQuery(); var matchedLines = [], content = ''; for (var i = lineStart; i <= lineEnd; i++) { var matched = query.test(cm.getLine(i)); if (matched) { matchedLines.push(i+1); content+= cm.getLine(i) + '
'; } } // if there is no [cmd], just display the list of matched lines if (!cmd) { showConfirm(cm, content); return; } var index = 0; var nextCommand = function() { if (index < matchedLines.length) { var command = matchedLines[index] + cmd; exCommandDispatcher.processCommand(cm, command, { callback: nextCommand }); } index++; }; nextCommand(); }, substitute: function(cm, params) { if (!cm.getSearchCursor) { throw new Error('Search feature not available. Requires searchcursor.js or ' + 'any other getSearchCursor implementation.'); } var argString = params.argString; var tokens = argString ? splitBySeparator(argString, argString[0]) : []; var regexPart, replacePart = '', trailing, flagsPart, count; var confirm = false; // Whether to confirm each replace. var global = false; // True to replace all instances on a line, false to replace only 1. if (tokens.length) { regexPart = tokens[0]; replacePart = tokens[1]; if (regexPart && regexPart[regexPart.length - 1] === '$') { regexPart = regexPart.slice(0, regexPart.length - 1) + '\\n'; replacePart = replacePart ? replacePart + '\n' : '\n'; } if (replacePart !== undefined) { if (getOption('pcre')) { replacePart = unescapeRegexReplace(replacePart); } else { replacePart = translateRegexReplace(replacePart); } vimGlobalState.lastSubstituteReplacePart = replacePart; } trailing = tokens[2] ? tokens[2].split(' ') : []; } else { // either the argString is empty or its of the form ' hello/world' // actually splitBySlash returns a list of tokens // only if the string starts with a '/' if (argString && argString.length) { showConfirm(cm, 'Substitutions should be of the form ' + ':s/pattern/replace/'); return; } } // After the 3rd slash, we can have flags followed by a space followed // by count. if (trailing) { flagsPart = trailing[0]; count = parseInt(trailing[1]); if (flagsPart) { if (flagsPart.indexOf('c') != -1) { confirm = true; flagsPart.replace('c', ''); } if (flagsPart.indexOf('g') != -1) { global = true; flagsPart.replace('g', ''); } regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart; } } if (regexPart) { // If regex part is empty, then use the previous query. Otherwise use // the regex part as the new query. try { updateSearchQuery(cm, regexPart, true /** ignoreCase */, true /** smartCase */); } catch (e) { showConfirm(cm, 'Invalid regex: ' + regexPart); return; } } replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart; if (replacePart === undefined) { showConfirm(cm, 'No previous substitute regular expression'); return; } var state = getSearchState(cm); var query = state.getQuery(); var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line; var lineEnd = params.lineEnd || lineStart; if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) { lineEnd = Infinity; } if (count) { lineStart = lineEnd; lineEnd = lineStart + count - 1; } var startPos = clipCursorToContent(cm, Pos(lineStart, 0)); var cursor = cm.getSearchCursor(query, startPos); doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback); }, redo: CodeMirror.commands.redo, undo: CodeMirror.commands.undo, write: function(cm) { if (CodeMirror.commands.save) { // If a save command is defined, call it. CodeMirror.commands.save(cm); } else if (cm.save) { // Saves to text area if no save command is defined and cm.save() is available. cm.save(); } }, nohlsearch: function(cm) { clearSearchHighlight(cm); }, yank: function (cm) { var cur = copyCursor(cm.getCursor()); var line = cur.line; var lineText = cm.getLine(line); vimGlobalState.registerController.pushText( '0', 'yank', lineText, true, true); }, delmarks: function(cm, params) { if (!params.argString || !trim(params.argString)) { showConfirm(cm, 'Argument required'); return; } var state = cm.state.vim; var stream = new CodeMirror.StringStream(trim(params.argString)); while (!stream.eol()) { stream.eatSpace(); // Record the streams position at the beginning of the loop for use // in error messages. var count = stream.pos; if (!stream.match(/[a-zA-Z]/, false)) { showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); return; } var sym = stream.next(); // Check if this symbol is part of a range if (stream.match('-', true)) { // This symbol is part of a range. // The range must terminate at an alphabetic character. if (!stream.match(/[a-zA-Z]/, false)) { showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); return; } var startMark = sym; var finishMark = stream.next(); // The range must terminate at an alphabetic character which // shares the same case as the start of the range. if (isLowerCase(startMark) && isLowerCase(finishMark) || isUpperCase(startMark) && isUpperCase(finishMark)) { var start = startMark.charCodeAt(0); var finish = finishMark.charCodeAt(0); if (start >= finish) { showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count)); return; } // Because marks are always ASCII values, and we have // determined that they are the same case, we can use // their char codes to iterate through the defined range. for (var j = 0; j <= finish - start; j++) { var mark = String.fromCharCode(start + j); delete state.marks[mark]; } } else { showConfirm(cm, 'Invalid argument: ' + startMark + '-'); return; } } else { // This symbol is a valid mark, and is not part of a range. delete state.marks[sym]; } } } }; var exCommandDispatcher = new ExCommandDispatcher(); /** * @param {CodeMirror} cm CodeMirror instance we are in. * @param {boolean} confirm Whether to confirm each replace. * @param {Cursor} lineStart Line to start replacing from. * @param {Cursor} lineEnd Line to stop replacing at. * @param {RegExp} query Query for performing matches with. * @param {string} replaceWith Text to replace matches with. May contain $1, * $2, etc for replacing captured groups using Javascript replace. * @param {function()} callback A callback for when the replace is done. */ function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query, replaceWith, callback) { // Set up all the functions. cm.state.vim.exMode = true; var done = false; var lastPos = searchCursor.from(); function replaceAll() { cm.operation(function() { while (!done) { replace(); next(); } stop(); }); } function replace() { var text = cm.getRange(searchCursor.from(), searchCursor.to()); var newText = text.replace(query, replaceWith); searchCursor.replace(newText); } function next() { // The below only loops to skip over multiple occurrences on the same // line when 'global' is not true. while(searchCursor.findNext() && isInRange(searchCursor.from(), lineStart, lineEnd)) { if (!global && lastPos && searchCursor.from().line == lastPos.line) { continue; } cm.scrollIntoView(searchCursor.from(), 30); cm.setSelection(searchCursor.from(), searchCursor.to()); lastPos = searchCursor.from(); done = false; return; } done = true; } function stop(close) { if (close) { close(); } cm.focus(); if (lastPos) { cm.setCursor(lastPos); var vim = cm.state.vim; vim.exMode = false; vim.lastHPos = vim.lastHSPos = lastPos.ch; } if (callback) { callback(); } } function onPromptKeyDown(e, _value, close) { // Swallow all keys. CodeMirror.e_stop(e); var keyName = CodeMirror.keyName(e); switch (keyName) { case 'Y': replace(); next(); break; case 'N': next(); break; case 'A': // replaceAll contains a call to close of its own. We don't want it // to fire too early or multiple times. var savedCallback = callback; callback = undefined; cm.operation(replaceAll); callback = savedCallback; break; case 'L': replace(); // fall through and exit. case 'Q': case 'Esc': case 'Ctrl-C': case 'Ctrl-[': stop(close); break; } if (done) { stop(close); } return true; } // Actually do replace. next(); if (done) { showConfirm(cm, 'No matches for ' + query.source); return; } if (!confirm) { replaceAll(); if (callback) { callback(); } return; } showPrompt(cm, { prefix: 'replace with ' + replaceWith + ' (y/n/a/q/l)', onKeyDown: onPromptKeyDown }); } CodeMirror.keyMap.vim = { attach: attachVimMap, detach: detachVimMap, call: cmKey }; function exitInsertMode(cm) { var vim = cm.state.vim; var macroModeState = vimGlobalState.macroModeState; var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.'); var isPlaying = macroModeState.isPlaying; var lastChange = macroModeState.lastInsertModeChanges; if (!isPlaying) { cm.off('change', onChange); CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown); } if (!isPlaying && vim.insertModeRepeat > 1) { // Perform insert mode repeat for commands like 3,a and 3,o. repeatLastEdit(cm, vim, vim.insertModeRepeat - 1, true /** repeatForInsert */); vim.lastEditInputState.repeatOverride = vim.insertModeRepeat; } delete vim.insertModeRepeat; vim.insertMode = false; cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1); cm.setOption('keyMap', 'vim'); cm.setOption('disableInput', true); cm.toggleOverwrite(false); // exit replace mode if we were in it. // update the ". register before exiting insert mode insertModeChangeRegister.setText(lastChange.changes.join('')); CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"}); if (macroModeState.isRecording) { logInsertModeChange(macroModeState); } } function _mapCommand(command) { defaultKeymap.unshift(command); } function mapCommand(keys, type, name, args, extra) { var command = {keys: keys, type: type}; command[type] = name; command[type + "Args"] = args; for (var key in extra) command[key] = extra[key]; _mapCommand(command); } // The timeout in milliseconds for the two-character ESC keymap should be // adjusted according to your typing speed to prevent false positives. defineOption('insertModeEscKeysTimeout', 200, 'number'); CodeMirror.keyMap['vim-insert'] = { // TODO: override navigation keys so that Esc will cancel automatic // indentation from o, O, i_ fallthrough: ['default'], attach: attachVimMap, detach: detachVimMap, call: cmKey }; CodeMirror.keyMap['vim-replace'] = { 'Backspace': 'goCharLeft', fallthrough: ['vim-insert'], attach: attachVimMap, detach: detachVimMap, call: cmKey }; function executeMacroRegister(cm, vim, macroModeState, registerName) { var register = vimGlobalState.registerController.getRegister(registerName); if (registerName == ':') { // Read-only register containing last Ex command. if (register.keyBuffer[0]) { exCommandDispatcher.processCommand(cm, register.keyBuffer[0]); } macroModeState.isPlaying = false; return; } var keyBuffer = register.keyBuffer; var imc = 0; macroModeState.isPlaying = true; macroModeState.replaySearchQueries = register.searchQueries.slice(0); for (var i = 0; i < keyBuffer.length; i++) { var text = keyBuffer[i]; var match, key; while (text) { // Pull off one command key, which is either a single character // or a special sequence wrapped in '<' and '>', e.g. ''. match = (/<\w+-.+?>|<\w+>|./).exec(text); key = match[0]; text = text.substring(match.index + key.length); CodeMirror.Vim.handleKey(cm, key, 'macro'); if (vim.insertMode) { var changes = register.insertModeChanges[imc++].changes; vimGlobalState.macroModeState.lastInsertModeChanges.changes = changes; repeatInsertModeChanges(cm, changes, 1); exitInsertMode(cm); } } } macroModeState.isPlaying = false; } function logKey(macroModeState, key) { if (macroModeState.isPlaying) { return; } var registerName = macroModeState.latestRegister; var register = vimGlobalState.registerController.getRegister(registerName); if (register) { register.pushText(key); } } function logInsertModeChange(macroModeState) { if (macroModeState.isPlaying) { return; } var registerName = macroModeState.latestRegister; var register = vimGlobalState.registerController.getRegister(registerName); if (register && register.pushInsertModeChanges) { register.pushInsertModeChanges(macroModeState.lastInsertModeChanges); } } function logSearchQuery(macroModeState, query) { if (macroModeState.isPlaying) { return; } var registerName = macroModeState.latestRegister; var register = vimGlobalState.registerController.getRegister(registerName); if (register && register.pushSearchQuery) { register.pushSearchQuery(query); } } /** * Listens for changes made in insert mode. * Should only be active in insert mode. */ function onChange(cm, changeObj) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; if (!macroModeState.isPlaying) { while(changeObj) { lastChange.expectCursorActivityForChange = true; if (lastChange.ignoreCount > 1) { lastChange.ignoreCount--; } else if (changeObj.origin == '+input' || changeObj.origin == 'paste' || changeObj.origin === undefined /* only in testing */) { var selectionCount = cm.listSelections().length; if (selectionCount > 1) lastChange.ignoreCount = selectionCount; var text = changeObj.text.join('\n'); if (lastChange.maybeReset) { lastChange.changes = []; lastChange.maybeReset = false; } if (text) { if (cm.state.overwrite && !/\n/.test(text)) { lastChange.changes.push([text]); } else { lastChange.changes.push(text); } } } // Change objects may be chained with next. changeObj = changeObj.next; } } } /** * Listens for any kind of cursor activity on CodeMirror. */ function onCursorActivity(cm) { var vim = cm.state.vim; if (vim.insertMode) { // Tracking cursor activity in insert mode (for macro support). var macroModeState = vimGlobalState.macroModeState; if (macroModeState.isPlaying) { return; } var lastChange = macroModeState.lastInsertModeChanges; if (lastChange.expectCursorActivityForChange) { lastChange.expectCursorActivityForChange = false; } else { // Cursor moved outside the context of an edit. Reset the change. lastChange.maybeReset = true; } } else if (!cm.curOp.isVimOp) { handleExternalSelection(cm, vim); } if (vim.visualMode) { updateFakeCursor(cm); } } function updateFakeCursor(cm) { var vim = cm.state.vim; var from = clipCursorToContent(cm, copyCursor(vim.sel.head)); var to = offsetCursor(from, 0, 1); if (vim.fakeCursor) { vim.fakeCursor.clear(); } vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'}); } function handleExternalSelection(cm, vim) { var anchor = cm.getCursor('anchor'); var head = cm.getCursor('head'); // Enter or exit visual mode to match mouse selection. if (vim.visualMode && !cm.somethingSelected()) { exitVisualMode(cm, false); } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) { vim.visualMode = true; vim.visualLine = false; CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"}); } if (vim.visualMode) { // Bind CodeMirror selection model to vim selection model. // Mouse selections are considered visual characterwise. var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0; var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0; head = offsetCursor(head, 0, headOffset); anchor = offsetCursor(anchor, 0, anchorOffset); vim.sel = { anchor: anchor, head: head }; updateMark(cm, vim, '<', cursorMin(head, anchor)); updateMark(cm, vim, '>', cursorMax(head, anchor)); } else if (!vim.insertMode) { // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse. vim.lastHPos = cm.getCursor().ch; } } /** Wrapper for special keys pressed in insert mode */ function InsertModeKey(keyName) { this.keyName = keyName; } /** * Handles raw key down events from the text area. * - Should only be active in insert mode. * - For recording deletes in insert mode. */ function onKeyEventTargetKeyDown(e) { var macroModeState = vimGlobalState.macroModeState; var lastChange = macroModeState.lastInsertModeChanges; var keyName = CodeMirror.keyName(e); if (!keyName) { return; } function onKeyFound() { if (lastChange.maybeReset) { lastChange.changes = []; lastChange.maybeReset = false; } lastChange.changes.push(new InsertModeKey(keyName)); return true; } if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) { CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound); } } /** * Repeats the last edit, which includes exactly 1 command and at most 1 * insert. Operator and motion commands are read from lastEditInputState, * while action commands are read from lastEditActionCommand. * * If repeatForInsert is true, then the function was called by * exitInsertMode to repeat the insert mode changes the user just made. The * corresponding enterInsertMode call was made with a count. */ function repeatLastEdit(cm, vim, repeat, repeatForInsert) { var macroModeState = vimGlobalState.macroModeState; macroModeState.isPlaying = true; var isAction = !!vim.lastEditActionCommand; var cachedInputState = vim.inputState; function repeatCommand() { if (isAction) { commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand); } else { commandDispatcher.evalInput(cm, vim); } } function repeatInsert(repeat) { if (macroModeState.lastInsertModeChanges.changes.length > 0) { // For some reason, repeat cw in desktop VIM does not repeat // insert mode changes. Will conform to that behavior. repeat = !vim.lastEditActionCommand ? 1 : repeat; var changeObject = macroModeState.lastInsertModeChanges; repeatInsertModeChanges(cm, changeObject.changes, repeat); } } vim.inputState = vim.lastEditInputState; if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) { // o and O repeat have to be interlaced with insert repeats so that the // insertions appear on separate lines instead of the last line. for (var i = 0; i < repeat; i++) { repeatCommand(); repeatInsert(1); } } else { if (!repeatForInsert) { // Hack to get the cursor to end up at the right place. If I is // repeated in insert mode repeat, cursor will be 1 insert // change set left of where it should be. repeatCommand(); } repeatInsert(repeat); } vim.inputState = cachedInputState; if (vim.insertMode && !repeatForInsert) { // Don't exit insert mode twice. If repeatForInsert is set, then we // were called by an exitInsertMode call lower on the stack. exitInsertMode(cm); } macroModeState.isPlaying = false; } function repeatInsertModeChanges(cm, changes, repeat) { function keyHandler(binding) { if (typeof binding == 'string') { CodeMirror.commands[binding](cm); } else { binding(cm); } return true; } var head = cm.getCursor('head'); var inVisualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.inVisualBlock; if (inVisualBlock) { // Set up block selection again for repeating the changes. var vim = cm.state.vim; var lastSel = vim.lastSelection; var offset = getOffset(lastSel.anchor, lastSel.head); selectForInsert(cm, head, offset.line + 1); repeat = cm.listSelections().length; cm.setCursor(head); } for (var i = 0; i < repeat; i++) { if (inVisualBlock) { cm.setCursor(offsetCursor(head, i, 0)); } for (var j = 0; j < changes.length; j++) { var change = changes[j]; if (change instanceof InsertModeKey) { CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler); } else if (typeof change == "string") { var cur = cm.getCursor(); cm.replaceRange(change, cur, cur); } else { var start = cm.getCursor(); var end = offsetCursor(start, 0, change[0].length); cm.replaceRange(change[0], start, end); } } } if (inVisualBlock) { cm.setCursor(offsetCursor(head, 0, 1)); } } resetVimGlobalState(); return vimApi; }; // Initialize Vim and make it available as an API. CodeMirror.Vim = Vim(); }); ================================================ FILE: third_party/CodeMirror/lib/codemirror.css ================================================ /* BASICS */ .CodeMirror { /* Set height, width, borders, and global font properties here */ font-family: monospace; height: 300px; color: black; direction: ltr; } /* PADDING */ .CodeMirror-lines { padding: 4px 0; /* Vertical padding around content */ } .CodeMirror pre { padding: 0 4px; /* Horizontal padding of content */ } .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { background-color: white; /* The little square between H and V scrollbars */ } /* GUTTER */ .CodeMirror-gutters { border-right: 1px solid #ddd; background-color: #f7f7f7; white-space: nowrap; } .CodeMirror-linenumbers {} .CodeMirror-linenumber { padding: 0 3px 0 5px; min-width: 20px; text-align: right; color: #999; white-space: nowrap; } .CodeMirror-guttermarker { color: black; } .CodeMirror-guttermarker-subtle { color: #999; } /* CURSOR */ .CodeMirror-cursor { border-left: 1px solid black; border-right: none; width: 0; } /* Shown when moving in bi-directional text */ .CodeMirror div.CodeMirror-secondarycursor { border-left: 1px solid silver; } .cm-fat-cursor .CodeMirror-cursor { width: auto; border: 0 !important; background: #7e7; } .cm-fat-cursor div.CodeMirror-cursors { z-index: 1; } .cm-fat-cursor-mark { background-color: rgba(20, 255, 20, 0.5); -webkit-animation: blink 1.06s steps(1) infinite; -moz-animation: blink 1.06s steps(1) infinite; animation: blink 1.06s steps(1) infinite; } .cm-animate-fat-cursor { width: auto; border: 0; -webkit-animation: blink 1.06s steps(1) infinite; -moz-animation: blink 1.06s steps(1) infinite; animation: blink 1.06s steps(1) infinite; background-color: #7e7; } @-moz-keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } @-webkit-keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } @keyframes blink { 0% {} 50% { background-color: transparent; } 100% {} } /* Can style cursor different in overwrite (non-insert) mode */ .CodeMirror-overwrite .CodeMirror-cursor {} .cm-tab { display: inline-block; text-decoration: inherit; } .CodeMirror-rulers { position: absolute; left: 0; right: 0; top: -50px; bottom: -20px; overflow: hidden; } .CodeMirror-ruler { border-left: 1px solid #ccc; top: 0; bottom: 0; position: absolute; } /* DEFAULT THEME */ .cm-s-default .cm-header {color: blue;} .cm-s-default .cm-quote {color: #090;} .cm-negative {color: #d44;} .cm-positive {color: #292;} .cm-header, .cm-strong {font-weight: bold;} .cm-em {font-style: italic;} .cm-link {text-decoration: underline;} .cm-strikethrough {text-decoration: line-through;} .cm-s-default .cm-keyword {color: #708;} .cm-s-default .cm-atom {color: #219;} .cm-s-default .cm-number {color: #164;} .cm-s-default .cm-def {color: #00f;} .cm-s-default .cm-variable, .cm-s-default .cm-punctuation, .cm-s-default .cm-property, .cm-s-default .cm-operator {} .cm-s-default .cm-variable-2 {color: #05a;} .cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;} .cm-s-default .cm-comment {color: #a50;} .cm-s-default .cm-string {color: #a11;} .cm-s-default .cm-string-2 {color: #f50;} .cm-s-default .cm-meta {color: #555;} .cm-s-default .cm-qualifier {color: #555;} .cm-s-default .cm-builtin {color: #30a;} .cm-s-default .cm-bracket {color: #997;} .cm-s-default .cm-tag {color: #170;} .cm-s-default .cm-attribute {color: #00c;} .cm-s-default .cm-hr {color: #999;} .cm-s-default .cm-link {color: #00c;} .cm-s-default .cm-error {color: #f00;} .cm-invalidchar {color: #f00;} .CodeMirror-composing { border-bottom: 2px solid; } /* Default styles for common addons */ div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;} div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;} .CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); } .CodeMirror-activeline-background {background: #e8f2ff;} /* STOP */ /* The rest of this file contains styles related to the mechanics of the editor. You probably shouldn't touch them. */ .CodeMirror { position: relative; overflow: hidden; background: white; } .CodeMirror-scroll { overflow: scroll !important; /* Things will break if this is overridden */ /* 30px is the magic margin used to hide the element's real scrollbars */ /* See overflow: hidden in .CodeMirror */ margin-bottom: -30px; margin-right: -30px; padding-bottom: 30px; height: 100%; outline: none; /* Prevent dragging from highlighting the element */ position: relative; } .CodeMirror-sizer { position: relative; border-right: 30px solid transparent; } /* The fake, visible scrollbars. Used to force redraw during scrolling before actual scrolling happens, thus preventing shaking and flickering artifacts. */ .CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler { position: absolute; z-index: 6; display: none; } .CodeMirror-vscrollbar { right: 0; top: 0; overflow-x: hidden; overflow-y: scroll; } .CodeMirror-hscrollbar { bottom: 0; left: 0; overflow-y: hidden; overflow-x: scroll; } .CodeMirror-scrollbar-filler { right: 0; bottom: 0; } .CodeMirror-gutter-filler { left: 0; bottom: 0; } .CodeMirror-gutters { position: absolute; left: 0; top: 0; min-height: 100%; z-index: 3; } .CodeMirror-gutter { white-space: normal; height: 100%; display: inline-block; vertical-align: top; margin-bottom: -30px; } .CodeMirror-gutter-wrapper { position: absolute; z-index: 4; background: none !important; border: none !important; } .CodeMirror-gutter-background { position: absolute; top: 0; bottom: 0; z-index: 4; } .CodeMirror-gutter-elt { position: absolute; cursor: default; z-index: 4; } .CodeMirror-gutter-wrapper ::selection { background-color: transparent } .CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent } .CodeMirror-lines { cursor: text; min-height: 1px; /* prevents collapsing before first draw */ } .CodeMirror pre { /* Reset some styles that the rest of the page might have set */ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0; border-width: 0; background: transparent; font-family: inherit; font-size: inherit; margin: 0; white-space: pre; word-wrap: normal; line-height: inherit; color: inherit; z-index: 2; position: relative; overflow: visible; -webkit-tap-highlight-color: transparent; -webkit-font-variant-ligatures: contextual; font-variant-ligatures: contextual; } .CodeMirror-wrap pre { word-wrap: break-word; white-space: pre-wrap; word-break: normal; } .CodeMirror-linebackground { position: absolute; left: 0; right: 0; top: 0; bottom: 0; z-index: 0; } .CodeMirror-linewidget { position: relative; z-index: 2; padding: 0.1px; /* Force widget margins to stay inside of the container */ } .CodeMirror-widget {} .CodeMirror-rtl pre { direction: rtl; } .CodeMirror-code { outline: none; } /* Force content-box sizing for the elements where we expect it */ .CodeMirror-scroll, .CodeMirror-sizer, .CodeMirror-gutter, .CodeMirror-gutters, .CodeMirror-linenumber { -moz-box-sizing: content-box; box-sizing: content-box; } .CodeMirror-measure { position: absolute; width: 100%; height: 0; overflow: hidden; visibility: hidden; } .CodeMirror-cursor { position: absolute; pointer-events: none; } .CodeMirror-measure pre { position: static; } div.CodeMirror-cursors { visibility: hidden; position: relative; z-index: 3; } div.CodeMirror-dragcursors { visibility: visible; } .CodeMirror-focused div.CodeMirror-cursors { visibility: visible; } .CodeMirror-selected { background: #d9d9d9; } .CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; } .CodeMirror-crosshair { cursor: crosshair; } .CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; } .CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; } .cm-searching { background-color: #ffa; background-color: rgba(255, 255, 0, .4); } /* Used to force a border model for a node */ .cm-force-border { padding-right: .1px; } @media print { /* Hide the cursor when printing */ .CodeMirror div.CodeMirror-cursors { visibility: hidden; } } /* See issue #2901 */ .cm-tab-wrap-hack:after { content: ''; } /* Help users use markselection to safely style text background */ span.CodeMirror-selectedtext { background: none; } ================================================ FILE: third_party/CodeMirror/lib/codemirror.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // This is CodeMirror (https://codemirror.net), a code editor // implemented in JavaScript on top of the browser's DOM. // // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.CodeMirror = factory()); }(this, (function () { 'use strict'; // Kludges for bugs and behavior differences that can't be feature // detected are enabled based on userAgent etc sniffing. var userAgent = navigator.userAgent; var platform = navigator.platform; var gecko = /gecko\/\d/i.test(userAgent); var ie_upto10 = /MSIE \d/.test(userAgent); var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); var edge = /Edge\/(\d+)/.exec(userAgent); var ie = ie_upto10 || ie_11up || edge; var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); var webkit = !edge && /WebKit\//.test(userAgent); var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); var chrome = !edge && /Chrome\//.test(userAgent); var presto = /Opera\//.test(userAgent); var safari = /Apple Computer/.test(navigator.vendor); var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); var phantom = /PhantomJS/.test(userAgent); var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); var android = /Android/.test(userAgent); // This is woefully incomplete. Suggestions for alternative methods welcome. var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); var mac = ios || /Mac/.test(platform); var chromeOS = /\bCrOS\b/.test(userAgent); var windows = /win/i.test(platform); var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); if (presto_version) { presto_version = Number(presto_version[1]); } if (presto_version && presto_version >= 15) { presto = false; webkit = true; } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); var captureRightClick = gecko || (ie && ie_version >= 9); function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } var rmClass = function(node, cls) { var current = node.className; var match = classTest(cls).exec(current); if (match) { var after = current.slice(match.index + match[0].length); node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); } }; function removeChildren(e) { for (var count = e.childNodes.length; count > 0; --count) { e.removeChild(e.firstChild); } return e } function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e) } function elt(tag, content, className, style) { var e = document.createElement(tag); if (className) { e.className = className; } if (style) { e.style.cssText = style; } if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } return e } // wrapper for elt, which removes the elt from the accessibility tree function eltP(tag, content, className, style) { var e = elt(tag, content, className, style); e.setAttribute("role", "presentation"); return e } var range; if (document.createRange) { range = function(node, start, end, endNode) { var r = document.createRange(); r.setEnd(endNode || node, end); r.setStart(node, start); return r }; } else { range = function(node, start, end) { var r = document.body.createTextRange(); try { r.moveToElementText(node.parentNode); } catch(e) { return r } r.collapse(true); r.moveEnd("character", end); r.moveStart("character", start); return r }; } function contains(parent, child) { if (child.nodeType == 3) // Android browser always returns false when child is a textnode { child = child.parentNode; } if (parent.contains) { return parent.contains(child) } do { if (child.nodeType == 11) { child = child.host; } if (child == parent) { return true } } while (child = child.parentNode) } function activeElt() { // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. // IE < 10 will throw when accessed while the page is loading or in an iframe. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. var activeElement; try { activeElement = document.activeElement; } catch(e) { activeElement = document.body || null; } while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) { activeElement = activeElement.shadowRoot.activeElement; } return activeElement } function addClass(node, cls) { var current = node.className; if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } } function joinClasses(a, b) { var as = a.split(" "); for (var i = 0; i < as.length; i++) { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } return b } var selectInput = function(node) { node.select(); }; if (ios) // Mobile Safari apparently has a bug where select() is broken. { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } else if (ie) // Suppress mysterious IE10 errors { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } function bind(f) { var args = Array.prototype.slice.call(arguments, 1); return function(){return f.apply(null, args)} } function copyObj(obj, target, overwrite) { if (!target) { target = {}; } for (var prop in obj) { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) { target[prop] = obj[prop]; } } return target } // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/); if (end == -1) { end = string.length; } } for (var i = startIndex || 0, n = startValue || 0;;) { var nextTab = string.indexOf("\t", i); if (nextTab < 0 || nextTab >= end) { return n + (end - i) } n += nextTab - i; n += tabSize - (n % tabSize); i = nextTab + 1; } } var Delayed = function() {this.id = null;}; Delayed.prototype.set = function (ms, f) { clearTimeout(this.id); this.id = setTimeout(f, ms); }; function indexOf(array, elt) { for (var i = 0; i < array.length; ++i) { if (array[i] == elt) { return i } } return -1 } // Number of pixels added to scroller and sizer to hide scrollbar var scrollerGap = 30; // Returned or thrown by various protocols to signal 'I'm not // handling this'. var Pass = {toString: function(){return "CodeMirror.Pass"}}; // Reused option objects for setSelection & friends var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; // The inverse of countColumn -- find the offset that corresponds to // a particular column. function findColumn(string, goal, tabSize) { for (var pos = 0, col = 0;;) { var nextTab = string.indexOf("\t", pos); if (nextTab == -1) { nextTab = string.length; } var skipped = nextTab - pos; if (nextTab == string.length || col + skipped >= goal) { return pos + Math.min(skipped, goal - col) } col += nextTab - pos; col += tabSize - (col % tabSize); pos = nextTab + 1; if (col >= goal) { return pos } } } var spaceStrs = [""]; function spaceStr(n) { while (spaceStrs.length <= n) { spaceStrs.push(lst(spaceStrs) + " "); } return spaceStrs[n] } function lst(arr) { return arr[arr.length-1] } function map(array, f) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } return out } function insertSorted(array, value, score) { var pos = 0, priority = score(value); while (pos < array.length && score(array[pos]) <= priority) { pos++; } array.splice(pos, 0, value); } function nothing() {} function createObj(base, props) { var inst; if (Object.create) { inst = Object.create(base); } else { nothing.prototype = base; inst = new nothing(); } if (props) { copyObj(props, inst); } return inst } var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; function isWordCharBasic(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) } function isWordChar(ch, helper) { if (!helper) { return isWordCharBasic(ch) } if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } return helper.test(ch) } function isEmpty(obj) { for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } return true } // Extending unicode characters. A series of a non-extending char + // any number of extending chars is treated as a single unit as far // as editing and measuring is concerned. This is not fully correct, // since some scripts/fonts/browsers also treat other configurations // of code points as a group. 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]/; function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. function skipExtendingChars(str, pos, dir) { while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } return pos } // Returns the value from the range [`from`; `to`] that satisfies // `pred` and is closest to `from`. Assumes that at least `to` // satisfies `pred`. Supports `from` being greater than `to`. function findFirst(pred, from, to) { // At any point we are certain `to` satisfies `pred`, don't know // whether `from` does. var dir = from > to ? -1 : 1; for (;;) { if (from == to) { return from } var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); if (mid == from) { return pred(mid) ? from : to } if (pred(mid)) { to = mid; } else { from = mid + dir; } } } // The display handles the DOM integration, both for input reading // and content drawing. It holds references to DOM nodes and // display-related state. function Display(place, doc, input) { var d = this; this.input = input; // Covers bottom-right square when both scrollbars are present. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); d.scrollbarFiller.setAttribute("cm-not-content", "true"); // Covers bottom of gutter when coverGutterNextToScrollbar is on // and h scrollbar is present. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); d.gutterFiller.setAttribute("cm-not-content", "true"); // Will contain the actual code, positioned to cover the viewport. d.lineDiv = eltP("div", null, "CodeMirror-code"); // Elements are added to these to represent selection and cursors. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); d.cursorDiv = elt("div", null, "CodeMirror-cursors"); // A visibility: hidden element used to find the size of things. d.measure = elt("div", null, "CodeMirror-measure"); // When lines outside of the viewport are measured, they are drawn in this. d.lineMeasure = elt("div", null, "CodeMirror-measure"); // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none"); var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); // Moved around its parent to cover visible view. d.mover = elt("div", [lines], null, "position: relative"); // Set to the height of the document, allowing scrolling. d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); d.sizerWidth = null; // Behavior of elts with overflow: auto and padding is // inconsistent across browsers. This is used to ensure the // scrollable area is big enough. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); // Will contain the gutters, if any. d.gutters = elt("div", null, "CodeMirror-gutters"); d.lineGutter = null; // Actual scrollable element. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); d.scroller.setAttribute("tabIndex", "-1"); // The element in which the editor lives. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } if (place) { if (place.appendChild) { place.appendChild(d.wrapper); } else { place(d.wrapper); } } // Current rendered range (may be bigger than the view window). d.viewFrom = d.viewTo = doc.first; d.reportedViewFrom = d.reportedViewTo = doc.first; // Information about the rendered lines. d.view = []; d.renderedView = null; // Holds info about a single rendered line when it was rendered // for measurement, while not in view. d.externalMeasured = null; // Empty space (in pixels) above the view d.viewOffset = 0; d.lastWrapHeight = d.lastWrapWidth = 0; d.updateLineNumbers = null; d.nativeBarWidth = d.barHeight = d.barWidth = 0; d.scrollbarsClipped = false; // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; // Set to true when a non-horizontal-scrolling line widget is // added. As an optimization, line widget aligning is skipped when // this is false. d.alignWidgets = false; d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. d.maxLine = null; d.maxLineLength = 0; d.maxLineChanged = false; // Used for measuring wheel scrolling granularity d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; // True when shift is held down. d.shift = false; // Used to track whether anything happened since the context menu // was opened. d.selForContextMenu = null; d.activeTouch = null; input.init(d); } // Find the line object corresponding to the given line number. function getLine(doc, n) { n -= doc.first; if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } var chunk = doc; while (!chunk.lines) { for (var i = 0;; ++i) { var child = chunk.children[i], sz = child.chunkSize(); if (n < sz) { chunk = child; break } n -= sz; } } return chunk.lines[n] } // Get the part of a document between two positions, as an array of // strings. function getBetween(doc, start, end) { var out = [], n = start.line; doc.iter(start.line, end.line + 1, function (line) { var text = line.text; if (n == end.line) { text = text.slice(0, end.ch); } if (n == start.line) { text = text.slice(start.ch); } out.push(text); ++n; }); return out } // Get the lines between from and to, as array of strings. function getLines(doc, from, to) { var out = []; doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value return out } // Update the height of a line, propagating the height change // upwards to parent nodes. function updateLineHeight(line, height) { var diff = height - line.height; if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } } // Given a line object, find its line number by walking up through // its parent links. function lineNo(line) { if (line.parent == null) { return null } var cur = line.parent, no = indexOf(cur.lines, line); for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (var i = 0;; ++i) { if (chunk.children[i] == cur) { break } no += chunk.children[i].chunkSize(); } } return no + cur.first } // Find the line at the given vertical position, using the height // information in the document tree. function lineAtHeight(chunk, h) { var n = chunk.first; outer: do { for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { var child = chunk.children[i$1], ch = child.height; if (h < ch) { chunk = child; continue outer } h -= ch; n += child.chunkSize(); } return n } while (!chunk.lines) var i = 0; for (; i < chunk.lines.length; ++i) { var line = chunk.lines[i], lh = line.height; if (h < lh) { break } h -= lh; } return n + i } function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)) } // A Pos instance represents a position within the text. function Pos(line, ch, sticky) { if ( sticky === void 0 ) sticky = null; if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } this.line = line; this.ch = ch; this.sticky = sticky; } // Compare two positions, return 0 if they are the same, a negative // number when a is less, and a positive number otherwise. function cmp(a, b) { return a.line - b.line || a.ch - b.ch } function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } function copyPos(x) {return Pos(x.line, x.ch)} function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } function minPos(a, b) { return cmp(a, b) < 0 ? a : b } // Most of the external API clips given positions to make sure they // actually exist within the document. function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} function clipPos(doc, pos) { if (pos.line < doc.first) { return Pos(doc.first, 0) } var last = doc.first + doc.size - 1; if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } return clipToLen(pos, getLine(doc, pos.line).text.length) } function clipToLen(pos, linelen) { var ch = pos.ch; if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } else if (ch < 0) { return Pos(pos.line, 0) } else { return pos } } function clipPosArray(doc, array) { var out = []; for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } return out } // Optimize some code when these features are not used. var sawReadOnlySpans = false, sawCollapsedSpans = false; function seeReadOnlySpans() { sawReadOnlySpans = true; } function seeCollapsedSpans() { sawCollapsedSpans = true; } // TEXTMARKER SPANS function MarkedSpan(marker, from, to) { this.marker = marker; this.from = from; this.to = to; } // Search an array of spans for a span matching the given marker. function getMarkedSpanFor(spans, marker) { if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.marker == marker) { return span } } } } // Remove a span from an array, returning undefined if no spans are // left (we don't store arrays for lines without spans). function removeMarkedSpan(spans, span) { var r; for (var i = 0; i < spans.length; ++i) { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } return r } // Add a span to a line. function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; span.marker.attachLine(line); } // Used for the algorithm that adjusts markers for a change in the // document. These functions cut an array of spans at a given // character position, returning an array of remaining chunks (or // undefined if nothing remains). function markedSpansBefore(old, startCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); } } } return nw } function markedSpansAfter(old, endCh, isInsert) { var nw; if (old) { for (var i = 0; i < old.length; ++i) { var span = old[i], marker = span.marker; var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)); } } } return nw } // Given a change object, compute the new set of marker spans that // cover the line in which the change took place. Removes spans // entirely within the change, reconnects spans belonging to the // same marker that appear on both sides of the change, and cuts off // spans partially within the change. Returns an array of span // arrays with one element for each line in (after) the change. function stretchSpansOverChange(doc, change) { if (change.full) { return null } var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; if (!oldFirst && !oldLast) { return null } var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; // Get the spans that 'stick out' on both sides var first = markedSpansBefore(oldFirst, startCh, isInsert); var last = markedSpansAfter(oldLast, endCh, isInsert); // Next, merge those two ends var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); if (first) { // Fix up .to properties of first for (var i = 0; i < first.length; ++i) { var span = first[i]; if (span.to == null) { var found = getMarkedSpanFor(last, span.marker); if (!found) { span.to = startCh; } else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (var i$1 = 0; i$1 < last.length; ++i$1) { var span$1 = last[i$1]; if (span$1.to != null) { span$1.to += offset; } if (span$1.from == null) { var found$1 = getMarkedSpanFor(first, span$1.marker); if (!found$1) { span$1.from = offset; if (sameLine) { (first || (first = [])).push(span$1); } } } else { span$1.from += offset; if (sameLine) { (first || (first = [])).push(span$1); } } } } // Make sure we didn't create any zero-length spans if (first) { first = clearEmptySpans(first); } if (last && last != first) { last = clearEmptySpans(last); } var newMarkers = [first]; if (!sameLine) { // Fill gap with whole-line-spans var gap = change.text.length - 2, gapMarkers; if (gap > 0 && first) { for (var i$2 = 0; i$2 < first.length; ++i$2) { if (first[i$2].to == null) { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } for (var i$3 = 0; i$3 < gap; ++i$3) { newMarkers.push(gapMarkers); } newMarkers.push(last); } return newMarkers } // Remove spans that are empty and don't have a clearWhenEmpty // option of false. function clearEmptySpans(spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) { spans.splice(i--, 1); } } if (!spans.length) { return null } return spans } // Used to 'clip' out readOnly ranges when making a change. function removeReadOnlyRanges(doc, from, to) { var markers = null; doc.iter(from.line, to.line + 1, function (line) { if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var mark = line.markedSpans[i].marker; if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) { (markers || (markers = [])).push(mark); } } } }); if (!markers) { return null } var parts = [{from: from, to: to}]; for (var i = 0; i < markers.length; ++i) { var mk = markers[i], m = mk.find(0); for (var j = 0; j < parts.length; ++j) { var p = parts[j]; if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) { newParts.push({from: p.from, to: m.from}); } if (dto > 0 || !mk.inclusiveRight && !dto) { newParts.push({from: m.to, to: p.to}); } parts.splice.apply(parts, newParts); j += newParts.length - 3; } } return parts } // Connect or disconnect spans from a line. function detachMarkedSpans(line) { var spans = line.markedSpans; if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.detachLine(line); } line.markedSpans = null; } function attachMarkedSpans(line, spans) { if (!spans) { return } for (var i = 0; i < spans.length; ++i) { spans[i].marker.attachLine(line); } line.markedSpans = spans; } // Helpers used when computing which overlapping collapsed span // counts as the larger one. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } // Returns a number indicating which of two overlapping collapsed // spans is larger (and thus includes the other). Falls back to // comparing ids when the spans cover exactly the same range. function compareCollapsedMarkers(a, b) { var lenDiff = a.lines.length - b.lines.length; if (lenDiff != 0) { return lenDiff } var aPos = a.find(), bPos = b.find(); var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); if (fromCmp) { return -fromCmp } var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); if (toCmp) { return toCmp } return b.id - a.id } // Find out whether a line ends or starts in a collapsed span. If // so, return the marker for that span. function collapsedSpanAtSide(line, start) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } function collapsedSpanAround(line, ch) { var sps = sawCollapsedSpans && line.markedSpans, found; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } } } return found } // Test whether there exists a collapsed span that partially // overlaps (covers the start or end, but not both) of a new span. // Such overlap is not allowed. function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { var line = getLine(doc, lineNo$$1); var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { var sp = sps[i]; if (!sp.marker.collapsed) { continue } var found = sp.marker.find(0); var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) { return true } } } } // A visual line is a line as drawn on the screen. Folding, for // example, can cause multiple logical lines to appear on the same // visual line. This finds the start of the visual line that the // given line is part of (usually that is the line itself). function visualLine(line) { var merged; while (merged = collapsedSpanAtStart(line)) { line = merged.find(-1, true).line; } return line } function visualLineEnd(line) { var merged; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return line } // Returns an array of logical lines that continue the visual line // started by the argument, or undefined if there are no such lines. function visualLineContinued(line) { var merged, lines; while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line ;(lines || (lines = [])).push(line); } return lines } // Get the line number of the start of the visual line that the // given line number is part of. function visualLineNo(doc, lineN) { var line = getLine(doc, lineN), vis = visualLine(line); if (line == vis) { return lineN } return lineNo(vis) } // Get the line number of the start of the next visual line after // the given line. function visualLineEndNo(doc, lineN) { if (lineN > doc.lastLine()) { return lineN } var line = getLine(doc, lineN), merged; if (!lineIsHidden(doc, line)) { return lineN } while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line; } return lineNo(line) + 1 } // Compute whether a line is hidden. Lines count as hidden when they // are part of a visual line that starts with another line, or when // they are entirely covered by collapsed, non-widget span. function lineIsHidden(doc, line) { var sps = sawCollapsedSpans && line.markedSpans; if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { sp = sps[i]; if (!sp.marker.collapsed) { continue } if (sp.from == null) { return true } if (sp.marker.widgetNode) { continue } if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) { return true } } } } function lineIsHiddenInner(doc, line, span) { if (span.to == null) { var end = span.marker.find(1, true); return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) } if (span.marker.inclusiveRight && span.to == line.text.length) { return true } for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i]; if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) { return true } } } // Find the height above the given line. function heightAtLine(lineObj) { lineObj = visualLine(lineObj); var h = 0, chunk = lineObj.parent; for (var i = 0; i < chunk.lines.length; ++i) { var line = chunk.lines[i]; if (line == lineObj) { break } else { h += line.height; } } for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { for (var i$1 = 0; i$1 < p.children.length; ++i$1) { var cur = p.children[i$1]; if (cur == chunk) { break } else { h += cur.height; } } } return h } // Compute the character length of a line, taking into account // collapsed ranges (see markText) that might hide parts, and join // other lines onto it. function lineLength(line) { if (line.height == 0) { return 0 } var len = line.text.length, merged, cur = line; while (merged = collapsedSpanAtStart(cur)) { var found = merged.find(0, true); cur = found.from.line; len += found.from.ch - found.to.ch; } cur = line; while (merged = collapsedSpanAtEnd(cur)) { var found$1 = merged.find(0, true); len -= cur.text.length - found$1.from.ch; cur = found$1.to.line; len += cur.text.length - found$1.to.ch; } return len } // Find the longest line in the document. function findMaxLine(cm) { var d = cm.display, doc = cm.doc; d.maxLine = getLine(doc, doc.first); d.maxLineLength = lineLength(d.maxLine); d.maxLineChanged = true; doc.iter(function (line) { var len = lineLength(line); if (len > d.maxLineLength) { d.maxLineLength = len; d.maxLine = line; } }); } // BIDI HELPERS function iterateBidiSections(order, from, to, f) { if (!order) { return f(from, to, "ltr", 0) } var found = false; for (var i = 0; i < order.length; ++i) { var part = order[i]; if (part.from < to && part.to > from || from == to && part.to == from) { f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); found = true; } } if (!found) { f(from, to, "ltr"); } } var bidiOther = null; function getBidiPartAt(order, ch, sticky) { var found; bidiOther = null; for (var i = 0; i < order.length; ++i) { var cur = order[i]; if (cur.from < ch && cur.to > ch) { return i } if (cur.to == ch) { if (cur.from != cur.to && sticky == "before") { found = i; } else { bidiOther = i; } } if (cur.from == ch) { if (cur.from != cur.to && sticky != "before") { found = i; } else { bidiOther = i; } } } return found != null ? found : bidiOther } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. var bidiOrdering = (function() { // Character types for codepoints 0 to 0xff var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; // Character types for codepoints 0x600 to 0x6f9 var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; function charType(code) { if (code <= 0xf7) { return lowTypes.charAt(code) } else if (0x590 <= code && code <= 0x5f4) { return "R" } else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } else if (0x6ee <= code && code <= 0x8ac) { return "r" } else if (0x2000 <= code && code <= 0x200b) { return "w" } else if (code == 0x200c) { return "b" } else { return "L" } } var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; function BidiSpan(level, from, to) { this.level = level; this.from = from; this.to = to; } return function(str, direction) { var outerType = direction == "ltr" ? "L" : "R"; if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } var len = str.length, types = []; for (var i = 0; i < len; ++i) { types.push(charType(str.charCodeAt(i))); } // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { var type = types[i$1]; if (type == "m") { types[i$1] = prev; } else { prev = type; } } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { var type$1 = types[i$2]; if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { var type$2 = types[i$3]; if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } else if (type$2 == "," && prev$1 == types[i$3+1] && (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } prev$1 = type$2; } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (var i$4 = 0; i$4 < len; ++i$4) { var type$3 = types[i$4]; if (type$3 == ",") { types[i$4] = "N"; } else if (type$3 == "%") { var end = (void 0); for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; for (var j = i$4; j < end; ++j) { types[j] = replace; } i$4 = end - 1; } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { var type$4 = types[i$5]; if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } else if (isStrong.test(type$4)) { cur$1 = type$4; } } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (var i$6 = 0; i$6 < len; ++i$6) { if (isNeutral.test(types[i$6])) { var end$1 = (void 0); for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} var before = (i$6 ? types[i$6-1] : outerType) == "L"; var after = (end$1 < len ? types[end$1] : outerType) == "L"; var replace$1 = before == after ? (before ? "L" : "R") : outerType; for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } i$6 = end$1 - 1; } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. var order = [], m; for (var i$7 = 0; i$7 < len;) { if (countsAsLeft.test(types[i$7])) { var start = i$7; for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} order.push(new BidiSpan(0, start, i$7)); } else { var pos = i$7, at = order.length; for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} for (var j$2 = pos; j$2 < i$7;) { if (countsAsNum.test(types[j$2])) { if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); } var nstart = j$2; for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} order.splice(at, 0, new BidiSpan(2, nstart, j$2)); pos = j$2; } else { ++j$2; } } if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } } } if (direction == "ltr") { if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length; order.unshift(new BidiSpan(0, 0, m[0].length)); } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length; order.push(new BidiSpan(0, len - m[0].length, len)); } } return direction == "rtl" ? order.reverse() : order } })(); // Get the bidi ordering for the given line (and cache it). Returns // false for lines that are fully left-to-right, and an array of // BidiSpan objects otherwise. function getOrder(line, direction) { var order = line.order; if (order == null) { order = line.order = bidiOrdering(line.text, direction); } return order } // EVENT HANDLING // Lightweight event framework. on/off also work on DOM nodes, // registering native DOM handlers. var noHandlers = []; var on = function(emitter, type, f) { if (emitter.addEventListener) { emitter.addEventListener(type, f, false); } else if (emitter.attachEvent) { emitter.attachEvent("on" + type, f); } else { var map$$1 = emitter._handlers || (emitter._handlers = {}); map$$1[type] = (map$$1[type] || noHandlers).concat(f); } }; function getHandlers(emitter, type) { return emitter._handlers && emitter._handlers[type] || noHandlers } function off(emitter, type, f) { if (emitter.removeEventListener) { emitter.removeEventListener(type, f, false); } else if (emitter.detachEvent) { emitter.detachEvent("on" + type, f); } else { var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; if (arr) { var index = indexOf(arr, f); if (index > -1) { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } } } } function signal(emitter, type /*, values...*/) { var handlers = getHandlers(emitter, type); if (!handlers.length) { return } var args = Array.prototype.slice.call(arguments, 2); for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } } // The DOM events that CodeMirror handles can be overridden by // registering a (non-DOM) handler on the editor for the event name, // and preventDefault-ing the event in that handler. function signalDOMEvent(cm, e, override) { if (typeof e == "string") { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } signal(cm, override || e.type, cm, e); return e_defaultPrevented(e) || e.codemirrorIgnore } function signalCursorActivity(cm) { var arr = cm._handlers && cm._handlers.cursorActivity; if (!arr) { return } var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) { set.push(arr[i]); } } } function hasHandler(emitter, type) { return getHandlers(emitter, type).length > 0 } // Add on and off methods to a constructor's prototype, to make // registering events on such objects more convenient. function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f);}; ctor.prototype.off = function(type, f) {off(this, type, f);}; } // Due to the fact that we still support jurassic IE versions, some // compatibility wrappers are needed. function e_preventDefault(e) { if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } } function e_stopPropagation(e) { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } } function e_defaultPrevented(e) { return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false } function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} function e_target(e) {return e.target || e.srcElement} function e_button(e) { var b = e.which; if (b == null) { if (e.button & 1) { b = 1; } else if (e.button & 2) { b = 3; } else if (e.button & 4) { b = 2; } } if (mac && e.ctrlKey && b == 1) { b = 3; } return b } // Detect drag-and-drop var dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie && ie_version < 9) { return false } var div = elt('div'); return "draggable" in div || "dragDrop" in div }(); var zwspSupported; function zeroWidthElement(measure) { if (zwspSupported == null) { var test = elt("span", "\u200b"); removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); if (measure.firstChild.offsetHeight != 0) { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } } var node = zwspSupported ? elt("span", "\u200b") : elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); node.setAttribute("cm-text", ""); return node } // Feature-detect IE's crummy client rect reporting for bidi text var badBidiRects; function hasBadBidiRects(measure) { if (badBidiRects != null) { return badBidiRects } var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); var r0 = range(txt, 0, 1).getBoundingClientRect(); var r1 = range(txt, 1, 2).getBoundingClientRect(); removeChildren(measure); if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) return badBidiRects = (r1.right - r0.right < 3) } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { var pos = 0, result = [], l = string.length; while (pos <= l) { var nl = string.indexOf("\n", pos); if (nl == -1) { nl = string.length; } var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); var rt = line.indexOf("\r"); if (rt != -1) { result.push(line.slice(0, rt)); pos += rt + 1; } else { result.push(line); pos = nl + 1; } } return result } : function (string) { return string.split(/\r\n?|\n/); }; var hasSelection = window.getSelection ? function (te) { try { return te.selectionStart != te.selectionEnd } catch(e) { return false } } : function (te) { var range$$1; try {range$$1 = te.ownerDocument.selection.createRange();} catch(e) {} if (!range$$1 || range$$1.parentElement() != te) { return false } return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 }; var hasCopyEvent = (function () { var e = elt("div"); if ("oncopy" in e) { return true } e.setAttribute("oncopy", "return;"); return typeof e.oncopy == "function" })(); var badZoomedRects = null; function hasBadZoomedRects(measure) { if (badZoomedRects != null) { return badZoomedRects } var node = removeChildrenAndAdd(measure, elt("span", "x")); var normal = node.getBoundingClientRect(); var fromRange = range(node, 0, 1).getBoundingClientRect(); return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 } // Known modes, by name and by MIME var modes = {}, mimeModes = {}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) function defineMode(name, mode) { if (arguments.length > 2) { mode.dependencies = Array.prototype.slice.call(arguments, 2); } modes[name] = mode; } function defineMIME(mime, spec) { mimeModes[mime] = spec; } // Given a MIME type, a {name, ...options} config object, or a name // string, return a mode config object. function resolveMode(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec]; } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { var found = mimeModes[spec.name]; if (typeof found == "string") { found = {name: found}; } spec = createObj(found, spec); spec.name = found.name; } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return resolveMode("application/xml") } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { return resolveMode("application/json") } if (typeof spec == "string") { return {name: spec} } else { return spec || {name: "null"} } } // Given a mode spec (anything that resolveMode accepts), find and // initialize an actual mode object. function getMode(options, spec) { spec = resolveMode(spec); var mfactory = modes[spec.name]; if (!mfactory) { return getMode(options, "text/plain") } var modeObj = mfactory(options, spec); if (modeExtensions.hasOwnProperty(spec.name)) { var exts = modeExtensions[spec.name]; for (var prop in exts) { if (!exts.hasOwnProperty(prop)) { continue } if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } modeObj[prop] = exts[prop]; } } modeObj.name = spec.name; if (spec.helperType) { modeObj.helperType = spec.helperType; } if (spec.modeProps) { for (var prop$1 in spec.modeProps) { modeObj[prop$1] = spec.modeProps[prop$1]; } } return modeObj } // This can be used to attach properties to mode objects from // outside the actual mode definition. var modeExtensions = {}; function extendMode(mode, properties) { var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); copyObj(properties, exts); } function copyState(mode, state) { if (state === true) { return state } if (mode.copyState) { return mode.copyState(state) } var nstate = {}; for (var n in state) { var val = state[n]; if (val instanceof Array) { val = val.concat([]); } nstate[n] = val; } return nstate } // Given a mode and a state (for that mode), find the inner mode and // state at the position that the state refers to. function innerMode(mode, state) { var info; while (mode.innerMode) { info = mode.innerMode(state); if (!info || info.mode == mode) { break } state = info.state; mode = info.mode; } return info || {mode: mode, state: state} } function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true } // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. var StringStream = function(string, tabSize, lineOracle) { this.pos = this.start = 0; this.string = string; this.tabSize = tabSize || 8; this.lastColumnPos = this.lastColumnValue = 0; this.lineStart = 0; this.lineOracle = lineOracle; }; StringStream.prototype.eol = function () {return this.pos >= this.string.length}; StringStream.prototype.sol = function () {return this.pos == this.lineStart}; StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; StringStream.prototype.next = function () { if (this.pos < this.string.length) { return this.string.charAt(this.pos++) } }; StringStream.prototype.eat = function (match) { var ch = this.string.charAt(this.pos); var ok; if (typeof match == "string") { ok = ch == match; } else { ok = ch && (match.test ? match.test(ch) : match(ch)); } if (ok) {++this.pos; return ch} }; StringStream.prototype.eatWhile = function (match) { var start = this.pos; while (this.eat(match)){} return this.pos > start }; StringStream.prototype.eatSpace = function () { var this$1 = this; var start = this.pos; while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } return this.pos > start }; StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; StringStream.prototype.skipTo = function (ch) { var found = this.string.indexOf(ch, this.pos); if (found > -1) {this.pos = found; return true} }; StringStream.prototype.backUp = function (n) {this.pos -= n;}; StringStream.prototype.column = function () { if (this.lastColumnPos < this.start) { this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); this.lastColumnPos = this.start; } return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.indentation = function () { return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) }; StringStream.prototype.match = function (pattern, consume, caseInsensitive) { if (typeof pattern == "string") { var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; var substr = this.string.substr(this.pos, pattern.length); if (cased(substr) == cased(pattern)) { if (consume !== false) { this.pos += pattern.length; } return true } } else { var match = this.string.slice(this.pos).match(pattern); if (match && match.index > 0) { return null } if (match && consume !== false) { this.pos += match[0].length; } return match } }; StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; StringStream.prototype.hideFirstChars = function (n, inner) { this.lineStart += n; try { return inner() } finally { this.lineStart -= n; } }; StringStream.prototype.lookAhead = function (n) { var oracle = this.lineOracle; return oracle && oracle.lookAhead(n) }; StringStream.prototype.baseToken = function () { var oracle = this.lineOracle; return oracle && oracle.baseToken(this.pos) }; var SavedContext = function(state, lookAhead) { this.state = state; this.lookAhead = lookAhead; }; var Context = function(doc, state, line, lookAhead) { this.state = state; this.doc = doc; this.line = line; this.maxLookAhead = lookAhead || 0; this.baseTokens = null; this.baseTokenPos = 1; }; Context.prototype.lookAhead = function (n) { var line = this.doc.getLine(this.line + n); if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } return line }; Context.prototype.baseToken = function (n) { var this$1 = this; if (!this.baseTokens) { return null } while (this.baseTokens[this.baseTokenPos] <= n) { this$1.baseTokenPos += 2; } var type = this.baseTokens[this.baseTokenPos + 1]; return {type: type && type.replace(/( |^)overlay .*/, ""), size: this.baseTokens[this.baseTokenPos] - n} }; Context.prototype.nextLine = function () { this.line++; if (this.maxLookAhead > 0) { this.maxLookAhead--; } }; Context.fromSaved = function (doc, saved, line) { if (saved instanceof SavedContext) { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } else { return new Context(doc, copyState(doc.mode, saved), line) } }; Context.prototype.save = function (copy) { var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state }; // Compute a style array (an array starting with a mode generation // -- for invalidation -- followed by pairs of end positions and // style strings), which is used to highlight the tokens on the // line. function highlightLine(cm, line, context, forceToEnd) { // A styles array always starts with a number identifying the // mode/overlays that it is based on (for easy invalidation). var st = [cm.state.modeGen], lineClasses = {}; // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, lineClasses, forceToEnd); var state = context.state; // Run overlays, adjust style array. var loop = function ( o ) { context.baseTokens = st; var overlay = cm.state.overlays[o], i = 1, at = 0; context.state = true; runMode(cm, line.text, overlay.mode, context, function (end, style) { var start = i; // Ensure there's a token end at the current position, and that i points at it while (at < end) { var i_end = st[i]; if (i_end > end) { st.splice(i, 1, end, st[i+1], i_end); } i += 2; at = Math.min(end, i_end); } if (!style) { return } if (overlay.opaque) { st.splice(start, i - start, end, "overlay " + style); i = start + 2; } else { for (; start < i; start += 2) { var cur = st[start+1]; st[start+1] = (cur ? cur + " " : "") + "overlay " + style; } } }, lineClasses); context.state = state; context.baseTokens = null; context.baseTokenPos = 1; }; for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} } function getLineStyles(cm, line, updateFrontier) { if (!line.styles || line.styles[0] != cm.state.modeGen) { var context = getContextBefore(cm, lineNo(line)); var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); var result = highlightLine(cm, line, context); if (resetState) { context.state = resetState; } line.stateAfter = context.save(!resetState); line.styles = result.styles; if (result.classes) { line.styleClasses = result.classes; } else if (line.styleClasses) { line.styleClasses = null; } if (updateFrontier === cm.doc.highlightFrontier) { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } } return line.styles } function getContextBefore(cm, n, precise) { var doc = cm.doc, display = cm.display; if (!doc.mode.startState) { return new Context(doc, true, n) } var start = findStartLine(cm, n, precise); var saved = start > doc.first && getLine(doc, start - 1).stateAfter; var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); doc.iter(start, n, function (line) { processLine(cm, line.text, context); var pos = context.line; line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; context.nextLine(); }); if (precise) { doc.modeFrontier = context.line; } return context } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. Used for lines that // aren't currently visible. function processLine(cm, text, context, startAt) { var mode = cm.doc.mode; var stream = new StringStream(text, cm.options.tabSize, context); stream.start = stream.pos = startAt || 0; if (text == "") { callBlankLine(mode, context.state); } while (!stream.eol()) { readToken(mode, stream, context.state); stream.start = stream.pos; } } function callBlankLine(mode, state) { if (mode.blankLine) { return mode.blankLine(state) } if (!mode.innerMode) { return } var inner = innerMode(mode, state); if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } } function readToken(mode, stream, state, inner) { for (var i = 0; i < 10; i++) { if (inner) { inner[0] = innerMode(mode, state).mode; } var style = mode.token(stream, state); if (stream.pos > stream.start) { return style } } throw new Error("Mode " + mode.name + " failed to advance stream.") } var Token = function(stream, type, state) { this.start = stream.start; this.end = stream.pos; this.string = stream.current(); this.type = type || null; this.state = state; }; // Utility for getTokenAt and getLineTokens function takeToken(cm, pos, precise, asArray) { var doc = cm.doc, mode = doc.mode, style; pos = clipPos(doc, pos); var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; if (asArray) { tokens = []; } while ((asArray || stream.pos < pos.ch) && !stream.eol()) { stream.start = stream.pos; style = readToken(mode, stream, context.state); if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } } return asArray ? tokens : new Token(stream, style, context.state) } function extractLineClasses(type, output) { if (type) { for (;;) { var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); if (!lineClass) { break } type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); var prop = lineClass[1] ? "bgClass" : "textClass"; if (output[prop] == null) { output[prop] = lineClass[2]; } else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) { output[prop] += " " + lineClass[2]; } } } return type } // Run the given mode's parser over a line, calling f for each token. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { var flattenSpans = mode.flattenSpans; if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } var curStart = 0, curStyle = null; var stream = new StringStream(text, cm.options.tabSize, context), style; var inner = cm.options.addModeClass && [null]; if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false; if (forceToEnd) { processLine(cm, text, context, stream.pos); } stream.pos = text.length; style = null; } else { style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); } if (inner) { var mName = inner[0].name; if (mName) { style = "m-" + (style ? mName + " " + style : mName); } } if (!flattenSpans || curStyle != style) { while (curStart < stream.start) { curStart = Math.min(stream.start, curStart + 5000); f(curStart, curStyle); } curStyle = style; } stream.start = stream.pos; } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 // characters, and returns inaccurate measurements in nodes // starting around 5000 chars. var pos = Math.min(stream.pos, curStart + 5000); f(pos, curStyle); curStart = pos; } } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n, precise) { var minindent, minline, doc = cm.doc; var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); for (var search = n; search > lim; --search) { if (search <= doc.first) { return doc.first } var line = getLine(doc, search - 1), after = line.stateAfter; if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) { return search } var indented = countColumn(line.text, null, cm.options.tabSize); if (minline == null || minindent > indented) { minline = search - 1; minindent = indented; } } return minline } function retreatFrontier(doc, n) { doc.modeFrontier = Math.min(doc.modeFrontier, n); if (doc.highlightFrontier < n - 10) { return } var start = doc.first; for (var line = n - 1; line > start; line--) { var saved = getLine(doc, line).stateAfter; // change is on 3 // state on line 1 looked ahead 2 -- so saw 3 // test 1 + 2 < 3 should cover this if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { start = line + 1; break } } doc.highlightFrontier = Math.min(doc.highlightFrontier, start); } // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). var Line = function(text, markedSpans, estimateHeight) { this.text = text; attachMarkedSpans(this, markedSpans); this.height = estimateHeight ? estimateHeight(this) : 1; }; Line.prototype.lineNo = function () { return lineNo(this) }; eventMixin(Line); // Change the content (text, markers) of a line. Automatically // invalidates cached information and tries to re-estimate the // line's height. function updateLine(line, text, markedSpans, estimateHeight) { line.text = text; if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } if (line.order != null) { line.order = null; } detachMarkedSpans(line); attachMarkedSpans(line, markedSpans); var estHeight = estimateHeight ? estimateHeight(line) : 1; if (estHeight != line.height) { updateLineHeight(line, estHeight); } } // Detach a line from the document tree and its markers. function cleanUpLine(line) { line.parent = null; detachMarkedSpans(line); } // Convert a style as returned by a mode (either null, or a string // containing one or more styles) to a CSS style. This is cached, // and also looks for line-wide styles. var styleToClassCache = {}, styleToClassCacheWithMode = {}; function interpretTokenStyle(style, options) { if (!style || /^\s*$/.test(style)) { return null } var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")) } // Render the DOM representation of the text of a line. Also builds // up a 'line map', which points at the DOM nodes that represent // specific stretches of text, and is used by the measuring code. // The returned object contains the DOM node, this map, and // information about line-wide styles that were set by the mode. function buildLineContent(cm, lineView) { // The padding-right forces the element to have a 'border', which // is needed on Webkit to be able to get line-level bounding // rectangles for it (in measureChar). var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, col: 0, pos: 0, cm: cm, trailingSpace: false, splitSpaces: cm.getOption("lineWrapping")}; lineView.measure = {}; // Iterate over the logical lines that make up this visual line. for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); builder.pos = 0; builder.addToken = buildToken; // Optionally wire in some hacks into the token-rendering // algorithm, to deal with browser quirks. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) { builder.addToken = buildTokenBadBidi(builder.addToken, order); } builder.map = []; var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); if (line.styleClasses) { if (line.styleClasses.bgClass) { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } if (line.styleClasses.textClass) { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } } // Ensure at least a single node is present, for measuring. if (builder.map.length == 0) { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } // Store the map and a cache object for the current logical line if (i == 0) { lineView.measure.map = builder.map; lineView.measure.cache = {}; } else { (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); } } // See issue #2901 if (webkit) { var last = builder.content.lastChild; if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) { builder.content.className = "cm-tab-wrap-hack"; } } signal(cm, "renderLine", cm, lineView.line, builder.pre); if (builder.pre.className) { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } return builder } function defaultSpecialCharPlaceholder(ch) { var token = elt("span", "\u2022", "cm-invalidchar"); token.title = "\\u" + ch.charCodeAt(0).toString(16); token.setAttribute("aria-label", token.title); return token } // Build up the DOM representation for a single token, and add it to // the line map. Takes care to render special characters separately. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { if (!text) { return } var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; var special = builder.cm.state.specialChars, mustWrap = false; var content; if (!special.test(text)) { builder.col += text.length; content = document.createTextNode(displayText); builder.map.push(builder.pos, builder.pos + text.length, content); if (ie && ie_version < 9) { mustWrap = true; } builder.pos += text.length; } else { content = document.createDocumentFragment(); var pos = 0; while (true) { special.lastIndex = pos; var m = special.exec(text); var skipped = m ? m.index - pos : text.length - pos; if (skipped) { var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } else { content.appendChild(txt); } builder.map.push(builder.pos, builder.pos + skipped, txt); builder.col += skipped; builder.pos += skipped; } if (!m) { break } pos += skipped + 1; var txt$1 = (void 0); if (m[0] == "\t") { var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); txt$1.setAttribute("role", "presentation"); txt$1.setAttribute("cm-text", "\t"); builder.col += tabWidth; } else if (m[0] == "\r" || m[0] == "\n") { txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); txt$1.setAttribute("cm-text", m[0]); builder.col += 1; } else { txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); txt$1.setAttribute("cm-text", m[0]); if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } else { content.appendChild(txt$1); } builder.col += 1; } builder.map.push(builder.pos, builder.pos + 1, txt$1); builder.pos++; } } builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; if (style || startStyle || endStyle || mustWrap || css) { var fullStyle = style || ""; if (startStyle) { fullStyle += startStyle; } if (endStyle) { fullStyle += endStyle; } var token = elt("span", [content], fullStyle, css); if (attributes) { for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") { token.setAttribute(attr, attributes[attr]); } } } return builder.content.appendChild(token) } builder.content.appendChild(content); } // Change some spaces to NBSP to prevent the browser from collapsing // trailing spaces at the end of a line when rendering text (issue #1362). function splitSpaces(text, trailingBefore) { if (text.length > 1 && !/ /.test(text)) { return text } var spaceBefore = trailingBefore, result = ""; for (var i = 0; i < text.length; i++) { var ch = text.charAt(i); if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) { ch = "\u00a0"; } result += ch; spaceBefore = ch == " "; } return result } // Work around nonsense dimensions being reported for stretches of // right-to-left text. function buildTokenBadBidi(inner, order) { return function (builder, text, style, startStyle, endStyle, css, attributes) { style = style ? style + " cm-force-border" : "cm-force-border"; var start = builder.pos, end = start + text.length; for (;;) { // Find the part that overlaps with the start of this text var part = (void 0); for (var i = 0; i < order.length; i++) { part = order[i]; if (part.to > start && part.from <= start) { break } } if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); startStyle = null; text = text.slice(part.to - start); start = part.to; } } } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { var widget = !ignoreWidget && marker.widgetNode; if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { if (!widget) { widget = builder.content.appendChild(document.createElement("span")); } widget.setAttribute("cm-marker", marker.id); } if (widget) { builder.cm.display.input.setUneditable(widget); builder.content.appendChild(widget); } builder.pos += size; builder.trailingSpace = false; } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder, styles) { var spans = line.markedSpans, allText = line.text, at = 0; if (!spans) { for (var i$1 = 1; i$1 < styles.length; i$1+=2) { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } return } var len = allText.length, pos = 0, i = 1, text = "", style, css; var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = css = ""; attributes = null; collapsed = null; nextChange = Infinity; var foundBookmarks = [], endStyles = (void 0); for (var j = 0; j < spans.length; ++j) { var sp = spans[j], m = sp.marker; if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { foundBookmarks.push(m); } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { if (sp.to != null && sp.to != pos && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; } if (m.className) { spanStyle += " " + m.className; } if (m.css) { css = (css ? css + ";" : "") + m.css; } if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } // support for the old title property // https://github.com/codemirror/CodeMirror/pull/5673 if (m.title) { (attributes || (attributes = {})).title = m.title; } if (m.attributes) { for (var attr in m.attributes) { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } } if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) { collapsed = sp; } } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from; } } if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null); if (collapsed.to == null) { return } if (collapsed.to == pos) { collapsed = false; } } } if (pos >= len) { break } var upto = Math.min(len, nextChange); while (true) { if (text) { var end = pos + text.length; if (!collapsed) { var tokenText = end > upto ? text.slice(0, upto - pos) : text; builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} pos = end; spanStartStyle = ""; } text = allText.slice(at, at = styles[i++]); style = interpretTokenStyle(styles[i++], builder.cm.options); } } } // These objects are used to represent the visible (currently drawn) // part of the document. A LineView may correspond to multiple // logical lines, if those are connected by collapsed ranges. function LineView(doc, line, lineN) { // The starting line this.line = line; // Continuing lines, if any this.rest = visualLineContinued(line); // Number of logical lines in this visual line this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; this.node = this.text = null; this.hidden = lineIsHidden(doc, line); } // Create a range of LineView objects for the given lines. function buildViewArray(cm, from, to) { var array = [], nextPos; for (var pos = from; pos < to; pos = nextPos) { var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); nextPos = pos + view.size; array.push(view); } return array } var operationGroup = null; function pushOperation(op) { if (operationGroup) { operationGroup.ops.push(op); } else { op.ownsGroup = operationGroup = { ops: [op], delayedCallbacks: [] }; } } function fireCallbacksForOps(group) { // Calls delayed callbacks and cursorActivity handlers until no // new ones appear var callbacks = group.delayedCallbacks, i = 0; do { for (; i < callbacks.length; i++) { callbacks[i].call(null); } for (var j = 0; j < group.ops.length; j++) { var op = group.ops[j]; if (op.cursorActivityHandlers) { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } } } while (i < callbacks.length) } function finishOperation(op, endCb) { var group = op.ownsGroup; if (!group) { return } try { fireCallbacksForOps(group); } finally { operationGroup = null; endCb(group); } } var orphanDelayedCallbacks = null; // Often, we want to signal events at a point where we are in the // middle of some work, but don't want the handler to start calling // other methods on the editor, which might be in an inconsistent // state or simply not expect any other events to happen. // signalLater looks whether there are any handlers, and schedules // them to be executed when the last operation ends, or, if no // operation is active, when a timeout fires. function signalLater(emitter, type /*, values...*/) { var arr = getHandlers(emitter, type); if (!arr.length) { return } var args = Array.prototype.slice.call(arguments, 2), list; if (operationGroup) { list = operationGroup.delayedCallbacks; } else if (orphanDelayedCallbacks) { list = orphanDelayedCallbacks; } else { list = orphanDelayedCallbacks = []; setTimeout(fireOrphanDelayed, 0); } var loop = function ( i ) { list.push(function () { return arr[i].apply(null, args); }); }; for (var i = 0; i < arr.length; ++i) loop( i ); } function fireOrphanDelayed() { var delayed = orphanDelayedCallbacks; orphanDelayedCallbacks = null; for (var i = 0; i < delayed.length; ++i) { delayed[i](); } } // When an aspect of a line changes, a string is added to // lineView.changes. This updates the relevant part of the line's // DOM structure. function updateLineForChanges(cm, lineView, lineN, dims) { for (var j = 0; j < lineView.changes.length; j++) { var type = lineView.changes[j]; if (type == "text") { updateLineText(cm, lineView); } else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } else if (type == "class") { updateLineClasses(cm, lineView); } else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } } lineView.changes = null; } // Lines with gutter elements, widgets or a background class need to // be wrapped, and have the extra elements added to the wrapper div function ensureLineWrapped(lineView) { if (lineView.node == lineView.text) { lineView.node = elt("div", null, null, "position: relative"); if (lineView.text.parentNode) { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } lineView.node.appendChild(lineView.text); if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } } return lineView.node } function updateLineBackground(cm, lineView) { var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; if (cls) { cls += " CodeMirror-linebackground"; } if (lineView.background) { if (cls) { lineView.background.className = cls; } else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } } else if (cls) { var wrap = ensureLineWrapped(lineView); lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); cm.display.input.setUneditable(lineView.background); } } // Wrapper around buildLineContent which will reuse the structure // in display.externalMeasured when possible. function getLineContent(cm, lineView) { var ext = cm.display.externalMeasured; if (ext && ext.line == lineView.line) { cm.display.externalMeasured = null; lineView.measure = ext.measure; return ext.built } return buildLineContent(cm, lineView) } // Redraw the line's text. Interacts with the background and text // classes because the mode may output tokens that influence these // classes. function updateLineText(cm, lineView) { var cls = lineView.text.className; var built = getLineContent(cm, lineView); if (lineView.text == lineView.node) { lineView.node = built.pre; } lineView.text.parentNode.replaceChild(built.pre, lineView.text); lineView.text = built.pre; if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { lineView.bgClass = built.bgClass; lineView.textClass = built.textClass; updateLineClasses(cm, lineView); } else if (cls) { lineView.text.className = cls; } } function updateLineClasses(cm, lineView) { updateLineBackground(cm, lineView); if (lineView.line.wrapClass) { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } else if (lineView.node != lineView.text) { lineView.node.className = ""; } var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; lineView.text.className = textClass || ""; } function updateLineGutter(cm, lineView, lineN, dims) { if (lineView.gutter) { lineView.node.removeChild(lineView.gutter); lineView.gutter = null; } if (lineView.gutterBackground) { lineView.node.removeChild(lineView.gutterBackground); lineView.gutterBackground = null; } if (lineView.line.gutterClass) { var wrap = ensureLineWrapped(lineView); lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); cm.display.input.setUneditable(lineView.gutterBackground); wrap.insertBefore(lineView.gutterBackground, lineView.text); } var markers = lineView.line.gutterMarkers; if (cm.options.lineNumbers || markers) { var wrap$1 = ensureLineWrapped(lineView); var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); cm.display.input.setUneditable(gutterWrap); wrap$1.insertBefore(gutterWrap, lineView.text); if (lineView.line.gutterClass) { gutterWrap.className += " " + lineView.line.gutterClass; } if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { lineView.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } if (markers) { for (var k = 0; k < cm.options.gutters.length; ++k) { var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; if (found) { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } } } } } function updateLineWidgets(cm, lineView, dims) { if (lineView.alignable) { lineView.alignable = null; } for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { next = node.nextSibling; if (node.className == "CodeMirror-linewidget") { lineView.node.removeChild(node); } } insertLineWidgets(cm, lineView, dims); } // Build a line's DOM representation from scratch function buildLineElement(cm, lineView, lineN, dims) { var built = getLineContent(cm, lineView); lineView.text = lineView.node = built.pre; if (built.bgClass) { lineView.bgClass = built.bgClass; } if (built.textClass) { lineView.textClass = built.textClass; } updateLineClasses(cm, lineView); updateLineGutter(cm, lineView, lineN, dims); insertLineWidgets(cm, lineView, dims); return lineView.node } // A lineView may contain multiple logical lines (when merged by // collapsed spans). The widgets for all of them need to be drawn. function insertLineWidgets(cm, lineView, dims) { insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } } function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { if (!line.widgets) { return } var wrap = ensureLineWrapped(lineView); for (var i = 0, ws = line.widgets; i < ws.length; ++i) { var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } positionLineWidget(widget, node, lineView, dims); cm.display.input.setUneditable(node); if (allowAbove && widget.above) { wrap.insertBefore(node, lineView.gutter || lineView.text); } else { wrap.appendChild(node); } signalLater(widget, "redraw"); } } function positionLineWidget(widget, node, lineView, dims) { if (widget.noHScroll) { (lineView.alignable || (lineView.alignable = [])).push(node); var width = dims.wrapperWidth; node.style.left = dims.fixedPos + "px"; if (!widget.coverGutter) { width -= dims.gutterTotalWidth; node.style.paddingLeft = dims.gutterTotalWidth + "px"; } node.style.width = width + "px"; } if (widget.coverGutter) { node.style.zIndex = 5; node.style.position = "relative"; if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } } } function widgetHeight(widget) { if (widget.height != null) { return widget.height } var cm = widget.doc.cm; if (!cm) { return 0 } if (!contains(document.body, widget.node)) { var parentStyle = "position: relative;"; if (widget.coverGutter) { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } if (widget.noHScroll) { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); } return widget.height = widget.node.parentNode.offsetHeight } // Return true when the given mouse event happened in a widget function eventInWidget(display, e) { for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || (n.parentNode == display.sizer && n != display.mover)) { return true } } } // POSITION MEASUREMENT function paddingTop(display) {return display.lineSpace.offsetTop} function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} function paddingH(display) { if (display.cachedPaddingH) { return display.cachedPaddingH } var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } return data } function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } function displayWidth(cm) { return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth } function displayHeight(cm) { return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight } // Ensure the lineView.wrapping.heights array is populated. This is // an array of bottom offsets for the lines that make up a drawn // line. When lineWrapping is on, there might be more than one // height. function ensureLineHeights(cm, lineView, rect) { var wrapping = cm.options.lineWrapping; var curWidth = wrapping && displayWidth(cm); if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { var heights = lineView.measure.heights = []; if (wrapping) { lineView.measure.width = curWidth; var rects = lineView.text.firstChild.getClientRects(); for (var i = 0; i < rects.length - 1; i++) { var cur = rects[i], next = rects[i + 1]; if (Math.abs(cur.bottom - next.bottom) > 2) { heights.push((cur.bottom + next.top) / 2 - rect.top); } } } heights.push(rect.bottom - rect.top); } } // Find a line map (mapping character offsets to text nodes) and a // measurement cache for the given line number. (A line view might // contain multiple lines when collapsed ranges are present.) function mapFromLineView(lineView, line, lineN) { if (lineView.line == line) { return {map: lineView.measure.map, cache: lineView.measure.cache} } for (var i = 0; i < lineView.rest.length; i++) { if (lineView.rest[i] == line) { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) { if (lineNo(lineView.rest[i$1]) > lineN) { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } } // Render a line into the hidden node display.externalMeasured. Used // when measurement is needed for a line that's not in the viewport. function updateExternalMeasurement(cm, line) { line = visualLine(line); var lineN = lineNo(line); var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); view.lineN = lineN; var built = view.built = buildLineContent(cm, view); view.text = built.pre; removeChildrenAndAdd(cm.display.lineMeasure, built.pre); return view } // Get a {top, bottom, left, right} box (in line-local coordinates) // for a given character. function measureChar(cm, line, ch, bias) { return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) } // Find a line view that corresponds to the given line number. function findViewForLine(cm, lineN) { if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) { return cm.display.view[findViewIndex(cm, lineN)] } var ext = cm.display.externalMeasured; if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) { return ext } } // Measurement can be split in two steps, the set-up work that // applies to the whole line, and the measurement of the actual // character. Functions like coordsChar, that need to do a lot of // measurements in a row, can thus ensure that the set-up work is // only done once. function prepareMeasureForLine(cm, line) { var lineN = lineNo(line); var view = findViewForLine(cm, lineN); if (view && !view.text) { view = null; } else if (view && view.changes) { updateLineForChanges(cm, view, lineN, getDimensions(cm)); cm.curOp.forceUpdate = true; } if (!view) { view = updateExternalMeasurement(cm, line); } var info = mapFromLineView(view, line, lineN); return { line: line, view: view, rect: null, map: info.map, cache: info.cache, before: info.before, hasHeights: false } } // Given a prepared measurement object, measures the position of an // actual character (or fetches it from the cache). function measureCharPrepared(cm, prepared, ch, bias, varHeight) { if (prepared.before) { ch = -1; } var key = ch + (bias || ""), found; if (prepared.cache.hasOwnProperty(key)) { found = prepared.cache[key]; } else { if (!prepared.rect) { prepared.rect = prepared.view.text.getBoundingClientRect(); } if (!prepared.hasHeights) { ensureLineHeights(cm, prepared.view, prepared.rect); prepared.hasHeights = true; } found = measureCharInner(cm, prepared, ch, bias); if (!found.bogus) { prepared.cache[key] = found; } } return {left: found.left, right: found.right, top: varHeight ? found.rtop : found.top, bottom: varHeight ? found.rbottom : found.bottom} } var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; function nodeAndOffsetInLineMap(map$$1, ch, bias) { var node, start, end, collapse, mStart, mEnd; // First, search the line map for the text node corresponding to, // or closest to, the target character. for (var i = 0; i < map$$1.length; i += 3) { mStart = map$$1[i]; mEnd = map$$1[i + 1]; if (ch < mStart) { start = 0; end = 1; collapse = "left"; } else if (ch < mEnd) { start = ch - mStart; end = start + 1; } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { end = mEnd - mStart; start = end - 1; if (ch >= mEnd) { collapse = "right"; } } if (start != null) { node = map$$1[i + 2]; if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) { collapse = bias; } if (bias == "left" && start == 0) { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { node = map$$1[(i -= 3) + 2]; collapse = "left"; } } if (bias == "right" && start == mEnd - mStart) { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { node = map$$1[(i += 3) + 2]; collapse = "right"; } } break } } return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} } function getUsefulRect(rects, bias) { var rect = nullRect; if (bias == "left") { for (var i = 0; i < rects.length; i++) { if ((rect = rects[i]).left != rect.right) { break } } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { if ((rect = rects[i$1]).left != rect.right) { break } } } return rect } function measureCharInner(cm, prepared, ch, bias) { var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); var node = place.node, start = place.start, end = place.end, collapse = place.collapse; var rect; if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { rect = node.parentNode.getBoundingClientRect(); } else { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } if (rect.left || rect.right || start == 0) { break } end = start; start = start - 1; collapse = "right"; } if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } } else { // If it is a widget, simply get the box for the whole widget. if (start > 0) { collapse = bias = "right"; } var rects; if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) { rect = rects[bias == "right" ? rects.length - 1 : 0]; } else { rect = node.getBoundingClientRect(); } } if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { var rSpan = node.parentNode.getClientRects()[0]; if (rSpan) { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } else { rect = nullRect; } } var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; var mid = (rtop + rbot) / 2; var heights = prepared.view.measure.heights; var i = 0; for (; i < heights.length - 1; i++) { if (mid < heights[i]) { break } } var top = i ? heights[i - 1] : 0, bot = heights[i]; var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, top: top, bottom: bot}; if (!rect.left && !rect.right) { result.bogus = true; } if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } return result } // Work around problem with bounding client rects on ranges being // returned incorrectly when zoomed on IE10 and below. function maybeUpdateRectForZooming(measure, rect) { if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) { return rect } var scaleX = screen.logicalXDPI / screen.deviceXDPI; var scaleY = screen.logicalYDPI / screen.deviceYDPI; return {left: rect.left * scaleX, right: rect.right * scaleX, top: rect.top * scaleY, bottom: rect.bottom * scaleY} } function clearLineMeasurementCacheFor(lineView) { if (lineView.measure) { lineView.measure.cache = {}; lineView.measure.heights = null; if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) { lineView.measure.caches[i] = {}; } } } } function clearLineMeasurementCache(cm) { cm.display.externalMeasure = null; removeChildren(cm.display.lineMeasure); for (var i = 0; i < cm.display.view.length; i++) { clearLineMeasurementCacheFor(cm.display.view[i]); } } function clearCaches(cm) { clearLineMeasurementCache(cm); cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } cm.display.lineNumChars = null; } function pageScrollX() { // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 // which causes page_Offset and bounding client rects to use // different reference viewports and invalidate our calculations. if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } return window.pageXOffset || (document.documentElement || document.body).scrollLeft } function pageScrollY() { if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } return window.pageYOffset || (document.documentElement || document.body).scrollTop } function widgetTopHeight(lineObj) { var height = 0; if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) { height += widgetHeight(lineObj.widgets[i]); } } } return height } // Converts a {top, bottom, left, right} box from line-local // coordinates into another coordinate system. Context may be one of // "line", "div" (display.lineDiv), "local"./null (editor), "window", // or "page". function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { if (!includeWidgets) { var height = widgetTopHeight(lineObj); rect.top += height; rect.bottom += height; } if (context == "line") { return rect } if (!context) { context = "local"; } var yOff = heightAtLine(lineObj); if (context == "local") { yOff += paddingTop(cm.display); } else { yOff -= cm.display.viewOffset; } if (context == "page" || context == "window") { var lOff = cm.display.lineSpace.getBoundingClientRect(); yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); rect.left += xOff; rect.right += xOff; } rect.top += yOff; rect.bottom += yOff; return rect } // Coverts a box from "div" coords to another coordinate system. // Context may be "window", "page", "div", or "local"./null. function fromCoordSystem(cm, coords, context) { if (context == "div") { return coords } var left = coords.left, top = coords.top; // First move into "page" coordinate system if (context == "page") { left -= pageScrollX(); top -= pageScrollY(); } else if (context == "local" || !context) { var localBox = cm.display.sizer.getBoundingClientRect(); left += localBox.left; top += localBox.top; } var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} } function charCoords(cm, pos, context, lineObj, bias) { if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) } // Returns a box for a given cursor position, which may have an // 'other' property containing the position of the secondary cursor // on a bidi boundary. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` // and after `char - 1` in writing order of `char - 1` // A cursor Pos(line, char, "after") is on the same visual line as `char` // and before `char` in writing order of `char` // Examples (upper-case letters are RTL, lower-case are LTR): // Pos(0, 1, ...) // before after // ab a|b a|b // aB a|B aB| // Ab |Ab A|b // AB B|A B|A // Every position after the last character on a line is considered to stick // to the last character on the line. function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { lineObj = lineObj || getLine(cm.doc, pos.line); if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } function get(ch, right) { var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); if (right) { m.left = m.right; } else { m.right = m.left; } return intoCoordSystem(cm, lineObj, m, context) } var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; if (ch >= lineObj.text.length) { ch = lineObj.text.length; sticky = "before"; } else if (ch <= 0) { ch = 0; sticky = "after"; } if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } function getBidi(ch, partPos, invert) { var part = order[partPos], right = part.level == 1; return get(invert ? ch - 1 : ch, right != invert) } var partPos = getBidiPartAt(order, ch, sticky); var other = bidiOther; var val = getBidi(ch, partPos, sticky == "before"); if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } return val } // Used to cheaply estimate the coordinates for a position. Used for // intermediate scroll updates. function estimateCoords(cm, pos) { var left = 0; pos = clipPos(cm.doc, pos); if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } var lineObj = getLine(cm.doc, pos.line); var top = heightAtLine(lineObj) + paddingTop(cm.display); return {left: left, right: left, top: top, bottom: top + lineObj.height} } // Positions returned by coordsChar contain some extra information. // xRel is the relative x position of the input coordinates compared // to the found position (so xRel > 0 means the coordinates are to // the right of the character position, for example). When outside // is true, that means the coordinates lie outside the line's // vertical range. function PosWithInfo(line, ch, sticky, outside, xRel) { var pos = Pos(line, ch, sticky); pos.xRel = xRel; if (outside) { pos.outside = true; } return pos } // Compute the character position closest to the given coordinates. // Input must be lineSpace-local ("div" coordinate system). function coordsChar(cm, x, y) { var doc = cm.doc; y += cm.display.viewOffset; if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) } var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; if (lineN > last) { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) } if (x < 0) { x = 0; } var lineObj = getLine(doc, lineN); for (;;) { var found = coordsCharInner(cm, lineObj, lineN, x, y); var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0)); if (!collapsed) { return found } var rangeEnd = collapsed.find(1); if (rangeEnd.line == lineN) { return rangeEnd } lineObj = getLine(doc, lineN = rangeEnd.line); } } function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { y -= widgetTopHeight(lineObj); var end = lineObj.text.length; var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); return {begin: begin, end: end} } function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) } // Returns true if the given side of a box is after the given // coordinates, in top-to-bottom, left-to-right order. function boxIsAfter(box, x, y, left) { return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x } function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { // Move y into line-local coordinate space y -= heightAtLine(lineObj); var preparedMeasure = prepareMeasureForLine(cm, lineObj); // When directly calling `measureCharPrepared`, we have to adjust // for the widgets at this line. var widgetHeight$$1 = widgetTopHeight(lineObj); var begin = 0, end = lineObj.text.length, ltr = true; var order = getOrder(lineObj, cm.doc.direction); // If the line isn't plain left-to-right text, first figure out // which bidi section the coordinates fall into. if (order) { var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y); ltr = part.level != 1; // The awkward -1 offsets are needed because findFirst (called // on these below) will treat its first bound as inclusive, // second as exclusive, but we want to actually address the // characters in the part's range begin = ltr ? part.from : part.to - 1; end = ltr ? part.to : part.from - 1; } // A binary search to find the first character whose bounding box // starts after the coordinates. If we run across any whose box wrap // the coordinates, store that. var chAround = null, boxAround = null; var ch = findFirst(function (ch) { var box = measureCharPrepared(cm, preparedMeasure, ch); box.top += widgetHeight$$1; box.bottom += widgetHeight$$1; if (!boxIsAfter(box, x, y, false)) { return false } if (box.top <= y && box.left <= x) { chAround = ch; boxAround = box; } return true }, begin, end); var baseX, sticky, outside = false; // If a box around the coordinates was found, use that if (boxAround) { // Distinguish coordinates nearer to the left or right side of the box var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; ch = chAround + (atStart ? 0 : 1); sticky = atStart ? "after" : "before"; baseX = atLeft ? boxAround.left : boxAround.right; } else { // (Adjust for extended bound, if necessary.) if (!ltr && (ch == end || ch == begin)) { ch++; } // To determine which side to associate with, get the box to the // left of the character and compare it's vertical position to the // coordinates sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ? "after" : "before"; // Now get accurate coordinates for this place, in order to get a // base X position var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure); baseX = coords.left; outside = y < coords.top || y >= coords.bottom; } ch = skipExtendingChars(lineObj.text, ch, 1); return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX) } function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) { // Bidi parts are sorted left-to-right, and in a non-line-wrapping // situation, we can take this ordering to correspond to the visual // ordering. This finds the first part whose end is after the given // coordinates. var index = findFirst(function (i) { var part = order[i], ltr = part.level != 1; return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true) }, 0, order.length - 1); var part = order[index]; // If this isn't the first part, the part's start is also after // the coordinates, and the coordinates aren't on the same line as // that start, move one part back. if (index > 0) { var ltr = part.level != 1; var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure); if (boxIsAfter(start, x, y, true) && start.top > y) { part = order[index - 1]; } } return part } function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { // In a wrapped line, rtl text on wrapping boundaries can do things // that don't correspond to the ordering in our `order` array at // all, so a binary search doesn't work, and we want to return a // part that only spans one line so that the binary search in // coordsCharInner is safe. As such, we first find the extent of the // wrapped line, and then do a flat search in which we discard any // spans that aren't on the line. var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); var begin = ref.begin; var end = ref.end; if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } var part = null, closestDist = null; for (var i = 0; i < order.length; i++) { var p = order[i]; if (p.from >= end || p.to <= begin) { continue } var ltr = p.level != 1; var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; // Weigh against spans ending before this, so that they are only // picked if nothing ends after var dist = endX < x ? x - endX + 1e9 : endX - x; if (!part || closestDist > dist) { part = p; closestDist = dist; } } if (!part) { part = order[order.length - 1]; } // Clip the part to the wrapped line. if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } return part } var measureText; // Compute the default text height. function textHeight(display) { if (display.cachedTextHeight != null) { return display.cachedTextHeight } if (measureText == null) { measureText = elt("pre"); // Measure a bunch of lines, for browsers that compute // fractional heights. for (var i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")); measureText.appendChild(elt("br")); } measureText.appendChild(document.createTextNode("x")); } removeChildrenAndAdd(display.measure, measureText); var height = measureText.offsetHeight / 50; if (height > 3) { display.cachedTextHeight = height; } removeChildren(display.measure); return height || 1 } // Compute the default character width. function charWidth(display) { if (display.cachedCharWidth != null) { return display.cachedCharWidth } var anchor = elt("span", "xxxxxxxxxx"); var pre = elt("pre", [anchor]); removeChildrenAndAdd(display.measure, pre); var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; if (width > 2) { display.cachedCharWidth = width; } return width || 10 } // Do a bulk-read of the DOM positions and sizes needed to draw the // view, so that we don't interleave reading and writing to the DOM. function getDimensions(cm) { var d = cm.display, left = {}, width = {}; var gutterLeft = d.gutters.clientLeft; for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; width[cm.options.gutters[i]] = n.clientWidth; } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth} } // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, // but using getBoundingClientRect to get a sub-pixel-accurate // result. function compensateForHScroll(display) { return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left } // Returns a function that estimates the height of a line, to use as // first approximation until the line becomes visible (and is thus // properly measurable). function estimateHeight(cm) { var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); return function (line) { if (lineIsHidden(cm.doc, line)) { return 0 } var widgetsHeight = 0; if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } } } if (wrapping) { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } else { return widgetsHeight + th } } } function estimateLineHeights(cm) { var doc = cm.doc, est = estimateHeight(cm); doc.iter(function (line) { var estHeight = est(line); if (estHeight != line.height) { updateLineHeight(line, estHeight); } }); } // Given a mouse event, find the corresponding position. If liberal // is false, it checks whether a gutter or scrollbar was clicked, // and returns null if it was. forRect is used by rectangular // selections, and tries to estimate a character position even for // coordinates beyond the right of the text. function posFromMouse(cm, e, liberal, forRect) { var display = cm.display; if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } var x, y, space = display.lineSpace.getBoundingClientRect(); // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e) { return null } var coords = coordsChar(cm, x, y), line; if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); } return coords } // Find the view element corresponding to a given line. Return null // when the line isn't visible. function findViewIndex(cm, n) { if (n >= cm.display.viewTo) { return null } n -= cm.display.viewFrom; if (n < 0) { return null } var view = cm.display.view; for (var i = 0; i < view.length; i++) { n -= view[i].size; if (n < 0) { return i } } } function updateSelection(cm) { cm.display.input.showSelection(cm.display.input.prepareSelection()); } function prepareSelection(cm, primary) { if ( primary === void 0 ) primary = true; var doc = cm.doc, result = {}; var curFragment = result.cursors = document.createDocumentFragment(); var selFragment = result.selection = document.createDocumentFragment(); for (var i = 0; i < doc.sel.ranges.length; i++) { if (!primary && i == doc.sel.primIndex) { continue } var range$$1 = doc.sel.ranges[i]; if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } var collapsed = range$$1.empty(); if (collapsed || cm.options.showCursorWhenSelecting) { drawSelectionCursor(cm, range$$1.head, curFragment); } if (!collapsed) { drawSelectionRange(cm, range$$1, selFragment); } } return result } // Draws a cursor for the given range function drawSelectionCursor(cm, head, output) { var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); cursor.style.left = pos.left + "px"; cursor.style.top = pos.top + "px"; cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; if (pos.other) { // Secondary cursor, shown when on a 'jump' in bi-directional text var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); otherCursor.style.display = ""; otherCursor.style.left = pos.other.left + "px"; otherCursor.style.top = pos.other.top + "px"; otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; } } function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } // Draws the given range as a highlighted selection function drawSelectionRange(cm, range$$1, output) { var display = cm.display, doc = cm.doc; var fragment = document.createDocumentFragment(); var padding = paddingH(cm.display), leftSide = padding.left; var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; var docLTR = doc.direction == "ltr"; function add(left, top, width, bottom) { if (top < 0) { top = 0; } top = Math.round(top); bottom = Math.round(bottom); 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"))); } function drawForLine(line, fromArg, toArg) { var lineObj = getLine(doc, line); var lineLen = lineObj.text.length; var start, end; function coords(ch, bias) { return charCoords(cm, Pos(line, ch), "div", lineObj, bias) } function wrapX(pos, dir, side) { var extent = wrappedLineExtentChar(cm, lineObj, null, pos); var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); return coords(ch, prop)[prop] } var order = getOrder(lineObj, doc.direction); iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { var ltr = dir == "ltr"; var fromPos = coords(from, ltr ? "left" : "right"); var toPos = coords(to - 1, ltr ? "right" : "left"); var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; var first = i == 0, last = !order || i == order.length - 1; if (toPos.top - fromPos.top <= 3) { // Single line var openLeft = (docLTR ? openStart : openEnd) && first; var openRight = (docLTR ? openEnd : openStart) && last; var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; add(left, fromPos.top, right - left, fromPos.bottom); } else { // Multiple lines var topLeft, topRight, botLeft, botRight; if (ltr) { topLeft = docLTR && openStart && first ? leftSide : fromPos.left; topRight = docLTR ? rightSide : wrapX(from, dir, "before"); botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); botRight = docLTR && openEnd && last ? rightSide : toPos.right; } else { topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); topRight = !docLTR && openStart && first ? rightSide : fromPos.right; botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); } add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); } if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } if (cmpCoords(toPos, start) < 0) { start = toPos; } if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } if (cmpCoords(toPos, end) < 0) { end = toPos; } }); return {start: start, end: end} } var sFrom = range$$1.from(), sTo = range$$1.to(); if (sFrom.line == sTo.line) { drawForLine(sFrom.line, sFrom.ch, sTo.ch); } else { var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); var singleVLine = visualLine(fromLine) == visualLine(toLine); var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); } } if (leftEnd.bottom < rightStart.top) { add(leftSide, leftEnd.bottom, null, rightStart.top); } } output.appendChild(fragment); } // Cursor-blinking function restartBlink(cm) { if (!cm.state.focused) { return } var display = cm.display; clearInterval(display.blinker); var on = true; display.cursorDiv.style.visibility = ""; if (cm.options.cursorBlinkRate > 0) { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, cm.options.cursorBlinkRate); } else if (cm.options.cursorBlinkRate < 0) { display.cursorDiv.style.visibility = "hidden"; } } function ensureFocus(cm) { if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } } function delayBlurEvent(cm) { cm.state.delayingBlurEvent = true; setTimeout(function () { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; onBlur(cm); } }, 100); } function onFocus(cm, e) { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } if (cm.options.readOnly == "nocursor") { return } if (!cm.state.focused) { signal(cm, "focus", cm, e); cm.state.focused = true; addClass(cm.display.wrapper, "CodeMirror-focused"); // This test prevents this from firing when a context // menu is closed (since the input reset would kill the // select-all detection hack) if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { cm.display.input.reset(); if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 } cm.display.input.receivedFocus(); } restartBlink(cm); } function onBlur(cm, e) { if (cm.state.delayingBlurEvent) { return } if (cm.state.focused) { signal(cm, "blur", cm, e); cm.state.focused = false; rmClass(cm.display.wrapper, "CodeMirror-focused"); } clearInterval(cm.display.blinker); setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); } // Read the actual heights of the rendered lines, and update their // stored heights to match. function updateHeightsInViewport(cm) { var display = cm.display; var prevBottom = display.lineDiv.offsetTop; for (var i = 0; i < display.view.length; i++) { var cur = display.view[i], wrapping = cm.options.lineWrapping; var height = (void 0), width = 0; if (cur.hidden) { continue } if (ie && ie_version < 8) { var bot = cur.node.offsetTop + cur.node.offsetHeight; height = bot - prevBottom; prevBottom = bot; } else { var box = cur.node.getBoundingClientRect(); height = box.bottom - box.top; // Check that lines don't extend past the right of the current // editor width if (!wrapping && cur.text.firstChild) { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } } var diff = cur.line.height - height; if (height < 2) { height = textHeight(display); } if (diff > .005 || diff < -.005) { updateLineHeight(cur.line, height); updateWidgetHeight(cur.line); if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) { updateWidgetHeight(cur.rest[j]); } } } if (width > cm.display.sizerWidth) { var chWidth = Math.ceil(width / charWidth(cm.display)); if (chWidth > cm.display.maxLineLength) { cm.display.maxLineLength = chWidth; cm.display.maxLine = cur.line; cm.display.maxLineChanged = true; } } } } // Read and store the height of line widgets associated with the // given line. function updateWidgetHeight(line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { var w = line.widgets[i], parent = w.node.parentNode; if (parent) { w.height = parent.offsetHeight; } } } } // Compute the lines that are visible in a given viewport (defaults // the the current scroll position). viewport may contain top, // height, and ensure (see op.scrollToPos) properties. function visibleLines(display, doc, viewport) { var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; top = Math.floor(top - paddingTop(display)); var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); // Ensure is a {from: {line, ch}, to: {line, ch}} object, and // forces those lines into the viewport (if possible). if (viewport && viewport.ensure) { var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; if (ensureFrom < from) { from = ensureFrom; to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); } else if (Math.min(ensureTo, doc.lastLine()) >= to) { from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); to = ensureTo; } } return {from: from, to: Math.max(to, from + 1)} } // Re-align line numbers and gutter marks to compensate for // horizontal scrolling. function alignHorizontally(cm) { var display = cm.display, view = display.view; if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; var gutterW = display.gutters.offsetWidth, left = comp + "px"; for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { if (cm.options.fixedGutter) { if (view[i].gutter) { view[i].gutter.style.left = left; } if (view[i].gutterBackground) { view[i].gutterBackground.style.left = left; } } var align = view[i].alignable; if (align) { for (var j = 0; j < align.length; j++) { align[j].style.left = left; } } } } if (cm.options.fixedGutter) { display.gutters.style.left = (comp + gutterW) + "px"; } } // Used to ensure that the line number gutter is still the right // size for the current document size. Returns true when an update // is needed. function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) { return false } var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; if (last.length != display.lineNumChars) { var test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")); var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; display.lineGutter.style.width = ""; display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; display.lineNumWidth = display.lineNumInnerWidth + padding; display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; display.lineGutter.style.width = display.lineNumWidth + "px"; updateGutterSpace(cm); return true } return false } // SCROLLING THINGS INTO VIEW // If an editor sits on the top or bottom of the window, partially // scrolled out of view, this ensures that the cursor is visible. function maybeScrollWindow(cm, rect) { if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; if (rect.top + box.top < 0) { doScroll = true; } else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } if (doScroll != null && !phantom) { 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;")); cm.display.lineSpace.appendChild(scrollNode); scrollNode.scrollIntoView(doScroll); cm.display.lineSpace.removeChild(scrollNode); } } // Scroll a given position into view (immediately), verifying that // it actually became visible (as line heights are accurately // measured, the position of something may 'drift' during drawing). function scrollPosIntoView(cm, pos, end, margin) { if (margin == null) { margin = 0; } var rect; if (!cm.options.lineWrapping && pos == end) { // Set pos and end to the cursor positions around the character pos sticks to // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch // If pos == Pos(_, 0, "before"), pos and end are unchanged pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; } for (var limit = 0; limit < 5; limit++) { var changed = false; var coords = cursorCoords(cm, pos); var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); rect = {left: Math.min(coords.left, endCoords.left), top: Math.min(coords.top, endCoords.top) - margin, right: Math.max(coords.left, endCoords.left), bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; var scrollPos = calculateScrollPos(cm, rect); var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } } if (!changed) { break } } return rect } // Scroll a given set of coordinates into view (immediately). function scrollIntoView(cm, rect) { var scrollPos = calculateScrollPos(cm, rect); if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } } // Calculate a new scroll position needed to scroll the given // rectangle into view. Returns an object with scrollTop and // scrollLeft properties. When these are undefined, the // vertical/horizontal position does not need to be adjusted. function calculateScrollPos(cm, rect) { var display = cm.display, snapMargin = textHeight(cm.display); if (rect.top < 0) { rect.top = 0; } var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; var screen = displayHeight(cm), result = {}; if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } var docBottom = cm.doc.height + paddingVert(display); var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; if (rect.top < screentop) { result.scrollTop = atTop ? 0 : rect.top; } else if (rect.bottom > screentop + screen) { var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); if (newTop != screentop) { result.scrollTop = newTop; } } var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); var tooWide = rect.right - rect.left > screenw; if (tooWide) { rect.right = rect.left + screenw; } if (rect.left < 10) { result.scrollLeft = 0; } else if (rect.left < screenleft) { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } else if (rect.right > screenw + screenleft - 3) { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } return result } // Store a relative adjustment to the scroll position in the current // operation (to be applied when the operation finishes). function addToScrollTop(cm, top) { if (top == null) { return } resolveScrollToPos(cm); cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; } // Make sure that at the end of the operation the current cursor is // shown. function ensureCursorVisible(cm) { resolveScrollToPos(cm); var cur = cm.getCursor(); cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; } function scrollToCoords(cm, x, y) { if (x != null || y != null) { resolveScrollToPos(cm); } if (x != null) { cm.curOp.scrollLeft = x; } if (y != null) { cm.curOp.scrollTop = y; } } function scrollToRange(cm, range$$1) { resolveScrollToPos(cm); cm.curOp.scrollToPos = range$$1; } // When an operation has its scrollToPos property set, and another // scroll action is applied before the end of the operation, this // 'simulates' scrolling that position into view in a cheap way, so // that the effect of intermediate scroll commands is not ignored. function resolveScrollToPos(cm) { var range$$1 = cm.curOp.scrollToPos; if (range$$1) { cm.curOp.scrollToPos = null; var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); scrollToCoordsRange(cm, from, to, range$$1.margin); } } function scrollToCoordsRange(cm, from, to, margin) { var sPos = calculateScrollPos(cm, { left: Math.min(from.left, to.left), top: Math.min(from.top, to.top) - margin, right: Math.max(from.right, to.right), bottom: Math.max(from.bottom, to.bottom) + margin }); scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); } // Sync the scrollable area and scrollbars, ensure the viewport // covers the visible area. function updateScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) { return } if (!gecko) { updateDisplaySimple(cm, {top: val}); } setScrollTop(cm, val, true); if (gecko) { updateDisplaySimple(cm); } startWorker(cm, 100); } function setScrollTop(cm, val, forceScroll) { val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val); if (cm.display.scroller.scrollTop == val && !forceScroll) { return } cm.doc.scrollTop = val; cm.display.scrollbars.setScrollTop(val); if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } } // Sync scroller and scrollbar, ensure the gutter elements are // aligned. function setScrollLeft(cm, val, isScroller, forceScroll) { val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } cm.doc.scrollLeft = val; alignHorizontally(cm); if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } cm.display.scrollbars.setScrollLeft(val); } // SCROLLBARS // Prepare DOM reads needed to update the scrollbars. Done in one // shot to minimize update/measure roundtrips. function measureForScrollbars(cm) { var d = cm.display, gutterW = d.gutters.offsetWidth; var docH = Math.round(cm.doc.height + paddingVert(cm.display)); return { clientHeight: d.scroller.clientHeight, viewHeight: d.wrapper.clientHeight, scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, viewWidth: d.wrapper.clientWidth, barLeft: cm.options.fixedGutter ? gutterW : 0, docHeight: docH, scrollHeight: docH + scrollGap(cm) + d.barHeight, nativeBarWidth: d.nativeBarWidth, gutterWidth: gutterW } } var NativeScrollbars = function(place, scroll, cm) { this.cm = cm; var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); vert.tabIndex = horiz.tabIndex = -1; place(vert); place(horiz); on(vert, "scroll", function () { if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } }); on(horiz, "scroll", function () { if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } }); this.checkedZeroWidth = false; // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } }; NativeScrollbars.prototype.update = function (measure) { var needsH = measure.scrollWidth > measure.clientWidth + 1; var needsV = measure.scrollHeight > measure.clientHeight + 1; var sWidth = measure.nativeBarWidth; if (needsV) { this.vert.style.display = "block"; this.vert.style.bottom = needsH ? sWidth + "px" : "0"; var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); // A bug in IE8 can cause this value to be negative, so guard it. this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; } else { this.vert.style.display = ""; this.vert.firstChild.style.height = "0"; } if (needsH) { this.horiz.style.display = "block"; this.horiz.style.right = needsV ? sWidth + "px" : "0"; this.horiz.style.left = measure.barLeft + "px"; var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; } else { this.horiz.style.display = ""; this.horiz.firstChild.style.width = "0"; } if (!this.checkedZeroWidth && measure.clientHeight > 0) { if (sWidth == 0) { this.zeroWidthHack(); } this.checkedZeroWidth = true; } return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} }; NativeScrollbars.prototype.setScrollLeft = function (pos) { if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } }; NativeScrollbars.prototype.setScrollTop = function (pos) { if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } }; NativeScrollbars.prototype.zeroWidthHack = function () { var w = mac && !mac_geMountainLion ? "12px" : "18px"; this.horiz.style.height = this.vert.style.width = w; this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; this.disableHoriz = new Delayed; this.disableVert = new Delayed; }; NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { bar.style.pointerEvents = "auto"; function maybeDisable() { // To find out whether the scrollbar is still visible, we // check whether the element under the pixel in the bottom // right corner of the scrollbar box is the scrollbar box // itself (when the bar is still visible) or its filler child // (when the bar is hidden). If it is still visible, we keep // it enabled, if it's hidden, we disable pointer events. var box = bar.getBoundingClientRect(); var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } else { delay.set(1000, maybeDisable); } } delay.set(1000, maybeDisable); }; NativeScrollbars.prototype.clear = function () { var parent = this.horiz.parentNode; parent.removeChild(this.horiz); parent.removeChild(this.vert); }; var NullScrollbars = function () {}; NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; NullScrollbars.prototype.setScrollLeft = function () {}; NullScrollbars.prototype.setScrollTop = function () {}; NullScrollbars.prototype.clear = function () {}; function updateScrollbars(cm, measure) { if (!measure) { measure = measureForScrollbars(cm); } var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; updateScrollbarsInner(cm, measure); for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { if (startWidth != cm.display.barWidth && cm.options.lineWrapping) { updateHeightsInViewport(cm); } updateScrollbarsInner(cm, measureForScrollbars(cm)); startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; } } // Re-synchronize the fake scrollbars with the actual size of the // content. function updateScrollbarsInner(cm, measure) { var d = cm.display; var sizes = d.scrollbars.update(measure); d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; if (sizes.right && sizes.bottom) { d.scrollbarFiller.style.display = "block"; d.scrollbarFiller.style.height = sizes.bottom + "px"; d.scrollbarFiller.style.width = sizes.right + "px"; } else { d.scrollbarFiller.style.display = ""; } if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block"; d.gutterFiller.style.height = sizes.bottom + "px"; d.gutterFiller.style.width = measure.gutterWidth + "px"; } else { d.gutterFiller.style.display = ""; } } var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; function initScrollbars(cm) { if (cm.display.scrollbars) { cm.display.scrollbars.clear(); if (cm.display.scrollbars.addClass) { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); // Prevent clicks in the scrollbars from killing focus on(node, "mousedown", function () { if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } }); node.setAttribute("cm-not-content", "true"); }, function (pos, axis) { if (axis == "horizontal") { setScrollLeft(cm, pos); } else { updateScrollTop(cm, pos); } }, cm); if (cm.display.scrollbars.addClass) { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } } // Operations are used to wrap a series of changes to the editor // state in such a way that each change won't have to update the // cursor and display (which would be awkward, slow, and // error-prone). Instead, display updates are batched and then all // combined and executed at once. var nextOpId = 0; // Start a new operation. function startOperation(cm) { cm.curOp = { cm: cm, viewChanged: false, // Flag that indicates that lines might need to be redrawn startHeight: cm.doc.height, // Used to detect need to update scrollbar forceUpdate: false, // Used to force a redraw updateInput: 0, // Whether to reset the input textarea typing: false, // Whether this reset should be careful to leave existing text (for compositing) changeObjs: null, // Accumulated changes, for firing change events cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already selectionChanged: false, // Whether the selection needs to be redrawn updateMaxLine: false, // Set when the widest line needs to be determined anew scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet scrollToPos: null, // Used to scroll to a specific position focus: false, id: ++nextOpId // Unique ID }; pushOperation(cm.curOp); } // Finish an operation, updating the display and signalling delayed events function endOperation(cm) { var op = cm.curOp; if (op) { finishOperation(op, function (group) { for (var i = 0; i < group.ops.length; i++) { group.ops[i].cm.curOp = null; } endOperations(group); }); } } // The DOM updates done when an operation finishes are batched so // that the minimum number of relayouts are required. function endOperations(group) { var ops = group.ops; for (var i = 0; i < ops.length; i++) // Read DOM { endOperation_R1(ops[i]); } for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) { endOperation_W1(ops[i$1]); } for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM { endOperation_R2(ops[i$2]); } for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) { endOperation_W2(ops[i$3]); } for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM { endOperation_finish(ops[i$4]); } } function endOperation_R1(op) { var cm = op.cm, display = cm.display; maybeClipScrollbars(cm); if (op.updateMaxLine) { findMaxLine(cm); } op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping; op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); } function endOperation_W1(op) { op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); } function endOperation_R2(op) { var cm = op.cm, display = cm.display; if (op.updatedDisplay) { updateHeightsInViewport(cm); } op.barMeasure = measureForScrollbars(cm); // If the max line changed since it was last measured, measure it, // and ensure the document's width matches it. // updateDisplay_W2 will use these properties to do the actual resizing if (display.maxLineChanged && !cm.options.lineWrapping) { op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; cm.display.sizerWidth = op.adjustWidthTo; op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); } if (op.updatedDisplay || op.selectionChanged) { op.preparedSelection = display.input.prepareSelection(); } } function endOperation_W2(op) { var cm = op.cm; if (op.adjustWidthTo != null) { cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; if (op.maxScrollLeft < cm.doc.scrollLeft) { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } cm.display.maxLineChanged = false; } var takeFocus = op.focus && op.focus == activeElt(); if (op.preparedSelection) { cm.display.input.showSelection(op.preparedSelection, takeFocus); } if (op.updatedDisplay || op.startHeight != cm.doc.height) { updateScrollbars(cm, op.barMeasure); } if (op.updatedDisplay) { setDocumentHeight(cm, op.barMeasure); } if (op.selectionChanged) { restartBlink(cm); } if (cm.state.focused && op.updateInput) { cm.display.input.reset(op.typing); } if (takeFocus) { ensureFocus(op.cm); } } function endOperation_finish(op) { var cm = op.cm, display = cm.display, doc = cm.doc; if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } // Abort mouse wheel delta measurement, when scrolling explicitly if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) { display.wheelStartX = display.wheelStartY = null; } // Propagate the scroll position to the actual DOM scroller if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } // If we need to scroll a specific position into view, do so. if (op.scrollToPos) { var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); maybeScrollWindow(cm, rect); } // Fire events for markers that are hidden/unidden by editing or // undoing var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; if (hidden) { for (var i = 0; i < hidden.length; ++i) { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } if (display.wrapper.offsetHeight) { doc.scrollTop = cm.display.scroller.scrollTop; } // Fire change events, and delayed event handlers if (op.changeObjs) { signal(cm, "changes", cm, op.changeObjs); } if (op.update) { op.update.finish(); } } // Run the given function in an operation function runInOp(cm, f) { if (cm.curOp) { return f() } startOperation(cm); try { return f() } finally { endOperation(cm); } } // Wraps a function in an operation. Returns the wrapped function. function operation(cm, f) { return function() { if (cm.curOp) { return f.apply(cm, arguments) } startOperation(cm); try { return f.apply(cm, arguments) } finally { endOperation(cm); } } } // Used to add methods to editor and doc instances, wrapping them in // operations. function methodOp(f) { return function() { if (this.curOp) { return f.apply(this, arguments) } startOperation(this); try { return f.apply(this, arguments) } finally { endOperation(this); } } } function docMethodOp(f) { return function() { var cm = this.cm; if (!cm || cm.curOp) { return f.apply(this, arguments) } startOperation(cm); try { return f.apply(this, arguments) } finally { endOperation(cm); } } } // Updates the display.view data structure for a given change to the // document. From and to are in pre-change coordinates. Lendiff is // the amount of lines added or subtracted by the change. This is // used for changes that span multiple lines, or change the way // lines are divided into visual lines. regLineChange (below) // registers single-line changes. function regChange(cm, from, to, lendiff) { if (from == null) { from = cm.doc.first; } if (to == null) { to = cm.doc.first + cm.doc.size; } if (!lendiff) { lendiff = 0; } var display = cm.display; if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) { display.updateLineNumbers = from; } cm.curOp.viewChanged = true; if (from >= display.viewTo) { // Change after if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) { resetView(cm); } } else if (to <= display.viewFrom) { // Change before if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { resetView(cm); } else { display.viewFrom += lendiff; display.viewTo += lendiff; } } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap resetView(cm); } else if (from <= display.viewFrom) { // Top overlap var cut = viewCuttingPoint(cm, to, to + lendiff, 1); if (cut) { display.view = display.view.slice(cut.index); display.viewFrom = cut.lineN; display.viewTo += lendiff; } else { resetView(cm); } } else if (to >= display.viewTo) { // Bottom overlap var cut$1 = viewCuttingPoint(cm, from, from, -1); if (cut$1) { display.view = display.view.slice(0, cut$1.index); display.viewTo = cut$1.lineN; } else { resetView(cm); } } else { // Gap in the middle var cutTop = viewCuttingPoint(cm, from, from, -1); var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); if (cutTop && cutBot) { display.view = display.view.slice(0, cutTop.index) .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) .concat(display.view.slice(cutBot.index)); display.viewTo += lendiff; } else { resetView(cm); } } var ext = display.externalMeasured; if (ext) { if (to < ext.lineN) { ext.lineN += lendiff; } else if (from < ext.lineN + ext.size) { display.externalMeasured = null; } } } // Register a change to a single line. Type must be one of "text", // "gutter", "class", "widget" function regLineChange(cm, line, type) { cm.curOp.viewChanged = true; var display = cm.display, ext = cm.display.externalMeasured; if (ext && line >= ext.lineN && line < ext.lineN + ext.size) { display.externalMeasured = null; } if (line < display.viewFrom || line >= display.viewTo) { return } var lineView = display.view[findViewIndex(cm, line)]; if (lineView.node == null) { return } var arr = lineView.changes || (lineView.changes = []); if (indexOf(arr, type) == -1) { arr.push(type); } } // Clear the view. function resetView(cm) { cm.display.viewFrom = cm.display.viewTo = cm.doc.first; cm.display.view = []; cm.display.viewOffset = 0; } function viewCuttingPoint(cm, oldN, newN, dir) { var index = findViewIndex(cm, oldN), diff, view = cm.display.view; if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) { return {index: index, lineN: newN} } var n = cm.display.viewFrom; for (var i = 0; i < index; i++) { n += view[i].size; } if (n != oldN) { if (dir > 0) { if (index == view.length - 1) { return null } diff = (n + view[index].size) - oldN; index++; } else { diff = n - oldN; } oldN += diff; newN += diff; } while (visualLineNo(cm.doc, newN) != newN) { if (index == (dir < 0 ? 0 : view.length - 1)) { return null } newN += dir * view[index - (dir < 0 ? 1 : 0)].size; index += dir; } return {index: index, lineN: newN} } // Force the view to cover a given range, adding empty view element // or clipping off existing ones as needed. function adjustView(cm, from, to) { var display = cm.display, view = display.view; if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { display.view = buildViewArray(cm, from, to); display.viewFrom = from; } else { if (display.viewFrom > from) { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } else if (display.viewFrom < from) { display.view = display.view.slice(findViewIndex(cm, from)); } display.viewFrom = from; if (display.viewTo < to) { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } else if (display.viewTo > to) { display.view = display.view.slice(0, findViewIndex(cm, to)); } } display.viewTo = to; } // Count the number of lines in the view whose DOM representation is // out of date (or nonexistent). function countDirtyView(cm) { var view = cm.display.view, dirty = 0; for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } } return dirty } // HIGHLIGHT WORKER function startWorker(cm, time) { if (cm.doc.highlightFrontier < cm.display.viewTo) { cm.state.highlight.set(time, bind(highlightWorker, cm)); } } function highlightWorker(cm) { var doc = cm.doc; if (doc.highlightFrontier >= cm.display.viewTo) { return } var end = +new Date + cm.options.workTime; var context = getContextBefore(cm, doc.highlightFrontier); var changedLines = []; doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { if (context.line >= cm.display.viewFrom) { // Visible var oldStyles = line.styles; var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; var highlighted = highlightLine(cm, line, context, true); if (resetState) { context.state = resetState; } line.styles = highlighted.styles; var oldCls = line.styleClasses, newCls = highlighted.classes; if (newCls) { line.styleClasses = newCls; } else if (oldCls) { line.styleClasses = null; } var ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } if (ischange) { changedLines.push(context.line); } line.stateAfter = context.save(); context.nextLine(); } else { if (line.text.length <= cm.options.maxHighlightLength) { processLine(cm, line.text, context); } line.stateAfter = context.line % 5 == 0 ? context.save() : null; context.nextLine(); } if (+new Date > end) { startWorker(cm, cm.options.workDelay); return true } }); doc.highlightFrontier = context.line; doc.modeFrontier = Math.max(doc.modeFrontier, context.line); if (changedLines.length) { runInOp(cm, function () { for (var i = 0; i < changedLines.length; i++) { regLineChange(cm, changedLines[i], "text"); } }); } } // DISPLAY DRAWING var DisplayUpdate = function(cm, viewport, force) { var display = cm.display; this.viewport = viewport; // Store some values that we'll need later (but don't want to force a relayout for) this.visible = visibleLines(display, cm.doc, viewport); this.editorIsHidden = !display.wrapper.offsetWidth; this.wrapperHeight = display.wrapper.clientHeight; this.wrapperWidth = display.wrapper.clientWidth; this.oldDisplayWidth = displayWidth(cm); this.force = force; this.dims = getDimensions(cm); this.events = []; }; DisplayUpdate.prototype.signal = function (emitter, type) { if (hasHandler(emitter, type)) { this.events.push(arguments); } }; DisplayUpdate.prototype.finish = function () { var this$1 = this; for (var i = 0; i < this.events.length; i++) { signal.apply(null, this$1.events[i]); } }; function maybeClipScrollbars(cm) { var display = cm.display; if (!display.scrollbarsClipped && display.scroller.offsetWidth) { display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; display.heightForcer.style.height = scrollGap(cm) + "px"; display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; display.scrollbarsClipped = true; } } function selectionSnapshot(cm) { if (cm.hasFocus()) { return null } var active = activeElt(); if (!active || !contains(cm.display.lineDiv, active)) { return null } var result = {activeElt: active}; if (window.getSelection) { var sel = window.getSelection(); if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { result.anchorNode = sel.anchorNode; result.anchorOffset = sel.anchorOffset; result.focusNode = sel.focusNode; result.focusOffset = sel.focusOffset; } } return result } function restoreSelection(snapshot) { if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } snapshot.activeElt.focus(); if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { var sel = window.getSelection(), range$$1 = document.createRange(); range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); range$$1.collapse(false); sel.removeAllRanges(); sel.addRange(range$$1); sel.extend(snapshot.focusNode, snapshot.focusOffset); } } // Does the actual updating of the line display. Bails out // (returning false) when there is nothing to be done and forced is // false. function updateDisplayIfNeeded(cm, update) { var display = cm.display, doc = cm.doc; if (update.editorIsHidden) { resetView(cm); return false } // Bail out if the visible area is already rendered and nothing changed. if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) { return false } if (maybeUpdateLineNumberWidth(cm)) { resetView(cm); update.dims = getDimensions(cm); } // Compute a suitable new viewport (from & to) var end = doc.first + doc.size; var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); var to = Math.min(end, update.visible.to + cm.options.viewportMargin); if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } if (sawCollapsedSpans) { from = visualLineNo(cm.doc, from); to = visualLineEndNo(cm.doc, to); } var different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; adjustView(cm, from, to); display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); // Position the mover div to align with the current scroll position cm.display.mover.style.top = display.viewOffset + "px"; var toUpdate = countDirtyView(cm); if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) { return false } // For big changes, we hide the enclosing element during the // update, since that speeds up the operations on most browsers. var selSnapshot = selectionSnapshot(cm); if (toUpdate > 4) { display.lineDiv.style.display = "none"; } patchDisplay(cm, display.updateLineNumbers, update.dims); if (toUpdate > 4) { display.lineDiv.style.display = ""; } display.renderedView = display.view; // There might have been a widget with a focused element that got // hidden or updated, if so re-focus it. restoreSelection(selSnapshot); // Prevent selection and cursors from interfering with the scroll // width and height. removeChildren(display.cursorDiv); removeChildren(display.selectionDiv); display.gutters.style.height = display.sizer.style.minHeight = 0; if (different) { display.lastWrapHeight = update.wrapperHeight; display.lastWrapWidth = update.wrapperWidth; startWorker(cm, 400); } display.updateLineNumbers = null; return true } function postUpdateDisplay(cm, update) { var viewport = update.viewport; for (var first = true;; first = false) { if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { // Clip forced viewport to actual scrollable area. if (viewport && viewport.top != null) { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } // Updated line heights might result in the drawn area not // actually covering the viewport. Keep looping until it does. update.visible = visibleLines(cm.display, cm.doc, viewport); if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) { break } } if (!updateDisplayIfNeeded(cm, update)) { break } updateHeightsInViewport(cm); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.force = false; } update.signal(cm, "update", cm); if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; } } function updateDisplaySimple(cm, viewport) { var update = new DisplayUpdate(cm, viewport); if (updateDisplayIfNeeded(cm, update)) { updateHeightsInViewport(cm); postUpdateDisplay(cm, update); var barMeasure = measureForScrollbars(cm); updateSelection(cm); updateScrollbars(cm, barMeasure); setDocumentHeight(cm, barMeasure); update.finish(); } } // Sync the actual display DOM structure with display.view, removing // nodes for lines that are no longer in view, and creating the ones // that are not there yet, and updating the ones that are out of // date. function patchDisplay(cm, updateNumbersFrom, dims) { var display = cm.display, lineNumbers = cm.options.lineNumbers; var container = display.lineDiv, cur = container.firstChild; function rm(node) { var next = node.nextSibling; // Works around a throw-scroll bug in OS X Webkit if (webkit && mac && cm.display.currentWheelTarget == node) { node.style.display = "none"; } else { node.parentNode.removeChild(node); } return next } var view = display.view, lineN = display.viewFrom; // Loop over the elements in the view, syncing cur (the DOM nodes // in display.lineDiv) with the view as we go. for (var i = 0; i < view.length; i++) { var lineView = view[i]; if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet var node = buildLineElement(cm, lineView, lineN, dims); container.insertBefore(node, cur); } else { // Already drawn while (cur != lineView.node) { cur = rm(cur); } var updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber; if (lineView.changes) { if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } updateLineForChanges(cm, lineView, lineN, dims); } if (updateNumber) { removeChildren(lineView.lineNumber); lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); } cur = lineView.node.nextSibling; } lineN += lineView.size; } while (cur) { cur = rm(cur); } } function updateGutterSpace(cm) { var width = cm.display.gutters.offsetWidth; cm.display.sizer.style.marginLeft = width + "px"; } function setDocumentHeight(cm, measure) { cm.display.sizer.style.minHeight = measure.docHeight + "px"; cm.display.heightForcer.style.top = measure.docHeight + "px"; cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; } // Rebuild the gutter elements, ensure the margin to the left of the // code matches their width. function updateGutters(cm) { var gutters = cm.display.gutters, specs = cm.options.gutters; removeChildren(gutters); var i = 0; for (; i < specs.length; ++i) { var gutterClass = specs[i]; var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); if (gutterClass == "CodeMirror-linenumbers") { cm.display.lineGutter = gElt; gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; } } gutters.style.display = i ? "" : "none"; updateGutterSpace(cm); } // Make sure the gutters options contains the element // "CodeMirror-linenumbers" when the lineNumbers option is true. function setGuttersForLineNumbers(options) { var found = indexOf(options.gutters, "CodeMirror-linenumbers"); if (found == -1 && options.lineNumbers) { options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); } else if (found > -1 && !options.lineNumbers) { options.gutters = options.gutters.slice(0); options.gutters.splice(found, 1); } } // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. var wheelSamples = 0, wheelPixelsPerUnit = null; // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) { wheelPixelsPerUnit = -.53; } else if (gecko) { wheelPixelsPerUnit = 15; } else if (chrome) { wheelPixelsPerUnit = -.7; } else if (safari) { wheelPixelsPerUnit = -1/3; } function wheelEventDelta(e) { var dx = e.wheelDeltaX, dy = e.wheelDeltaY; if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } else if (dy == null) { dy = e.wheelDelta; } return {x: dx, y: dy} } function wheelEventPixels(e) { var delta = wheelEventDelta(e); delta.x *= wheelPixelsPerUnit; delta.y *= wheelPixelsPerUnit; return delta } function onScrollWheel(cm, e) { var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; var display = cm.display, scroll = display.scroller; // Quit if there's nothing to scroll here var canScrollX = scroll.scrollWidth > scroll.clientWidth; var canScrollY = scroll.scrollHeight > scroll.clientHeight; if (!(dx && canScrollX || dy && canScrollY)) { return } // Webkit browsers on OS X abort momentum scrolls when the target // of the scroll event is removed from the scrollable element. // This hack (see related code in patchDisplay) makes sure the // element is kept around. if (dy && mac && webkit) { outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { for (var i = 0; i < view.length; i++) { if (view[i].node == cur) { cm.display.currentWheelTarget = cur; break outer } } } } // On some browsers, horizontal scrolling will cause redraws to // happen before the gutter has been realigned, causing it to // wriggle around in a most unseemly way. When we have an // estimated pixels/delta value, we just handle horizontal // scrolling entirely here. It'll be slightly off from native, but // better than glitching out. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { if (dy && canScrollY) { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); // Only prevent default scrolling if vertical scrolling is // actually possible. Otherwise, it causes vertical scroll // jitter on OSX trackpads when deltaX is small and deltaY // is large (issue #3579) if (!dy || (dy && canScrollY)) { e_preventDefault(e); } display.wheelStartX = null; // Abort measurement, if in progress return } // 'Project' the visible viewport to cover the area that is being // scrolled into view (if we know enough to estimate it). if (dy && wheelPixelsPerUnit != null) { var pixels = dy * wheelPixelsPerUnit; var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; if (pixels < 0) { top = Math.max(0, top + pixels - 50); } else { bot = Math.min(cm.doc.height, bot + pixels + 50); } updateDisplaySimple(cm, {top: top, bottom: bot}); } if (wheelSamples < 20) { if (display.wheelStartX == null) { display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; display.wheelDX = dx; display.wheelDY = dy; setTimeout(function () { if (display.wheelStartX == null) { return } var movedX = scroll.scrollLeft - display.wheelStartX; var movedY = scroll.scrollTop - display.wheelStartY; var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX); display.wheelStartX = display.wheelStartY = null; if (!sample) { return } wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); ++wheelSamples; }, 200); } else { display.wheelDX += dx; display.wheelDY += dy; } } } // Selection objects are immutable. A new one is created every time // the selection changes. A selection is one or more non-overlapping // (and non-touching) ranges, sorted, and an integer that indicates // which one is the primary selection (the one that's scrolled into // view, that getCursor returns, etc). var Selection = function(ranges, primIndex) { this.ranges = ranges; this.primIndex = primIndex; }; Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; Selection.prototype.equals = function (other) { var this$1 = this; if (other == this) { return true } if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } for (var i = 0; i < this.ranges.length; i++) { var here = this$1.ranges[i], there = other.ranges[i]; if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } } return true }; Selection.prototype.deepCopy = function () { var this$1 = this; var out = []; for (var i = 0; i < this.ranges.length; i++) { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } return new Selection(out, this.primIndex) }; Selection.prototype.somethingSelected = function () { var this$1 = this; for (var i = 0; i < this.ranges.length; i++) { if (!this$1.ranges[i].empty()) { return true } } return false }; Selection.prototype.contains = function (pos, end) { var this$1 = this; if (!end) { end = pos; } for (var i = 0; i < this.ranges.length; i++) { var range = this$1.ranges[i]; if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) { return i } } return -1 }; var Range = function(anchor, head) { this.anchor = anchor; this.head = head; }; Range.prototype.from = function () { return minPos(this.anchor, this.head) }; Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; // Take an unsorted, potentially overlapping set of ranges, and // build a selection out of it. 'Consumes' ranges array (modifying // it). function normalizeSelection(cm, ranges, primIndex) { var mayTouch = cm && cm.options.selectionsMayTouch; var prim = ranges[primIndex]; ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); primIndex = indexOf(ranges, prim); for (var i = 1; i < ranges.length; i++) { var cur = ranges[i], prev = ranges[i - 1]; var diff = cmp(prev.to(), cur.from()); if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; if (i <= primIndex) { --primIndex; } ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); } } return new Selection(ranges, primIndex) } function simpleSelection(anchor, head) { return new Selection([new Range(anchor, head || anchor)], 0) } // Compute the position of the end of a change (its 'to' property // refers to the pre-change end). function changeEnd(change) { if (!change.text) { return change.to } return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) } // Adjust a position to refer to the post-change position of the // same text, or the end of the change if the change covers it. function adjustForChange(pos, change) { if (cmp(pos, change.from) < 0) { return pos } if (cmp(pos, change.to) <= 0) { return changeEnd(change) } var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } return Pos(line, ch) } function computeSelAfterChange(doc, change) { var out = []; for (var i = 0; i < doc.sel.ranges.length; i++) { var range = doc.sel.ranges[i]; out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change))); } return normalizeSelection(doc.cm, out, doc.sel.primIndex) } function offsetPos(pos, old, nw) { if (pos.line == old.line) { return Pos(nw.line, pos.ch - old.ch + nw.ch) } else { return Pos(nw.line + (pos.line - old.line), pos.ch) } } // Used by replaceSelections to allow moving the selection to the // start or around the replaced test. Hint may be "start" or "around". function computeReplacedSel(doc, changes, hint) { var out = []; var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; for (var i = 0; i < changes.length; i++) { var change = changes[i]; var from = offsetPos(change.from, oldPrev, newPrev); var to = offsetPos(changeEnd(change), oldPrev, newPrev); oldPrev = change.to; newPrev = to; if (hint == "around") { var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; out[i] = new Range(inv ? to : from, inv ? from : to); } else { out[i] = new Range(from, from); } } return new Selection(out, doc.sel.primIndex) } // Used to get the editor into a consistent state again when options change. function loadMode(cm) { cm.doc.mode = getMode(cm.options, cm.doc.modeOption); resetModeState(cm); } function resetModeState(cm) { cm.doc.iter(function (line) { if (line.stateAfter) { line.stateAfter = null; } if (line.styles) { line.styles = null; } }); cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; startWorker(cm, 100); cm.state.modeGen++; if (cm.curOp) { regChange(cm); } } // DOCUMENT DATA STRUCTURE // By default, updates that start and end at the beginning of a line // are treated specially, in order to make the association of line // widgets and marker elements with the text behave more intuitive. function isWholeLineUpdate(doc, change) { return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore) } // Perform a change on the document data structure. function updateDoc(doc, change, markedSpans, estimateHeight$$1) { function spansFor(n) {return markedSpans ? markedSpans[n] : null} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight$$1); signalLater(line, "change", line, change); } function linesFor(start, end) { var result = []; for (var i = start; i < end; ++i) { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } return result } var from = change.from, to = change.to, text = change.text; var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; // Adjust the line structure if (change.full) { doc.insert(0, linesFor(0, text.length)); doc.remove(text.length, doc.size - text.length); } else if (isWholeLineUpdate(doc, change)) { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. var added = linesFor(0, text.length - 1); update(lastLine, lastLine.text, lastSpans); if (nlines) { doc.remove(from.line, nlines); } if (added.length) { doc.insert(from.line, added); } } else if (firstLine == lastLine) { if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); } else { var added$1 = linesFor(1, text.length - 1); added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); doc.insert(from.line + 1, added$1); } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); doc.remove(from.line + 1, nlines); } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); var added$2 = linesFor(1, text.length - 1); if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } doc.insert(from.line + 1, added$2); } signalLater(doc, "change", doc, change); } // Call f for all linked documents. function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { var rel = doc.linked[i]; if (rel.doc == skip) { continue } var shared = sharedHist && rel.sharedHist; if (sharedHistOnly && !shared) { continue } f(rel.doc, shared); propagate(rel.doc, doc, shared); } } } propagate(doc, null, true); } // Attach a document to an editor. function attachDoc(cm, doc) { if (doc.cm) { throw new Error("This document is already in use.") } cm.doc = doc; doc.cm = cm; estimateLineHeights(cm); loadMode(cm); setDirectionClass(cm); if (!cm.options.lineWrapping) { findMaxLine(cm); } cm.options.mode = doc.modeOption; regChange(cm); } function setDirectionClass(cm) { (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); } function directionChanged(cm) { runInOp(cm, function () { setDirectionClass(cm); regChange(cm); }); } function History(startGen) { // Arrays of change events and selections. Doing something adds an // event to done and clears undo. Undoing moves events from done // to undone, redoing moves them in the other direction. this.done = []; this.undone = []; this.undoDepth = Infinity; // Used to track when changes can be merged into a single undo // event this.lastModTime = this.lastSelTime = 0; this.lastOp = this.lastSelOp = null; this.lastOrigin = this.lastSelOrigin = null; // Used by the isClean() method this.generation = this.maxGeneration = startGen || 1; } // Create a history change event from an updateDoc-style change // object. function historyChangeFromChange(doc, change) { var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); return histChange } // Pop all selection events off the end of a history array. Stop at // a change event. function clearSelectionEvents(array) { while (array.length) { var last = lst(array); if (last.ranges) { array.pop(); } else { break } } } // Find the top change event in the history. Pop off selection // events that are in the way. function lastChangeEvent(hist, force) { if (force) { clearSelectionEvents(hist.done); return lst(hist.done) } else if (hist.done.length && !lst(hist.done).ranges) { return lst(hist.done) } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { hist.done.pop(); return lst(hist.done) } } // Register a change in the history. Merges changes that are within // a single operation, or are close together with an origin that // allows merging (starting with "+") into a single event. function addChangeToHistory(doc, change, selAfter, opId) { var hist = doc.history; hist.undone.length = 0; var time = +new Date, cur; var last; if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { // Merge this change into the last event last = lst(cur.changes); if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { // Optimized case for simple insertion -- don't want to add // new changesets for every character typed last.to = changeEnd(change); } else { // Add new sub-event cur.changes.push(historyChangeFromChange(doc, change)); } } else { // Can not be merged, start a new event. var before = lst(hist.done); if (!before || !before.ranges) { pushSelectionToHistory(doc.sel, hist.done); } cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation}; hist.done.push(cur); while (hist.done.length > hist.undoDepth) { hist.done.shift(); if (!hist.done[0].ranges) { hist.done.shift(); } } } hist.done.push(selAfter); hist.generation = ++hist.maxGeneration; hist.lastModTime = hist.lastSelTime = time; hist.lastOp = hist.lastSelOp = opId; hist.lastOrigin = hist.lastSelOrigin = change.origin; if (!last) { signal(doc, "historyAdded"); } } function selectionEventCanBeMerged(doc, origin, prev, sel) { var ch = origin.charAt(0); return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) } // Called whenever the selection changes, sets the new selection as // the pending selection in the history, and pushes the old pending // selection into the 'done' array when it was significantly // different (in number of selected ranges, emptiness, or time). function addSelectionToHistory(doc, sel, opId, options) { var hist = doc.history, origin = options && options.origin; // A new event is started when the previous origin does not match // the current, or the origins don't allow matching. Origins // starting with * are always merged, those starting with + are // merged when similar and close together in time. if (opId == hist.lastSelOp || (origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) { hist.done[hist.done.length - 1] = sel; } else { pushSelectionToHistory(sel, hist.done); } hist.lastSelTime = +new Date; hist.lastSelOrigin = origin; hist.lastSelOp = opId; if (options && options.clearRedo !== false) { clearSelectionEvents(hist.undone); } } function pushSelectionToHistory(sel, dest) { var top = lst(dest); if (!(top && top.ranges && top.equals(sel))) { dest.push(sel); } } // Used to store marked span information in the history. function attachLocalSpans(doc, change, from, to) { var existing = change["spans_" + doc.id], n = 0; doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { if (line.markedSpans) { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } ++n; }); } // When un/re-doing restores text containing marked spans, those // that have been explicitly cleared should not be restored. function removeClearedSpans(spans) { if (!spans) { return null } var out; for (var i = 0; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } else if (out) { out.push(spans[i]); } } return !out ? spans : out.length ? out : null } // Retrieve and filter the old marked spans stored in a change event. function getOldSpans(doc, change) { var found = change["spans_" + doc.id]; if (!found) { return null } var nw = []; for (var i = 0; i < change.text.length; ++i) { nw.push(removeClearedSpans(found[i])); } return nw } // Used for un/re-doing changes from the history. Combines the // result of computing the existing spans with the set of spans that // existed in the history (so that deleting around a span and then // undoing brings back the span). function mergeOldSpans(doc, change) { var old = getOldSpans(doc, change); var stretched = stretchSpansOverChange(doc, change); if (!old) { return stretched } if (!stretched) { return old } for (var i = 0; i < old.length; ++i) { var oldCur = old[i], stretchCur = stretched[i]; if (oldCur && stretchCur) { spans: for (var j = 0; j < stretchCur.length; ++j) { var span = stretchCur[j]; for (var k = 0; k < oldCur.length; ++k) { if (oldCur[k].marker == span.marker) { continue spans } } oldCur.push(span); } } else if (stretchCur) { old[i] = stretchCur; } } return old } // Used both to provide a JSON-safe object in .getHistory, and, when // detaching a document, to split the history in two function copyHistoryArray(events, newGroup, instantiateSel) { var copy = []; for (var i = 0; i < events.length; ++i) { var event = events[i]; if (event.ranges) { copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); continue } var changes = event.changes, newChanges = []; copy.push({changes: newChanges}); for (var j = 0; j < changes.length; ++j) { var change = changes[j], m = (void 0); newChanges.push({from: change.from, to: change.to, text: change.text}); if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop]; delete change[prop]; } } } } } } return copy } // The 'scroll' parameter given to many of these indicated whether // the new cursor position should be scrolled into view after // modifying the selection. // If shift is held or the extend flag is set, extends a range to // include a given position (and optionally a second position). // Otherwise, simply returns the range between the given positions. // Used for cursor motion and such. function extendRange(range, head, other, extend) { if (extend) { var anchor = range.anchor; if (other) { var posBefore = cmp(head, anchor) < 0; if (posBefore != (cmp(other, anchor) < 0)) { anchor = head; head = other; } else if (posBefore != (cmp(head, other) < 0)) { head = other; } } return new Range(anchor, head) } else { return new Range(other || head, head) } } // Extend the primary selection range, discard the rest. function extendSelection(doc, head, other, options, extend) { if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); } // Extend all selections (pos is an array of selections with length // equal the number of selections) function extendSelections(doc, heads, options) { var out = []; var extend = doc.cm && (doc.cm.display.shift || doc.extend); for (var i = 0; i < doc.sel.ranges.length; i++) { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); setSelection(doc, newSel, options); } // Updates a single range in the selection. function replaceOneSelection(doc, i, range, options) { var ranges = doc.sel.ranges.slice(0); ranges[i] = range; setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); } // Reset the selection to a single range. function setSimpleSelection(doc, anchor, head, options) { setSelection(doc, simpleSelection(anchor, head), options); } // Give beforeSelectionChange handlers a change to influence a // selection update. function filterSelectionChange(doc, sel, options) { var obj = { ranges: sel.ranges, update: function(ranges) { var this$1 = this; this.ranges = []; for (var i = 0; i < ranges.length; i++) { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head)); } }, origin: options && options.origin }; signal(doc, "beforeSelectionChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } else { return sel } } function setSelectionReplaceHistory(doc, sel, options) { var done = doc.history.done, last = lst(done); if (last && last.ranges) { done[done.length - 1] = sel; setSelectionNoUndo(doc, sel, options); } else { setSelection(doc, sel, options); } } // Set a new selection. function setSelection(doc, sel, options) { setSelectionNoUndo(doc, sel, options); addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); } function setSelectionNoUndo(doc, sel, options) { if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) { sel = filterSelectionChange(doc, sel, options); } var bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); if (!(options && options.scroll === false) && doc.cm) { ensureCursorVisible(doc.cm); } } function setSelectionInner(doc, sel) { if (sel.equals(doc.sel)) { return } doc.sel = sel; if (doc.cm) { doc.cm.curOp.updateInput = 1; doc.cm.curOp.selectionChanged = true; signalCursorActivity(doc.cm); } signalLater(doc, "cursorActivity", doc); } // Verify that the selection does not partially select any atomic // marked ranges. function reCheckSelection(doc) { setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); } // Return a selection that does not partially select any atomic // ranges. function skipAtomicInSelection(doc, sel, bias, mayClear) { var out; for (var i = 0; i < sel.ranges.length; i++) { var range = sel.ranges[i]; var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); if (out || newAnchor != range.anchor || newHead != range.head) { if (!out) { out = sel.ranges.slice(0, i); } out[i] = new Range(newAnchor, newHead); } } return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel } function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { var line = getLine(doc, pos.line); if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { var sp = line.markedSpans[i], m = sp.marker; if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter"); if (m.explicitlyCleared) { if (!line.markedSpans) { break } else {--i; continue} } } if (!m.atomic) { continue } if (oldPos) { var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) { return skipAtomicInner(doc, near, pos, dir, mayClear) } } var far = m.find(dir < 0 ? -1 : 1); if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null } } } return pos } // Ensure a given position is not inside an atomic range. function skipAtomic(doc, pos, oldPos, bias, mayClear) { var dir = bias || 1; var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); if (!found) { doc.cantEdit = true; return Pos(doc.first, 0) } return found } function movePos(doc, pos, dir, line) { if (dir < 0 && pos.ch == 0) { if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } else { return null } } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } else { return null } } else { return new Pos(pos.line, pos.ch + dir) } } function selectAll(cm) { cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); } // UPDATING // Allow "beforeChange" event handlers to influence a change function filterChange(doc, change, update) { var obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: function () { return obj.canceled = true; } }; if (update) { obj.update = function (from, to, text, origin) { if (from) { obj.from = clipPos(doc, from); } if (to) { obj.to = clipPos(doc, to); } if (text) { obj.text = text; } if (origin !== undefined) { obj.origin = origin; } }; } signal(doc, "beforeChange", doc, obj); if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } if (obj.canceled) { if (doc.cm) { doc.cm.curOp.updateInput = 2; } return null } return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} } // Apply a change to a document, and add it to the document's // history, and propagating it to all linked documents. function makeChange(doc, change, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } if (doc.cm.state.suppressEdits) { return } } if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { change = filterChange(doc, change, true); if (!change) { return } } // Possibly split or suppress the update based on the presence // of read-only spans in its range. var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); if (split) { for (var i = split.length - 1; i >= 0; --i) { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } } else { makeChangeInner(doc, change); } } function makeChangeInner(doc, change) { if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } var selAfter = computeSelAfterChange(doc, change); addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); var rebased = []; linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); }); } // Revert a change stored in a document's history. function makeChangeFromHistory(doc, type, allowSelectionOnly) { var suppress = doc.cm && doc.cm.state.suppressEdits; if (suppress && !allowSelectionOnly) { return } var hist = doc.history, event, selAfter = doc.sel; var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; // Verify that there is a useable event (so that ctrl-z won't // needlessly clear selection events) var i = 0; for (; i < source.length; i++) { event = source[i]; if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) { break } } if (i == source.length) { return } hist.lastOrigin = hist.lastSelOrigin = null; for (;;) { event = source.pop(); if (event.ranges) { pushSelectionToHistory(event, dest); if (allowSelectionOnly && !event.equals(doc.sel)) { setSelection(doc, event, {clearRedo: false}); return } selAfter = event; } else if (suppress) { source.push(event); return } else { break } } // Build up a reverse change object to add to the opposite history // stack (redo when undoing, and vice versa). var antiChanges = []; pushSelectionToHistory(selAfter, dest); dest.push({changes: antiChanges, generation: hist.generation}); hist.generation = event.generation || ++hist.maxGeneration; var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); var loop = function ( i ) { var change = event.changes[i]; change.origin = type; if (filter && !filterChange(doc, change, false)) { source.length = 0; return {} } antiChanges.push(historyChangeFromChange(doc, change)); var after = i ? computeSelAfterChange(doc, change) : lst(source); makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } var rebased = []; // Propagate to the linked documents linkedDocs(doc, function (doc, sharedHist) { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change); rebased.push(doc.history); } makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); }); }; for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { var returned = loop( i$1 ); if ( returned ) return returned.v; } } // Sub-views need their line numbers shifted when text is added // above or below them in the parent document. function shiftDoc(doc, distance) { if (distance == 0) { return } doc.first += distance; doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch) ); }), doc.sel.primIndex); if (doc.cm) { regChange(doc.cm, doc.first, doc.first - distance, distance); for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) { regLineChange(doc.cm, l, "gutter"); } } } // More lower-level change function, handling only a single document // (not linked ones). function makeChangeSingleDoc(doc, change, selAfter, spans) { if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } if (change.to.line < doc.first) { shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); return } if (change.from.line > doc.lastLine()) { return } // Clip the change to the size of this doc if (change.from.line < doc.first) { var shift = change.text.length - 1 - (doc.first - change.from.line); shiftDoc(doc, shift); change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin}; } var last = doc.lastLine(); if (change.to.line > last) { change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin}; } change.removed = getBetween(doc, change.from, change.to); if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } else { updateDoc(doc, change, spans); } setSelectionNoUndo(doc, selAfter, sel_dontScroll); } // Handle the interaction of a change to a document with the editor // that this document is part of. function makeChangeSingleDocInEditor(cm, change, spans) { var doc = cm.doc, display = cm.display, from = change.from, to = change.to; var recomputeMaxLength = false, checkWidthStart = from.line; if (!cm.options.lineWrapping) { checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); doc.iter(checkWidthStart, to.line + 1, function (line) { if (line == display.maxLine) { recomputeMaxLength = true; return true } }); } if (doc.sel.contains(change.from, change.to) > -1) { signalCursorActivity(cm); } updateDoc(doc, change, spans, estimateHeight(cm)); if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, function (line) { var len = lineLength(line); if (len > display.maxLineLength) { display.maxLine = line; display.maxLineLength = len; display.maxLineChanged = true; recomputeMaxLength = false; } }); if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } } retreatFrontier(doc, from.line); startWorker(cm, 400); var lendiff = change.text.length - (to.line - from.line) - 1; // Remember that these lines changed, for updating the display if (change.full) { regChange(cm); } else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) { regLineChange(cm, from.line, "text"); } else { regChange(cm, from.line, to.line + 1, lendiff); } var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); if (changeHandler || changesHandler) { var obj = { from: from, to: to, text: change.text, removed: change.removed, origin: change.origin }; if (changeHandler) { signalLater(cm, "change", cm, obj); } if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } } cm.display.selForContextMenu = null; } function replaceRange(doc, code, from, to, origin) { var assign; if (!to) { to = from; } if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } if (typeof code == "string") { code = doc.splitLines(code); } makeChange(doc, {from: from, to: to, text: code, origin: origin}); } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSelSingle(pos, from, to, diff) { if (to < pos.line) { pos.line += diff; } else if (from < pos.line) { pos.line = from; pos.ch = 0; } } // Tries to rebase an array of history events given a change in the // document. If the change touches the same lines as the event, the // event, and everything 'behind' it, is discarded. If the change is // before the event, the event's positions are updated. Uses a // copy-on-write scheme for the positions, to avoid having to // reallocate them all on every rebase, but also avoid problems with // shared position objects being unsafely updated. function rebaseHistArray(array, from, to, diff) { for (var i = 0; i < array.length; ++i) { var sub = array[i], ok = true; if (sub.ranges) { if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } for (var j = 0; j < sub.ranges.length; j++) { rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); } continue } for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { var cur = sub.changes[j$1]; if (to < cur.from.line) { cur.from = Pos(cur.from.line + diff, cur.from.ch); cur.to = Pos(cur.to.line + diff, cur.to.ch); } else if (from <= cur.to.line) { ok = false; break } } if (!ok) { array.splice(0, i + 1); i = 0; } } } function rebaseHist(hist, change) { var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; rebaseHistArray(hist.done, from, to, diff); rebaseHistArray(hist.undone, from, to, diff); } // Utility for applying a change to a line by handle or number, // returning the number and optionally registering the line as // changed. function changeLine(doc, handle, changeType, op) { var no = handle, line = handle; if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } else { no = lineNo(handle); } if (no == null) { return null } if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } return line } // The document is represented as a BTree consisting of leaves, with // chunk of lines in them, and branches, with up to ten leaves or // other branch nodes below them. The top node is always a branch // node, and is the document object itself (meaning it has // additional methods and properties). // // All nodes have parent links. The tree is used both to go from // line numbers to line objects, and to go from objects to numbers. // It also indexes by height, and is used to convert between height // and line object, and to find the total height of the document. // // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html function LeafChunk(lines) { var this$1 = this; this.lines = lines; this.parent = null; var height = 0; for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; height += lines[i].height; } this.height = height; } LeafChunk.prototype = { chunkSize: function() { return this.lines.length }, // Remove the n lines at offset 'at'. removeInner: function(at, n) { var this$1 = this; for (var i = at, e = at + n; i < e; ++i) { var line = this$1.lines[i]; this$1.height -= line.height; cleanUpLine(line); signalLater(line, "delete"); } this.lines.splice(at, n); }, // Helper used to collapse a small branch into a single leaf. collapse: function(lines) { lines.push.apply(lines, this.lines); }, // Insert the given array of lines at offset 'at', count them as // having the given height. insertInner: function(at, lines, height) { var this$1 = this; this.height += height; this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } }, // Used to iterate over a part of the tree. iterN: function(at, n, op) { var this$1 = this; for (var e = at + n; at < e; ++at) { if (op(this$1.lines[at])) { return true } } } }; function BranchChunk(children) { var this$1 = this; this.children = children; var size = 0, height = 0; for (var i = 0; i < children.length; ++i) { var ch = children[i]; size += ch.chunkSize(); height += ch.height; ch.parent = this$1; } this.size = size; this.height = height; this.parent = null; } BranchChunk.prototype = { chunkSize: function() { return this.size }, removeInner: function(at, n) { var this$1 = this; this.size -= n; for (var i = 0; i < this.children.length; ++i) { var child = this$1.children[i], sz = child.chunkSize(); if (at < sz) { var rm = Math.min(n, sz - at), oldHeight = child.height; child.removeInner(at, rm); this$1.height -= oldHeight - child.height; if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } if ((n -= rm) == 0) { break } at = 0; } else { at -= sz; } } // If the result is smaller than 25 lines, ensure that it is a // single leaf node. if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { var lines = []; this.collapse(lines); this.children = [new LeafChunk(lines)]; this.children[0].parent = this; } }, collapse: function(lines) { var this$1 = this; for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } }, insertInner: function(at, lines, height) { var this$1 = this; this.size += lines.length; this.height += height; for (var i = 0; i < this.children.length; ++i) { var child = this$1.children[i], sz = child.chunkSize(); if (at <= sz) { child.insertInner(at, lines, height); if (child.lines && child.lines.length > 50) { // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. var remaining = child.lines.length % 25 + 25; for (var pos = remaining; pos < child.lines.length;) { var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); child.height -= leaf.height; this$1.children.splice(++i, 0, leaf); leaf.parent = this$1; } child.lines = child.lines.slice(0, remaining); this$1.maybeSpill(); } break } at -= sz; } }, // When a node has grown, check whether it should be split. maybeSpill: function() { if (this.children.length <= 10) { return } var me = this; do { var spilled = me.children.splice(me.children.length - 5, 5); var sibling = new BranchChunk(spilled); if (!me.parent) { // Become the parent node var copy = new BranchChunk(me.children); copy.parent = me; me.children = [copy, sibling]; me = copy; } else { me.size -= sibling.size; me.height -= sibling.height; var myIndex = indexOf(me.parent.children, me); me.parent.children.splice(myIndex + 1, 0, sibling); } sibling.parent = me.parent; } while (me.children.length > 10) me.parent.maybeSpill(); }, iterN: function(at, n, op) { var this$1 = this; for (var i = 0; i < this.children.length; ++i) { var child = this$1.children[i], sz = child.chunkSize(); if (at < sz) { var used = Math.min(n, sz - at); if (child.iterN(at, used, op)) { return true } if ((n -= used) == 0) { break } at = 0; } else { at -= sz; } } } }; // Line widgets are block elements displayed above or below a line. var LineWidget = function(doc, node, options) { var this$1 = this; if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) { this$1[opt] = options[opt]; } } } this.doc = doc; this.node = node; }; LineWidget.prototype.clear = function () { var this$1 = this; var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); if (no == null || !ws) { return } for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } if (!ws.length) { line.widgets = null; } var height = widgetHeight(this); updateLineHeight(line, Math.max(0, line.height - height)); if (cm) { runInOp(cm, function () { adjustScrollWhenAboveVisible(cm, line, -height); regLineChange(cm, no, "widget"); }); signalLater(cm, "lineWidgetCleared", cm, this, no); } }; LineWidget.prototype.changed = function () { var this$1 = this; var oldH = this.height, cm = this.doc.cm, line = this.line; this.height = null; var diff = widgetHeight(this) - oldH; if (!diff) { return } if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } if (cm) { runInOp(cm, function () { cm.curOp.forceUpdate = true; adjustScrollWhenAboveVisible(cm, line, diff); signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); }); } }; eventMixin(LineWidget); function adjustScrollWhenAboveVisible(cm, line, diff) { if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) { addToScrollTop(cm, diff); } } function addLineWidget(doc, handle, node, options) { var widget = new LineWidget(doc, node, options); var cm = doc.cm; if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } changeLine(doc, handle, "widget", function (line) { var widgets = line.widgets || (line.widgets = []); if (widget.insertAt == null) { widgets.push(widget); } else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } widget.line = line; if (cm && !lineIsHidden(doc, line)) { var aboveVisible = heightAtLine(line) < doc.scrollTop; updateLineHeight(line, line.height + widgetHeight(widget)); if (aboveVisible) { addToScrollTop(cm, widget.height); } cm.curOp.forceUpdate = true; } return true }); if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } return widget } // TEXTMARKERS // Created with markText and setBookmark methods. A TextMarker is a // handle that can be used to clear or find a marked position in the // document. Line objects hold arrays (markedSpans) containing // {from, to, marker} object pointing to such marker objects, and // indicating that such a marker is present on that line. Multiple // lines may point to the same marker when it spans across lines. // The spans will have null for their from/to properties when the // marker continues beyond the start/end of the line. Markers have // links back to the lines they currently touch. // Collapsed markers have unique ids, in order to be able to order // them, which is needed for uniquely determining an outer marker // when they overlap (they may nest, but not partially overlap). var nextMarkerId = 0; var TextMarker = function(doc, type) { this.lines = []; this.type = type; this.doc = doc; this.id = ++nextMarkerId; }; // Clear the marker. TextMarker.prototype.clear = function () { var this$1 = this; if (this.explicitlyCleared) { return } var cm = this.doc.cm, withOp = cm && !cm.curOp; if (withOp) { startOperation(cm); } if (hasHandler(this, "clear")) { var found = this.find(); if (found) { signalLater(this, "clear", found.from, found.to); } } var min = null, max = null; for (var i = 0; i < this.lines.length; ++i) { var line = this$1.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this$1); if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } else if (cm) { if (span.to != null) { max = lineNo(line); } if (span.from != null) { min = lineNo(line); } } line.markedSpans = removeMarkedSpan(line.markedSpans, span); if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) { updateLineHeight(line, textHeight(cm.display)); } } if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); if (len > cm.display.maxLineLength) { cm.display.maxLine = visual; cm.display.maxLineLength = len; cm.display.maxLineChanged = true; } } } if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } this.lines.length = 0; this.explicitlyCleared = true; if (this.atomic && this.doc.cantEdit) { this.doc.cantEdit = false; if (cm) { reCheckSelection(cm.doc); } } if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } if (withOp) { endOperation(cm); } if (this.parent) { this.parent.clear(); } }; // Find the position of the marker in the document. Returns a {from, // to} object by default. Side can be passed to get a specific side // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the // Pos objects returned contain a line object, rather than a line // number (used to prevent looking up the same line twice). TextMarker.prototype.find = function (side, lineObj) { var this$1 = this; if (side == null && this.type == "bookmark") { side = 1; } var from, to; for (var i = 0; i < this.lines.length; ++i) { var line = this$1.lines[i]; var span = getMarkedSpanFor(line.markedSpans, this$1); if (span.from != null) { from = Pos(lineObj ? line : lineNo(line), span.from); if (side == -1) { return from } } if (span.to != null) { to = Pos(lineObj ? line : lineNo(line), span.to); if (side == 1) { return to } } } return from && {from: from, to: to} }; // Signals that the marker's widget changed, and surrounding layout // should be recomputed. TextMarker.prototype.changed = function () { var this$1 = this; var pos = this.find(-1, true), widget = this, cm = this.doc.cm; if (!pos || !cm) { return } runInOp(cm, function () { var line = pos.line, lineN = lineNo(pos.line); var view = findViewForLine(cm, lineN); if (view) { clearLineMeasurementCacheFor(view); cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; } cm.curOp.updateMaxLine = true; if (!lineIsHidden(widget.doc, line) && widget.height != null) { var oldHeight = widget.height; widget.height = null; var dHeight = widgetHeight(widget) - oldHeight; if (dHeight) { updateLineHeight(line, line.height + dHeight); } } signalLater(cm, "markerChanged", cm, this$1); }); }; TextMarker.prototype.attachLine = function (line) { if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp; if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } } this.lines.push(line); }; TextMarker.prototype.detachLine = function (line) { this.lines.splice(indexOf(this.lines, line), 1); if (!this.lines.length && this.doc.cm) { var op = this.doc.cm.curOp ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); } }; eventMixin(TextMarker); // Create a marker, wire it up to the right lines, and function markText(doc, from, to, options, type) { // Shared markers (across linked documents) are handled separately // (markTextShared will call out to this again, once per // document). if (options && options.shared) { return markTextShared(doc, from, to, options, type) } // Ensure we are in an operation. if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } var marker = new TextMarker(doc, type), diff = cmp(from, to); if (options) { copyObj(options, marker, false); } // Don't connect empty markers unless clearWhenEmpty is false if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) { return marker } if (marker.replacedWith) { // Showing up as a widget implies collapsed (widget replaces text) marker.collapsed = true; marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } if (options.insertLeft) { marker.widgetNode.insertLeft = true; } } if (marker.collapsed) { if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) { throw new Error("Inserting collapsed marker partially overlapping an existing one") } seeCollapsedSpans(); } if (marker.addToHistory) { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } var curLine = from.line, cm = doc.cm, updateMaxLine; doc.iter(curLine, to.line + 1, function (line) { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) { updateMaxLine = true; } if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null)); ++curLine; }); // lineIsHidden depends on the presence of the spans, so needs a second pass if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } }); } if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } if (marker.readOnly) { seeReadOnlySpans(); if (doc.history.done.length || doc.history.undone.length) { doc.clearHistory(); } } if (marker.collapsed) { marker.id = ++nextMarkerId; marker.atomic = true; } if (cm) { // Sync editor state if (updateMaxLine) { cm.curOp.updateMaxLine = true; } if (marker.collapsed) { regChange(cm, from.line, to.line + 1); } else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } if (marker.atomic) { reCheckSelection(cm.doc); } signalLater(cm, "markerAdded", cm, marker); } return marker } // SHARED TEXTMARKERS // A shared marker spans multiple linked documents. It is // implemented as a meta-marker-object controlling multiple normal // markers. var SharedTextMarker = function(markers, primary) { var this$1 = this; this.markers = markers; this.primary = primary; for (var i = 0; i < markers.length; ++i) { markers[i].parent = this$1; } }; SharedTextMarker.prototype.clear = function () { var this$1 = this; if (this.explicitlyCleared) { return } this.explicitlyCleared = true; for (var i = 0; i < this.markers.length; ++i) { this$1.markers[i].clear(); } signalLater(this, "clear"); }; SharedTextMarker.prototype.find = function (side, lineObj) { return this.primary.find(side, lineObj) }; eventMixin(SharedTextMarker); function markTextShared(doc, from, to, options, type) { options = copyObj(options); options.shared = false; var markers = [markText(doc, from, to, options, type)], primary = markers[0]; var widget = options.widgetNode; linkedDocs(doc, function (doc) { if (widget) { options.widgetNode = widget.cloneNode(true); } markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); for (var i = 0; i < doc.linked.length; ++i) { if (doc.linked[i].isParent) { return } } primary = lst(markers); }); return new SharedTextMarker(markers, primary) } function findSharedMarkers(doc) { return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) } function copySharedMarkers(doc, markers) { for (var i = 0; i < markers.length; i++) { var marker = markers[i], pos = marker.find(); var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); if (cmp(mFrom, mTo)) { var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); marker.markers.push(subMark); subMark.parent = marker; } } } function detachSharedMarkers(markers) { var loop = function ( i ) { var marker = markers[i], linked = [marker.primary.doc]; linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); for (var j = 0; j < marker.markers.length; j++) { var subMarker = marker.markers[j]; if (indexOf(linked, subMarker.doc) == -1) { subMarker.parent = null; marker.markers.splice(j--, 1); } } }; for (var i = 0; i < markers.length; i++) loop( i ); } var nextDocId = 0; var Doc = function(text, mode, firstLine, lineSep, direction) { if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } if (firstLine == null) { firstLine = 0; } BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); this.first = firstLine; this.scrollTop = this.scrollLeft = 0; this.cantEdit = false; this.cleanGeneration = 1; this.modeFrontier = this.highlightFrontier = firstLine; var start = Pos(firstLine, 0); this.sel = simpleSelection(start); this.history = new History(null); this.id = ++nextDocId; this.modeOption = mode; this.lineSep = lineSep; this.direction = (direction == "rtl") ? "rtl" : "ltr"; this.extend = false; if (typeof text == "string") { text = this.splitLines(text); } updateDoc(this, {from: start, to: start, text: text}); setSelection(this, simpleSelection(start), sel_dontScroll); }; Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, // Iterate over the document. Supports two forms -- with only one // argument, it calls that for each line in the document. With // three, it iterates over the range given by the first two (with // the second being non-inclusive). iter: function(from, to, op) { if (op) { this.iterN(from - this.first, to - from, op); } else { this.iterN(this.first, this.first + this.size, from); } }, // Non-public interface for adding and removing lines. insert: function(at, lines) { var height = 0; for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } this.insertInner(at - this.first, lines, height); }, remove: function(at, n) { this.removeInner(at - this.first, n); }, // From here, the methods are part of the public interface. Most // are also available from CodeMirror (editor) instances. getValue: function(lineSep) { var lines = getLines(this, this.first, this.first + this.size); if (lineSep === false) { return lines } return lines.join(lineSep || this.lineSeparator()) }, setValue: docMethodOp(function(code) { var top = Pos(this.first, 0), last = this.first + this.size - 1; makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), text: this.splitLines(code), origin: "setValue", full: true}, true); if (this.cm) { scrollToCoords(this.cm, 0, 0); } setSelection(this, simpleSelection(top), sel_dontScroll); }), replaceRange: function(code, from, to, origin) { from = clipPos(this, from); to = to ? clipPos(this, to) : from; replaceRange(this, code, from, to, origin); }, getRange: function(from, to, lineSep) { var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); if (lineSep === false) { return lines } return lines.join(lineSep || this.lineSeparator()) }, getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, getLineNumber: function(line) {return lineNo(line)}, getLineHandleVisualStart: function(line) { if (typeof line == "number") { line = getLine(this, line); } return visualLine(line) }, lineCount: function() {return this.size}, firstLine: function() {return this.first}, lastLine: function() {return this.first + this.size - 1}, clipPos: function(pos) {return clipPos(this, pos)}, getCursor: function(start) { var range$$1 = this.sel.primary(), pos; if (start == null || start == "head") { pos = range$$1.head; } else if (start == "anchor") { pos = range$$1.anchor; } else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } else { pos = range$$1.from(); } return pos }, listSelections: function() { return this.sel.ranges }, somethingSelected: function() {return this.sel.somethingSelected()}, setCursor: docMethodOp(function(line, ch, options) { setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); }), setSelection: docMethodOp(function(anchor, head, options) { setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); }), extendSelection: docMethodOp(function(head, other, options) { extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); }), extendSelections: docMethodOp(function(heads, options) { extendSelections(this, clipPosArray(this, heads), options); }), extendSelectionsBy: docMethodOp(function(f, options) { var heads = map(this.sel.ranges, f); extendSelections(this, clipPosArray(this, heads), options); }), setSelections: docMethodOp(function(ranges, primary, options) { var this$1 = this; if (!ranges.length) { return } var out = []; for (var i = 0; i < ranges.length; i++) { out[i] = new Range(clipPos(this$1, ranges[i].anchor), clipPos(this$1, ranges[i].head)); } if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } setSelection(this, normalizeSelection(this.cm, out, primary), options); }), addSelection: docMethodOp(function(anchor, head, options) { var ranges = this.sel.ranges.slice(0); ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); }), getSelection: function(lineSep) { var this$1 = this; var ranges = this.sel.ranges, lines; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); lines = lines ? lines.concat(sel) : sel; } if (lineSep === false) { return lines } else { return lines.join(lineSep || this.lineSeparator()) } }, getSelections: function(lineSep) { var this$1 = this; var parts = [], ranges = this.sel.ranges; for (var i = 0; i < ranges.length; i++) { var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } parts[i] = sel; } return parts }, replaceSelection: function(code, collapse, origin) { var dup = []; for (var i = 0; i < this.sel.ranges.length; i++) { dup[i] = code; } this.replaceSelections(dup, collapse, origin || "+input"); }, replaceSelections: docMethodOp(function(code, collapse, origin) { var this$1 = this; var changes = [], sel = this.sel; for (var i = 0; i < sel.ranges.length; i++) { var range$$1 = sel.ranges[i]; changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; } var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) { makeChange(this$1, changes[i$1]); } if (newSel) { setSelectionReplaceHistory(this, newSel); } else if (this.cm) { ensureCursorVisible(this.cm); } }), undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), setExtending: function(val) {this.extend = val;}, getExtending: function() {return this.extend}, historySize: function() { var hist = this.history, done = 0, undone = 0; for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } return {undo: done, redo: undone} }, clearHistory: function() {this.history = new History(this.history.maxGeneration);}, markClean: function() { this.cleanGeneration = this.changeGeneration(true); }, changeGeneration: function(forceSplit) { if (forceSplit) { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } return this.history.generation }, isClean: function (gen) { return this.history.generation == (gen || this.cleanGeneration) }, getHistory: function() { return {done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone)} }, setHistory: function(histData) { var hist = this.history = new History(this.history.maxGeneration); hist.done = copyHistoryArray(histData.done.slice(0), null, true); hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); }, setGutterMarker: docMethodOp(function(line, gutterID, value) { return changeLine(this, line, "gutter", function (line) { var markers = line.gutterMarkers || (line.gutterMarkers = {}); markers[gutterID] = value; if (!value && isEmpty(markers)) { line.gutterMarkers = null; } return true }) }), clearGutter: docMethodOp(function(gutterID) { var this$1 = this; this.iter(function (line) { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { changeLine(this$1, line, "gutter", function () { line.gutterMarkers[gutterID] = null; if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } return true }); } }); }), lineInfo: function(line) { var n; if (typeof line == "number") { if (!isLine(this, line)) { return null } n = line; line = getLine(this, line); if (!line) { return null } } else { n = lineNo(line); if (n == null) { return null } } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets} }, addLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; if (!line[prop]) { line[prop] = cls; } else if (classTest(cls).test(line[prop])) { return false } else { line[prop] += " " + cls; } return true }) }), removeLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { var prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass"; var cur = line[prop]; if (!cur) { return false } else if (cls == null) { line[prop] = null; } else { var found = cur.match(classTest(cls)); if (!found) { return false } var end = found.index + found[0].length; line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; } return true }) }), addLineWidget: docMethodOp(function(handle, node, options) { return addLineWidget(this, handle, node, options) }), removeLineWidget: function(widget) { widget.clear(); }, markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") }, setBookmark: function(pos, options) { var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft, clearWhenEmpty: false, shared: options && options.shared, handleMouseEvents: options && options.handleMouseEvents}; pos = clipPos(this, pos); return markText(this, pos, pos, realOpts, "bookmark") }, findMarksAt: function(pos) { pos = clipPos(this, pos); var markers = [], spans = getLine(this, pos.line).markedSpans; if (spans) { for (var i = 0; i < spans.length; ++i) { var span = spans[i]; if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) { markers.push(span.marker.parent || span.marker); } } } return markers }, findMarks: function(from, to, filter) { from = clipPos(this, from); to = clipPos(this, to); var found = [], lineNo$$1 = from.line; this.iter(from.line, to.line + 1, function (line) { var spans = line.markedSpans; if (spans) { for (var i = 0; i < spans.length; i++) { var span = spans[i]; if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || span.from == null && lineNo$$1 != from.line || span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) { found.push(span.marker.parent || span.marker); } } } ++lineNo$$1; }); return found }, getAllMarks: function() { var markers = []; this.iter(function (line) { var sps = line.markedSpans; if (sps) { for (var i = 0; i < sps.length; ++i) { if (sps[i].from != null) { markers.push(sps[i].marker); } } } }); return markers }, posFromIndex: function(off) { var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; this.iter(function (line) { var sz = line.text.length + sepSize; if (sz > off) { ch = off; return true } off -= sz; ++lineNo$$1; }); return clipPos(this, Pos(lineNo$$1, ch)) }, indexFromPos: function (coords) { coords = clipPos(this, coords); var index = coords.ch; if (coords.line < this.first || coords.ch < 0) { return 0 } var sepSize = this.lineSeparator().length; this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value index += line.text.length + sepSize; }); return index }, copy: function(copyHistory) { var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction); doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; doc.sel = this.sel; doc.extend = false; if (copyHistory) { doc.history.undoDepth = this.history.undoDepth; doc.setHistory(this.getHistory()); } return doc }, linkedDoc: function(options) { if (!options) { options = {}; } var from = this.first, to = this.first + this.size; if (options.from != null && options.from > from) { from = options.from; } if (options.to != null && options.to < to) { to = options.to; } var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); if (options.sharedHist) { copy.history = this.history ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; copySharedMarkers(copy, findSharedMarkers(this)); return copy }, unlinkDoc: function(other) { var this$1 = this; if (other instanceof CodeMirror) { other = other.doc; } if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { var link = this$1.linked[i]; if (link.doc != other) { continue } this$1.linked.splice(i, 1); other.unlinkDoc(this$1); detachSharedMarkers(findSharedMarkers(this$1)); break } } // If the histories were shared, split them again if (other.history == this.history) { var splitIds = [other.id]; linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); other.history = new History(null); other.history.done = copyHistoryArray(this.history.done, splitIds); other.history.undone = copyHistoryArray(this.history.undone, splitIds); } }, iterLinkedDocs: function(f) {linkedDocs(this, f);}, getMode: function() {return this.mode}, getEditor: function() {return this.cm}, splitLines: function(str) { if (this.lineSep) { return str.split(this.lineSep) } return splitLinesAuto(str) }, lineSeparator: function() { return this.lineSep || "\n" }, setDirection: docMethodOp(function (dir) { if (dir != "rtl") { dir = "ltr"; } if (dir == this.direction) { return } this.direction = dir; this.iter(function (line) { return line.order = null; }); if (this.cm) { directionChanged(this.cm); } }) }); // Public alias. Doc.prototype.eachLine = Doc.prototype.iter; // Kludge to work around strange IE behavior where it'll sometimes // re-fire a series of drag-related events right after the drop (#1551) var lastDrop = 0; function onDrop(e) { var cm = this; clearDragCursor(cm); if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); if (ie) { lastDrop = +new Date; } var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; if (!pos || cm.isReadOnly()) { return } // Might be a file drop, in which case we simply extract the text // and insert it. if (files && files.length && window.FileReader && window.File) { var n = files.length, text = Array(n), read = 0; var loadFile = function (file, i) { if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) { return } var reader = new FileReader; reader.onload = operation(cm, function () { var content = reader.result; if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { content = ""; } text[i] = content; if (++read == n) { pos = clipPos(cm.doc, pos); var change = {from: pos, to: pos, text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), origin: "paste"}; makeChange(cm.doc, change); setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); } }); reader.readAsText(file); }; for (var i = 0; i < n; ++i) { loadFile(files[i], i); } } else { // Normal drop // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { cm.state.draggingText(e); // Ensure the editor is re-focused setTimeout(function () { return cm.display.input.focus(); }, 20); return } try { var text$1 = e.dataTransfer.getData("Text"); if (text$1) { var selected; if (cm.state.draggingText && !cm.state.draggingText.copy) { selected = cm.listSelections(); } setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } cm.replaceSelection(text$1, "around", "paste"); cm.display.input.focus(); } } catch(e){} } } function onDragStart(cm, e) { if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } e.dataTransfer.setData("Text", cm.getSelection()); e.dataTransfer.effectAllowed = "copyMove"; // Use dummy image instead of default browsers image. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. if (e.dataTransfer.setDragImage && !safari) { var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; if (presto) { img.width = img.height = 1; cm.display.wrapper.appendChild(img); // Force a relayout, or Opera won't use our image for some obscure reason img._top = img.offsetTop; } e.dataTransfer.setDragImage(img, 0, 0); if (presto) { img.parentNode.removeChild(img); } } } function onDragOver(cm, e) { var pos = posFromMouse(cm, e); if (!pos) { return } var frag = document.createDocumentFragment(); drawSelectionCursor(cm, pos, frag); if (!cm.display.dragCursor) { cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); } removeChildrenAndAdd(cm.display.dragCursor, frag); } function clearDragCursor(cm) { if (cm.display.dragCursor) { cm.display.lineSpace.removeChild(cm.display.dragCursor); cm.display.dragCursor = null; } } // These must be handled carefully, because naively registering a // handler for each editor will cause the editors to never be // garbage collected. function forEachCodeMirror(f) { if (!document.getElementsByClassName) { return } var byClass = document.getElementsByClassName("CodeMirror"), editors = []; for (var i = 0; i < byClass.length; i++) { var cm = byClass[i].CodeMirror; if (cm) { editors.push(cm); } } if (editors.length) { editors[0].operation(function () { for (var i = 0; i < editors.length; i++) { f(editors[i]); } }); } } var globalsRegistered = false; function ensureGlobalHandlers() { if (globalsRegistered) { return } registerGlobalHandlers(); globalsRegistered = true; } function registerGlobalHandlers() { // When the window resizes, we need to refresh active editors. var resizeTimer; on(window, "resize", function () { if (resizeTimer == null) { resizeTimer = setTimeout(function () { resizeTimer = null; forEachCodeMirror(onResize); }, 100); } }); // When the window loses focus, we want to show the editor as blurred on(window, "blur", function () { return forEachCodeMirror(onBlur); }); } // Called when the window resizes function onResize(cm) { var d = cm.display; // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; d.scrollbarsClipped = false; cm.setSize(); } var keyNames = { 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" }; // Number keys for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } // Alphabetic keys for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } // Function keys for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } var keyMap = {}; keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", "Esc": "singleSelection" }; // Note that the save and find-related commands aren't defined by // default. User code or addons can define them. Unknown commands // are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", "fallthrough": "basic" }; // Very basic readline/emacs-style bindings, which are standard on Mac. keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", "Ctrl-O": "openLine" }; keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", "fallthrough": ["basic", "emacsy"] }; keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; // KEYMAP DISPATCH function normalizeKeyName(name) { var parts = name.split(/-(?!$)/); name = parts[parts.length - 1]; var alt, ctrl, shift, cmd; for (var i = 0; i < parts.length - 1; i++) { var mod = parts[i]; if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } else if (/^a(lt)?$/i.test(mod)) { alt = true; } else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } else if (/^s(hift)?$/i.test(mod)) { shift = true; } else { throw new Error("Unrecognized modifier name: " + mod) } } if (alt) { name = "Alt-" + name; } if (ctrl) { name = "Ctrl-" + name; } if (cmd) { name = "Cmd-" + name; } if (shift) { name = "Shift-" + name; } return name } // This is a kludge to keep keymaps mostly working as raw objects // (backwards compatibility) while at the same time support features // like normalization and multi-stroke key bindings. It compiles a // new normalized keymap, and then updates the old object to reflect // this. function normalizeKeyMap(keymap) { var copy = {}; for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { var value = keymap[keyname]; if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } if (value == "...") { delete keymap[keyname]; continue } var keys = map(keyname.split(" "), normalizeKeyName); for (var i = 0; i < keys.length; i++) { var val = (void 0), name = (void 0); if (i == keys.length - 1) { name = keys.join(" "); val = value; } else { name = keys.slice(0, i + 1).join(" "); val = "..."; } var prev = copy[name]; if (!prev) { copy[name] = val; } else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } } delete keymap[keyname]; } } for (var prop in copy) { keymap[prop] = copy[prop]; } return keymap } function lookupKey(key, map$$1, handle, context) { map$$1 = getKeyMap(map$$1); var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; if (found === false) { return "nothing" } if (found === "...") { return "multi" } if (found != null && handle(found)) { return "handled" } if (map$$1.fallthrough) { if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") { return lookupKey(key, map$$1.fallthrough, handle, context) } for (var i = 0; i < map$$1.fallthrough.length; i++) { var result = lookupKey(key, map$$1.fallthrough[i], handle, context); if (result) { return result } } } } // Modifier key presses don't count as 'real' key presses for the // purpose of keymap fallthrough. function isModifierKey(value) { var name = typeof value == "string" ? value : keyNames[value.keyCode]; return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" } function addModifierNames(name, event, noShift) { var base = name; if (event.altKey && base != "Alt") { name = "Alt-" + name; } if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } return name } // Look up the name of a key as indicated by an event object. function keyName(event, noShift) { if (presto && event.keyCode == 34 && event["char"]) { return false } var name = keyNames[event.keyCode]; if (name == null || event.altGraphKey) { return false } // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) if (event.keyCode == 3 && event.code) { name = event.code; } return addModifierNames(name, event, noShift) } function getKeyMap(val) { return typeof val == "string" ? keyMap[val] : val } // Helper for deleting text near the selection(s), used to implement // backspace, delete, and similar functionality. function deleteNearSelection(cm, compute) { var ranges = cm.doc.sel.ranges, kill = []; // Build up a set of ranges to kill first, merging overlapping // ranges. for (var i = 0; i < ranges.length; i++) { var toKill = compute(ranges[i]); while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { var replaced = kill.pop(); if (cmp(replaced.from, toKill.from) < 0) { toKill.from = replaced.from; break } } kill.push(toKill); } // Next, remove those actual ranges. runInOp(cm, function () { for (var i = kill.length - 1; i >= 0; i--) { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } ensureCursorVisible(cm); }); } function moveCharLogically(line, ch, dir) { var target = skipExtendingChars(line.text, ch + dir, dir); return target < 0 || target > line.text.length ? null : target } function moveLogically(line, start, dir) { var ch = moveCharLogically(line, start.ch, dir); return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") } function endOfLine(visually, cm, lineObj, lineNo, dir) { if (visually) { var order = getOrder(lineObj, cm.doc.direction); if (order) { var part = dir < 0 ? lst(order) : order[0]; var moveInStorageOrder = (dir < 0) == (part.level == 1); var sticky = moveInStorageOrder ? "after" : "before"; var ch; // With a wrapped rtl chunk (possibly spanning multiple bidi parts), // it could be that the last bidi part is not on the last visual line, // since visual lines contain content order-consecutive chunks. // Thus, in rtl, we are looking for the first (content-order) character // in the rtl chunk that is on the last line (that is, the same line // as the last (content-order) character). if (part.level > 0 || cm.doc.direction == "rtl") { var prep = prepareMeasureForLine(cm, lineObj); ch = dir < 0 ? lineObj.text.length - 1 : 0; var targetTop = measureCharPrepared(cm, prep, ch).top; ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } } else { ch = dir < 0 ? part.to : part.from; } return new Pos(lineNo, ch, sticky) } } return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") } function moveVisually(cm, line, start, dir) { var bidi = getOrder(line, cm.doc.direction); if (!bidi) { return moveLogically(line, start, dir) } if (start.ch >= line.text.length) { start.ch = line.text.length; start.sticky = "before"; } else if (start.ch <= 0) { start.ch = 0; start.sticky = "after"; } var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, // nothing interesting happens. return moveLogically(line, start, dir) } var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; var prep; var getWrappedLineExtent = function (ch) { if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } prep = prep || prepareMeasureForLine(cm, line); return wrappedLineExtentChar(cm, line, prep, ch) }; var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); if (cm.doc.direction == "rtl" || part.level == 1) { var moveInStorageOrder = (part.level == 1) == (dir < 0); var ch = mv(start, moveInStorageOrder ? 1 : -1); if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { // Case 2: We move within an rtl part or in an rtl editor on the same visual line var sticky = moveInStorageOrder ? "before" : "after"; return new Pos(start.line, ch, sticky) } } // Case 3: Could not move within this bidi part in this visual line, so leave // the current bidi part var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder ? new Pos(start.line, mv(ch, 1), "before") : new Pos(start.line, ch, "after"); }; for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { var part = bidi[partPos]; var moveInStorageOrder = (dir > 0) == (part.level != 1); var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } ch = moveInStorageOrder ? part.from : mv(part.to, -1); if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } } }; // Case 3a: Look for other bidi parts on the same visual line var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); if (res) { return res } // Case 3b: Look for other bidi parts on the next visual line var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); if (res) { return res } } // Case 4: Nowhere to move return null } // Commands are parameter-less actions that can be performed on an // editor, mostly used for keybindings. var commands = { selectAll: selectAll, singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, killLine: function (cm) { return deleteNearSelection(cm, function (range) { if (range.empty()) { var len = getLine(cm.doc, range.head.line).text.length; if (range.head.ch == len && range.head.line < cm.lastLine()) { return {from: range.head, to: Pos(range.head.line + 1, 0)} } else { return {from: range.head, to: Pos(range.head.line, len)} } } else { return {from: range.from(), to: range.to()} } }); }, deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) }); }); }, delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ from: Pos(range.from().line, 0), to: range.from() }); }); }, delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var leftPos = cm.coordsChar({left: 0, top: top}, "div"); return {from: leftPos, to: range.from()} }); }, delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { var top = cm.charCoords(range.head, "div").top + 5; var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); return {from: range.from(), to: rightPos } }); }, undo: function (cm) { return cm.undo(); }, redo: function (cm) { return cm.redo(); }, undoSelection: function (cm) { return cm.undoSelection(); }, redoSelection: function (cm) { return cm.redoSelection(); }, goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, {origin: "+move", bias: 1} ); }, goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, {origin: "+move", bias: 1} ); }, goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, {origin: "+move", bias: -1} ); }, goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") }, sel_move); }, goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; return cm.coordsChar({left: 0, top: top}, "div") }, sel_move); }, goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { var top = cm.cursorCoords(range.head, "div").top + 5; var pos = cm.coordsChar({left: 0, top: top}, "div"); if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } return pos }, sel_move); }, goLineUp: function (cm) { return cm.moveV(-1, "line"); }, goLineDown: function (cm) { return cm.moveV(1, "line"); }, goPageUp: function (cm) { return cm.moveV(-1, "page"); }, goPageDown: function (cm) { return cm.moveV(1, "page"); }, goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, goCharRight: function (cm) { return cm.moveH(1, "char"); }, goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, goColumnRight: function (cm) { return cm.moveH(1, "column"); }, goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, goGroupRight: function (cm) { return cm.moveH(1, "group"); }, goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, goWordRight: function (cm) { return cm.moveH(1, "word"); }, delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, indentAuto: function (cm) { return cm.indentSelection("smart"); }, indentMore: function (cm) { return cm.indentSelection("add"); }, indentLess: function (cm) { return cm.indentSelection("subtract"); }, insertTab: function (cm) { return cm.replaceSelection("\t"); }, insertSoftTab: function (cm) { var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; for (var i = 0; i < ranges.length; i++) { var pos = ranges[i].from(); var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); spaces.push(spaceStr(tabSize - col % tabSize)); } cm.replaceSelections(spaces); }, defaultTab: function (cm) { if (cm.somethingSelected()) { cm.indentSelection("add"); } else { cm.execCommand("insertTab"); } }, // Swap the two chars left and right of each selection's head. // Move cursor behind the two swapped characters afterwards. // // Doesn't consider line feeds a character. // Doesn't scan more than one line above to find a character. // Doesn't do anything on an empty line. // Doesn't do anything with non-empty selections. transposeChars: function (cm) { return runInOp(cm, function () { var ranges = cm.listSelections(), newSel = []; for (var i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) { continue } var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; if (line) { if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } if (cur.ch > 0) { cur = new Pos(cur.line, cur.ch + 1); cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose"); } else if (cur.line > cm.doc.first) { var prev = getLine(cm.doc, cur.line - 1).text; if (prev) { cur = new Pos(cur.line, 1); cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); } } } newSel.push(new Range(cur, cur)); } cm.setSelections(newSel); }); }, newlineAndIndent: function (cm) { return runInOp(cm, function () { var sels = cm.listSelections(); for (var i = sels.length - 1; i >= 0; i--) { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } sels = cm.listSelections(); for (var i$1 = 0; i$1 < sels.length; i$1++) { cm.indentLine(sels[i$1].from().line, null, true); } ensureCursorVisible(cm); }); }, openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } }; function lineStart(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLine(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, visual, lineN, 1) } function lineEnd(cm, lineN) { var line = getLine(cm.doc, lineN); var visual = visualLineEnd(line); if (visual != line) { lineN = lineNo(visual); } return endOfLine(true, cm, line, lineN, -1) } function lineStartSmart(cm, pos) { var start = lineStart(cm, pos.line); var line = getLine(cm.doc, start.line); var order = getOrder(line, cm.doc.direction); if (!order || order[0].level == 0) { var firstNonWS = Math.max(0, line.text.search(/\S/)); var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) } return start } // Run a handler that was bound to a key. function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound]; if (!bound) { return false } } // Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled(); var prevShift = cm.display.shift, done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } if (dropShift) { cm.display.shift = false; } done = bound(cm) != Pass; } finally { cm.display.shift = prevShift; cm.state.suppressEdits = false; } return done } function lookupKeyForEditor(cm, name, handle) { for (var i = 0; i < cm.state.keyMaps.length; i++) { var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); if (result) { return result } } return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) || lookupKey(name, cm.options.keyMap, handle, cm) } // Note that, despite the name, this function is also used to check // for bound mouse clicks. var stopSeq = new Delayed; function dispatchKey(cm, name, e, handle) { var seq = cm.state.keySeq; if (seq) { if (isModifierKey(name)) { return "handled" } if (/\'$/.test(name)) { cm.state.keySeq = null; } else { stopSeq.set(50, function () { if (cm.state.keySeq == seq) { cm.state.keySeq = null; cm.display.input.reset(); } }); } if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } } return dispatchKeyInner(cm, name, e, handle) } function dispatchKeyInner(cm, name, e, handle) { var result = lookupKeyForEditor(cm, name, handle); if (result == "multi") { cm.state.keySeq = name; } if (result == "handled") { signalLater(cm, "keyHandled", cm, name, e); } if (result == "handled" || result == "multi") { e_preventDefault(e); restartBlink(cm); } return !!result } // Handle a key from the keydown event. function handleKeyBinding(cm, e) { var name = keyName(e, true); if (!name) { return false } if (e.shiftKey && !cm.state.keySeq) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) || dispatchKey(cm, name, e, function (b) { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) { return doHandleBinding(cm, b) } }) } else { return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) } } // Handle a key from the keypress event function handleCharBinding(cm, e, ch) { return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) } var lastStoppedKey = null; function onKeyDown(e) { var cm = this; cm.curOp.focus = activeElt(); if (signalDOMEvent(cm, e)) { return } // IE does strange things with escape. if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } var code = e.keyCode; cm.display.shift = code == 16 || e.shiftKey; var handled = handleKeyBinding(cm, e); if (presto) { lastStoppedKey = handled ? code : null; // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) { cm.replaceSelection("", null, "cut"); } } // Turn mouse into crosshair when Alt is held on Mac. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) { showCrossHair(cm); } } function showCrossHair(cm) { var lineDiv = cm.display.lineDiv; addClass(lineDiv, "CodeMirror-crosshair"); function up(e) { if (e.keyCode == 18 || !e.altKey) { rmClass(lineDiv, "CodeMirror-crosshair"); off(document, "keyup", up); off(document, "mouseover", up); } } on(document, "keyup", up); on(document, "mouseover", up); } function onKeyUp(e) { if (e.keyCode == 16) { this.doc.sel.shift = false; } signalDOMEvent(this, e); } function onKeyPress(e) { var cm = this; if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } var keyCode = e.keyCode, charCode = e.charCode; if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } var ch = String.fromCharCode(charCode == null ? keyCode : charCode); // Some browsers fire keypress events for backspace if (ch == "\x08") { return } if (handleCharBinding(cm, e, ch)) { return } cm.display.input.onKeyPress(e); } var DOUBLECLICK_DELAY = 400; var PastClick = function(time, pos, button) { this.time = time; this.pos = pos; this.button = button; }; PastClick.prototype.compare = function (time, pos, button) { return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button }; var lastClick, lastDoubleClick; function clickRepeat(pos, button) { var now = +new Date; if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { lastClick = lastDoubleClick = null; return "triple" } else if (lastClick && lastClick.compare(now, pos, button)) { lastDoubleClick = new PastClick(now, pos, button); lastClick = null; return "double" } else { lastClick = new PastClick(now, pos, button); lastDoubleClick = null; return "single" } } // A mouse down can be a single click, double click, triple click, // start of selection drag, start of text drag, new cursor // (ctrl-click), rectangle drag (alt-drag), or xwin // middle-click-paste. Or it might be a click on something we should // not interfere with, such as a scrollbar or widget. function onMouseDown(e) { var cm = this, display = cm.display; if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } display.input.ensurePolled(); display.shift = e.shiftKey; if (eventInWidget(display, e)) { if (!webkit) { // Briefly turn off draggability, to allow widgets to do // normal dragging things. display.scroller.draggable = false; setTimeout(function () { return display.scroller.draggable = true; }, 100); } return } if (clickInGutter(cm, e)) { return } var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; window.focus(); // #3261: make sure, that we're not starting a second selection if (button == 1 && cm.state.selectingText) { cm.state.selectingText(e); } if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } if (button == 1) { if (pos) { leftButtonDown(cm, pos, repeat, e); } else if (e_target(e) == display.scroller) { e_preventDefault(e); } } else if (button == 2) { if (pos) { extendSelection(cm.doc, pos); } setTimeout(function () { return display.input.focus(); }, 20); } else if (button == 3) { if (captureRightClick) { cm.display.input.onContextMenu(e); } else { delayBlurEvent(cm); } } } function handleMappedButton(cm, button, pos, repeat, event) { var name = "Click"; if (repeat == "double") { name = "Double" + name; } else if (repeat == "triple") { name = "Triple" + name; } name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { if (typeof bound == "string") { bound = commands[bound]; } if (!bound) { return false } var done = false; try { if (cm.isReadOnly()) { cm.state.suppressEdits = true; } done = bound(cm, pos) != Pass; } finally { cm.state.suppressEdits = false; } return done }) } function configureMouse(cm, repeat, event) { var option = cm.getOption("configureMouse"); var value = option ? option(cm, repeat, event) : {}; if (value.unit == null) { var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; } if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } return value } function leftButtonDown(cm, pos, repeat, event) { if (ie) { setTimeout(bind(ensureFocus, cm), 0); } else { cm.curOp.focus = activeElt(); } var behavior = configureMouse(cm, repeat, event); var sel = cm.doc.sel, contained; if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) { leftButtonStartDrag(cm, event, pos, behavior); } else { leftButtonSelect(cm, event, pos, behavior); } } // Start a text drag. When it ends, see if any dragging actually // happen, and treat as a click if it didn't. function leftButtonStartDrag(cm, event, pos, behavior) { var display = cm.display, moved = false; var dragEnd = operation(cm, function (e) { if (webkit) { display.scroller.draggable = false; } cm.state.draggingText = false; off(display.wrapper.ownerDocument, "mouseup", dragEnd); off(display.wrapper.ownerDocument, "mousemove", mouseMove); off(display.scroller, "dragstart", dragStart); off(display.scroller, "drop", dragEnd); if (!moved) { e_preventDefault(e); if (!behavior.addNew) { extendSelection(cm.doc, pos, null, null, behavior.extend); } // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) if (webkit || ie && ie_version == 9) { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); } else { display.input.focus(); } } }); var mouseMove = function(e2) { moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; }; var dragStart = function () { return moved = true; }; // Let the drag handler handle this. if (webkit) { display.scroller.draggable = true; } cm.state.draggingText = dragEnd; dragEnd.copy = !behavior.moveOnDrag; // IE's approach to draggable if (display.scroller.dragDrop) { display.scroller.dragDrop(); } on(display.wrapper.ownerDocument, "mouseup", dragEnd); on(display.wrapper.ownerDocument, "mousemove", mouseMove); on(display.scroller, "dragstart", dragStart); on(display.scroller, "drop", dragEnd); delayBlurEvent(cm); setTimeout(function () { return display.input.focus(); }, 20); } function rangeForUnit(cm, pos, unit) { if (unit == "char") { return new Range(pos, pos) } if (unit == "word") { return cm.findWordAt(pos) } if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } var result = unit(cm, pos); return new Range(result.from, result.to) } // Normal selection, as opposed to text dragging. function leftButtonSelect(cm, event, start, behavior) { var display = cm.display, doc = cm.doc; e_preventDefault(event); var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; if (behavior.addNew && !behavior.extend) { ourIndex = doc.sel.contains(start); if (ourIndex > -1) { ourRange = ranges[ourIndex]; } else { ourRange = new Range(start, start); } } else { ourRange = doc.sel.primary(); ourIndex = doc.sel.primIndex; } if (behavior.unit == "rectangle") { if (!behavior.addNew) { ourRange = new Range(start, start); } start = posFromMouse(cm, event, true, true); ourIndex = -1; } else { var range$$1 = rangeForUnit(cm, start, behavior.unit); if (behavior.extend) { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } else { ourRange = range$$1; } } if (!behavior.addNew) { ourIndex = 0; setSelection(doc, new Selection([ourRange], 0), sel_mouse); startSel = doc.sel; } else if (ourIndex == -1) { ourIndex = ranges.length; setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), {scroll: false, origin: "*mouse"}); } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), {scroll: false, origin: "*mouse"}); startSel = doc.sel; } else { replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); } var lastPos = start; function extendTo(pos) { if (cmp(lastPos, pos) == 0) { return } lastPos = pos; if (behavior.unit == "rectangle") { var ranges = [], tabSize = cm.options.tabSize; var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); if (left == right) { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } else if (text.length > leftPos) { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } } if (!ranges.length) { ranges.push(new Range(start, start)); } setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), {origin: "*mouse", scroll: false}); cm.scrollIntoView(pos); } else { var oldRange = ourRange; var range$$1 = rangeForUnit(cm, pos, behavior.unit); var anchor = oldRange.anchor, head; if (cmp(range$$1.anchor, anchor) > 0) { head = range$$1.head; anchor = minPos(oldRange.from(), range$$1.anchor); } else { head = range$$1.anchor; anchor = maxPos(oldRange.to(), range$$1.head); } var ranges$1 = startSel.ranges.slice(0); ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); } } var editorSize = display.wrapper.getBoundingClientRect(); // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). var counter = 0; function extend(e) { var curCount = ++counter; var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); if (!cur) { return } if (cmp(cur, lastPos) != 0) { cm.curOp.focus = activeElt(); extendTo(cur); var visible = visibleLines(display, doc); if (cur.line >= visible.to || cur.line < visible.from) { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } } else { var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; if (outside) { setTimeout(operation(cm, function () { if (counter != curCount) { return } display.scroller.scrollTop += outside; extend(e); }), 50); } } } function done(e) { cm.state.selectingText = false; counter = Infinity; e_preventDefault(e); display.input.focus(); off(display.wrapper.ownerDocument, "mousemove", move); off(display.wrapper.ownerDocument, "mouseup", up); doc.history.lastSelOrigin = null; } var move = operation(cm, function (e) { if (e.buttons === 0 || !e_button(e)) { done(e); } else { extend(e); } }); var up = operation(cm, done); cm.state.selectingText = up; on(display.wrapper.ownerDocument, "mousemove", move); on(display.wrapper.ownerDocument, "mouseup", up); } // Used when mouse-selecting to adjust the anchor to the proper side // of a bidi jump depending on the visual position of the head. function bidiSimplify(cm, range$$1) { var anchor = range$$1.anchor; var head = range$$1.head; var anchorLine = getLine(cm.doc, anchor.line); if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 } var order = getOrder(anchorLine); if (!order) { return range$$1 } var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 } var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); if (boundary == 0 || boundary == order.length) { return range$$1 } // Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) var leftSide; if (head.line != anchor.line) { leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; } else { var headIndex = getBidiPartAt(order, head.ch, head.sticky); var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); if (headIndex == boundary - 1 || headIndex == boundary) { leftSide = dir < 0; } else { leftSide = dir > 0; } } var usePart = order[boundary + (leftSide ? -1 : 0)]; var from = leftSide == (usePart.level == 1); var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head) } // Determines whether an event happened in the gutter, and fires the // handlers for the corresponding event. function gutterEvent(cm, e, type, prevent) { var mX, mY; if (e.touches) { mX = e.touches[0].clientX; mY = e.touches[0].clientY; } else { try { mX = e.clientX; mY = e.clientY; } catch(e) { return false } } if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } if (prevent) { e_preventDefault(e); } var display = cm.display; var lineBox = display.lineDiv.getBoundingClientRect(); if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } mY -= lineBox.top - display.viewOffset; for (var i = 0; i < cm.options.gutters.length; ++i) { var g = display.gutters.childNodes[i]; if (g && g.getBoundingClientRect().right >= mX) { var line = lineAtHeight(cm.doc, mY); var gutter = cm.options.gutters[i]; signal(cm, type, cm, line, gutter, e); return e_defaultPrevented(e) } } } function clickInGutter(cm, e) { return gutterEvent(cm, e, "gutterClick", true) } // CONTEXT MENU HANDLING // To make the context menu work, we need to briefly unhide the // textarea (making it as unobtrusive as possible) to let the // right-click take effect on it. function onContextMenu(cm, e) { if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } if (signalDOMEvent(cm, e, "contextmenu")) { return } if (!captureRightClick) { cm.display.input.onContextMenu(e); } } function contextMenuInGutter(cm, e) { if (!hasHandler(cm, "gutterContextMenu")) { return false } return gutterEvent(cm, e, "gutterContextMenu", false) } function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); clearCaches(cm); } var Init = {toString: function(){return "CodeMirror.Init"}}; var defaults = {}; var optionHandlers = {}; function defineOptions(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt; if (handle) { optionHandlers[name] = notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } } CodeMirror.defineOption = option; // Passed to option handlers when there is no old value. CodeMirror.Init = Init; // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", function (cm, val) { return cm.setValue(val); }, true); option("mode", null, function (cm, val) { cm.doc.modeOption = val; loadMode(cm); }, true); option("indentUnit", 2, loadMode, true); option("indentWithTabs", false); option("smartIndent", true); option("tabSize", 4, function (cm) { resetModeState(cm); clearCaches(cm); regChange(cm); }, true); option("lineSeparator", null, function (cm, val) { cm.doc.lineSep = val; if (!val) { return } var newBreaks = [], lineNo = cm.doc.first; cm.doc.iter(function (line) { for (var pos = 0;;) { var found = line.text.indexOf(val, pos); if (found == -1) { break } pos = found + val.length; newBreaks.push(Pos(lineNo, found)); } lineNo++; }); for (var i = newBreaks.length - 1; i >= 0; i--) { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } }); option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); if (old != Init) { cm.refresh(); } }); option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); option("electricChars", true); option("inputStyle", mobile ? "contenteditable" : "textarea", function () { throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME }, true); option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); option("rtlMoveVisually", !windows); option("wholeLineUpdateBefore", true); option("theme", "default", function (cm) { themeChanged(cm); guttersChanged(cm); }, true); option("keyMap", "default", function (cm, val, old) { var next = getKeyMap(val); var prev = old != Init && getKeyMap(old); if (prev && prev.detach) { prev.detach(cm, next); } if (next.attach) { next.attach(cm, prev || null); } }); option("extraKeys", null); option("configureMouse", null); option("lineWrapping", false, wrappingChanged, true); option("gutters", [], function (cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("fixedGutter", true, function (cm, val) { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; cm.refresh(); }, true); option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); option("scrollbarStyle", "native", function (cm) { initScrollbars(cm); updateScrollbars(cm); cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); }, true); option("lineNumbers", false, function (cm) { setGuttersForLineNumbers(cm.options); guttersChanged(cm); }, true); option("firstLineNumber", 1, guttersChanged, true); option("lineNumberFormatter", function (integer) { return integer; }, guttersChanged, true); option("showCursorWhenSelecting", false, updateSelection, true); option("resetSelectionOnContextMenu", true); option("lineWiseCopyCut", true); option("pasteLinesPerSelection", true); option("selectionsMayTouch", false); option("readOnly", false, function (cm, val) { if (val == "nocursor") { onBlur(cm); cm.display.input.blur(); } cm.display.input.readOnlyChanged(val); }); option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); option("dragDrop", true, dragDropChanged); option("allowDropFileTypes", null); option("cursorBlinkRate", 530); option("cursorScrollMargin", 0); option("cursorHeight", 1, updateSelection, true); option("singleCursorHeightPerLine", true, updateSelection, true); option("workTime", 100); option("workDelay", 100); option("flattenSpans", true, resetModeState, true); option("addModeClass", false, resetModeState, true); option("pollInterval", 100); option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); option("historyEventDelay", 1250); option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); option("maxHighlightLength", 10000, resetModeState, true); option("moveInputWithCursor", true, function (cm, val) { if (!val) { cm.display.input.resetPosition(); } }); option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); option("autofocus", null); option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); option("phrases", null); } function guttersChanged(cm) { updateGutters(cm); regChange(cm); alignHorizontally(cm); } function dragDropChanged(cm, value, old) { var wasOn = old && old != Init; if (!value != !wasOn) { var funcs = cm.display.dragFunctions; var toggle = value ? on : off; toggle(cm.display.scroller, "dragstart", funcs.start); toggle(cm.display.scroller, "dragenter", funcs.enter); toggle(cm.display.scroller, "dragover", funcs.over); toggle(cm.display.scroller, "dragleave", funcs.leave); toggle(cm.display.scroller, "drop", funcs.drop); } } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap"); cm.display.sizer.style.minWidth = ""; cm.display.sizerWidth = null; } else { rmClass(cm.display.wrapper, "CodeMirror-wrap"); findMaxLine(cm); } estimateLineHeights(cm); regChange(cm); clearCaches(cm); setTimeout(function () { return updateScrollbars(cm); }, 100); } // A CodeMirror instance represents an editor. This is the object // that user code is usually dealing with. function CodeMirror(place, options) { var this$1 = this; if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } this.options = options = options ? copyObj(options) : {}; // Determine effective options based on given values and defaults. copyObj(defaults, options, false); setGuttersForLineNumbers(options); var doc = options.value; if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } else if (options.mode) { doc.modeOption = options.mode; } this.doc = doc; var input = new CodeMirror.inputStyles[options.inputStyle](this); var display = this.display = new Display(place, doc, input); display.wrapper.CodeMirror = this; updateGutters(this); themeChanged(this); if (options.lineWrapping) { this.display.wrapper.className += " CodeMirror-wrap"; } initScrollbars(this); this.state = { keyMaps: [], // stores maps added by addKeyMap overlays: [], // highlighting overlays, as added by addOverlay modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info overwrite: false, delayingBlurEvent: false, focused: false, suppressEdits: false, // used to disable editing during key handlers when in readOnly mode pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll selectingText: false, draggingText: false, highlight: new Delayed(), // stores highlight worker timeout keySeq: null, // Unfinished key sequence specialChars: null }; if (options.autofocus && !mobile) { display.input.focus(); } // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } registerEventHandlers(this); ensureGlobalHandlers(); startOperation(this); this.curOp.forceUpdate = true; attachDoc(this, doc); if ((options.autofocus && !mobile) || this.hasFocus()) { setTimeout(bind(onFocus, this), 20); } else { onBlur(this); } for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) { optionHandlers[opt](this$1, options[opt], Init); } } maybeUpdateLineNumberWidth(this); if (options.finishInit) { options.finishInit(this); } for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } endOperation(this); // Suppress optimizelegibility in Webkit, since it breaks text // measuring on line wrapping boundaries. if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") { display.lineDiv.style.textRendering = "auto"; } } // The default configuration options. CodeMirror.defaults = defaults; // Functions to run when options are changed. CodeMirror.optionHandlers = optionHandlers; // Attach the necessary event handlers when initializing the editor function registerEventHandlers(cm) { var d = cm.display; on(d.scroller, "mousedown", operation(cm, onMouseDown)); // Older IE's will not fire a second mousedown for a double click if (ie && ie_version < 11) { on(d.scroller, "dblclick", operation(cm, function (e) { if (signalDOMEvent(cm, e)) { return } var pos = posFromMouse(cm, e); if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } e_preventDefault(e); var word = cm.findWordAt(pos); extendSelection(cm.doc, word.anchor, word.head); })); } else { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } // Some browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for these browsers. on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); // Used to suppress mouse event handling when a touch happens var touchFinished, prevTouch = {end: 0}; function finishTouch() { if (d.activeTouch) { touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); prevTouch = d.activeTouch; prevTouch.end = +new Date; } } function isMouseLikeTouchEvent(e) { if (e.touches.length != 1) { return false } var touch = e.touches[0]; return touch.radiusX <= 1 && touch.radiusY <= 1 } function farAway(touch, other) { if (other.left == null) { return true } var dx = other.left - touch.left, dy = other.top - touch.top; return dx * dx + dy * dy > 20 * 20 } on(d.scroller, "touchstart", function (e) { if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { d.input.ensurePolled(); clearTimeout(touchFinished); var now = +new Date; d.activeTouch = {start: now, moved: false, prev: now - prevTouch.end <= 300 ? prevTouch : null}; if (e.touches.length == 1) { d.activeTouch.left = e.touches[0].pageX; d.activeTouch.top = e.touches[0].pageY; } } }); on(d.scroller, "touchmove", function () { if (d.activeTouch) { d.activeTouch.moved = true; } }); on(d.scroller, "touchend", function (e) { var touch = d.activeTouch; if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date - touch.start < 300) { var pos = cm.coordsChar(d.activeTouch, "page"), range; if (!touch.prev || farAway(touch, touch.prev)) // Single tap { range = new Range(pos, pos); } else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap { range = cm.findWordAt(pos); } else // Triple tap { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } cm.setSelection(range.anchor, range.head); cm.focus(); e_preventDefault(e); } finishTouch(); }); on(d.scroller, "touchcancel", finishTouch); // Sync scrolling between fake scrollbars and real scrollable // area, ensure viewport is updated when scrolling. on(d.scroller, "scroll", function () { if (d.scroller.clientHeight) { updateScrollTop(cm, d.scroller.scrollTop); setScrollLeft(cm, d.scroller.scrollLeft, true); signal(cm, "scroll", cm); } }); // Listen to wheel events in order to try and update the viewport on time. on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); d.dragFunctions = { enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, start: function (e) { return onDragStart(cm, e); }, drop: operation(cm, onDrop), leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} }; var inp = d.input.getField(); on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); on(inp, "keydown", operation(cm, onKeyDown)); on(inp, "keypress", operation(cm, onKeyPress)); on(inp, "focus", function (e) { return onFocus(cm, e); }); on(inp, "blur", function (e) { return onBlur(cm, e); }); } var initHooks = []; CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; // Indent the given line. The how parameter can be "smart", // "add"/null, "subtract", or "prev". When aggressive is false // (typically set to true for forced single-line indents), empty // lines are not indented, and places where the mode returns Pass // are left alone. function indentLine(cm, n, how, aggressive) { var doc = cm.doc, state; if (how == null) { how = "add"; } if (how == "smart") { // Fall back to "prev" when the mode doesn't have an indentation // method. if (!doc.mode.indent) { how = "prev"; } else { state = getContextBefore(cm, n).state; } } var tabSize = cm.options.tabSize; var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); if (line.stateAfter) { line.stateAfter = null; } var curSpaceString = line.text.match(/^\s*/)[0], indentation; if (!aggressive && !/\S/.test(line.text)) { indentation = 0; how = "not"; } else if (how == "smart") { indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); if (indentation == Pass || indentation > 150) { if (!aggressive) { return } how = "prev"; } } if (how == "prev") { if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } else { indentation = 0; } } else if (how == "add") { indentation = curSpace + cm.options.indentUnit; } else if (how == "subtract") { indentation = curSpace - cm.options.indentUnit; } else if (typeof how == "number") { indentation = curSpace + how; } indentation = Math.max(0, indentation); var indentString = "", pos = 0; if (cm.options.indentWithTabs) { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } if (pos < indentation) { indentString += spaceStr(indentation - pos); } if (indentString != curSpaceString) { replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); line.stateAfter = null; return true } else { // Ensure that, if the cursor was in the whitespace at the start // of the line, it is moved to the end of that space. for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { var range = doc.sel.ranges[i$1]; if (range.head.line == n && range.head.ch < curSpaceString.length) { var pos$1 = Pos(n, curSpaceString.length); replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); break } } } } // This will be set to a {lineWise: bool, text: [string]} object, so // that, when pasting, we know what kind of selections the copied // text was made out of. var lastCopied = null; function setLastCopied(newLastCopied) { lastCopied = newLastCopied; } function applyTextInput(cm, inserted, deleted, sel, origin) { var doc = cm.doc; cm.display.shift = false; if (!sel) { sel = doc.sel; } var paste = cm.state.pasteIncoming || origin == "paste"; var textLines = splitLinesAuto(inserted), multiPaste = null; // When pasting N lines into N selections, insert one line per selection if (paste && sel.ranges.length > 1) { if (lastCopied && lastCopied.text.join("\n") == inserted) { if (sel.ranges.length % lastCopied.text.length == 0) { multiPaste = []; for (var i = 0; i < lastCopied.text.length; i++) { multiPaste.push(doc.splitLines(lastCopied.text[i])); } } } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { multiPaste = map(textLines, function (l) { return [l]; }); } } var updateInput = cm.curOp.updateInput; // Normal behavior is to insert the new text into every selection for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { var range$$1 = sel.ranges[i$1]; var from = range$$1.from(), to = range$$1.to(); if (range$$1.empty()) { if (deleted && deleted > 0) // Handle deletion { from = Pos(from.line, from.ch - deleted); } else if (cm.state.overwrite && !paste) // Handle overwrite { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) { from = to = Pos(from.line, 0); } } var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; makeChange(cm.doc, changeEvent); signalLater(cm, "inputRead", cm, changeEvent); } if (inserted && !paste) { triggerElectric(cm, inserted); } ensureCursorVisible(cm); if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } cm.curOp.typing = true; cm.state.pasteIncoming = cm.state.cutIncoming = false; } function handlePaste(e, cm) { var pasted = e.clipboardData && e.clipboardData.getData("Text"); if (pasted) { e.preventDefault(); if (!cm.isReadOnly() && !cm.options.disableInput) { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } return true } } function triggerElectric(cm, inserted) { // When an 'electric' character is inserted, immediately trigger a reindent if (!cm.options.electricChars || !cm.options.smartIndent) { return } var sel = cm.doc.sel; for (var i = sel.ranges.length - 1; i >= 0; i--) { var range$$1 = sel.ranges[i]; if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } var mode = cm.getModeAt(range$$1.head); var indented = false; if (mode.electricChars) { for (var j = 0; j < mode.electricChars.length; j++) { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { indented = indentLine(cm, range$$1.head.line, "smart"); break } } } else if (mode.electricInput) { if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) { indented = indentLine(cm, range$$1.head.line, "smart"); } } if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } } } function copyableRanges(cm) { var text = [], ranges = []; for (var i = 0; i < cm.doc.sel.ranges.length; i++) { var line = cm.doc.sel.ranges[i].head.line; var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; ranges.push(lineRange); text.push(cm.getRange(lineRange.anchor, lineRange.head)); } return {text: text, ranges: ranges} } function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { field.setAttribute("autocorrect", !!autocorrect); field.setAttribute("autocapitalize", !!autocapitalize); field.setAttribute("spellcheck", !!spellcheck); } function hiddenTextarea() { var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); // The textarea is kept positioned near the cursor to prevent the // fact that it'll be scrolled into view on input from scrolling // our fake cursor out of view. On webkit, when wrap=off, paste is // very slow. So make the area wide instead. if (webkit) { te.style.width = "1000px"; } else { te.setAttribute("wrap", "off"); } // If border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) { te.style.border = "1px solid black"; } disableBrowserMagic(te); return div } // The publicly visible API. Note that methodOp(f) means // 'wrap f in an operation, performed on its `this` parameter'. // This is not the complete set of editor methods. Most of the // methods defined on the Doc type are also injected into // CodeMirror.prototype, for backwards compatibility and // convenience. function addEditorMethods(CodeMirror) { var optionHandlers = CodeMirror.optionHandlers; var helpers = CodeMirror.helpers = {}; CodeMirror.prototype = { constructor: CodeMirror, focus: function(){window.focus(); this.display.input.focus();}, setOption: function(option, value) { var options = this.options, old = options[option]; if (options[option] == value && option != "mode") { return } options[option] = value; if (optionHandlers.hasOwnProperty(option)) { operation(this, optionHandlers[option])(this, value, old); } signal(this, "optionChange", this, option); }, getOption: function(option) {return this.options[option]}, getDoc: function() {return this.doc}, addKeyMap: function(map$$1, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); }, removeKeyMap: function(map$$1) { var maps = this.state.keyMaps; for (var i = 0; i < maps.length; ++i) { if (maps[i] == map$$1 || maps[i].name == map$$1) { maps.splice(i, 1); return true } } }, addOverlay: methodOp(function(spec, options) { var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); if (mode.startState) { throw new Error("Overlays may not be stateful.") } insertSorted(this.state.overlays, {mode: mode, modeSpec: spec, opaque: options && options.opaque, priority: (options && options.priority) || 0}, function (overlay) { return overlay.priority; }); this.state.modeGen++; regChange(this); }), removeOverlay: methodOp(function(spec) { var this$1 = this; var overlays = this.state.overlays; for (var i = 0; i < overlays.length; ++i) { var cur = overlays[i].modeSpec; if (cur == spec || typeof spec == "string" && cur.name == spec) { overlays.splice(i, 1); this$1.state.modeGen++; regChange(this$1); return } } }), indentLine: methodOp(function(n, dir, aggressive) { if (typeof dir != "string" && typeof dir != "number") { if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } else { dir = dir ? "add" : "subtract"; } } if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } }), indentSelection: methodOp(function(how) { var this$1 = this; var ranges = this.doc.sel.ranges, end = -1; for (var i = 0; i < ranges.length; i++) { var range$$1 = ranges[i]; if (!range$$1.empty()) { var from = range$$1.from(), to = range$$1.to(); var start = Math.max(end, from.line); end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; for (var j = start; j < end; ++j) { indentLine(this$1, j, how); } var newRanges = this$1.doc.sel.ranges; if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } } else if (range$$1.head.line > end) { indentLine(this$1, range$$1.head.line, how, true); end = range$$1.head.line; if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } } } }), // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(pos, precise) { return takeToken(this, pos, precise) }, getLineTokens: function(line, precise) { return takeToken(this, Pos(line), precise, true) }, getTokenTypeAt: function(pos) { pos = clipPos(this.doc, pos); var styles = getLineStyles(this, getLine(this.doc, pos.line)); var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; var type; if (ch == 0) { type = styles[2]; } else { for (;;) { var mid = (before + after) >> 1; if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } else { type = styles[mid * 2 + 2]; break } } } var cut = type ? type.indexOf("overlay ") : -1; return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) }, getModeAt: function(pos) { var mode = this.doc.mode; if (!mode.innerMode) { return mode } return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode }, getHelper: function(pos, type) { return this.getHelpers(pos, type)[0] }, getHelpers: function(pos, type) { var this$1 = this; var found = []; if (!helpers.hasOwnProperty(type)) { return found } var help = helpers[type], mode = this.getModeAt(pos); if (typeof mode[type] == "string") { if (help[mode[type]]) { found.push(help[mode[type]]); } } else if (mode[type]) { for (var i = 0; i < mode[type].length; i++) { var val = help[mode[type][i]]; if (val) { found.push(val); } } } else if (mode.helperType && help[mode.helperType]) { found.push(help[mode.helperType]); } else if (help[mode.name]) { found.push(help[mode.name]); } for (var i$1 = 0; i$1 < help._global.length; i$1++) { var cur = help._global[i$1]; if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) { found.push(cur.val); } } return found }, getStateAfter: function(line, precise) { var doc = this.doc; line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); return getContextBefore(this, line + 1, precise).state }, cursorCoords: function(start, mode) { var pos, range$$1 = this.doc.sel.primary(); if (start == null) { pos = range$$1.head; } else if (typeof start == "object") { pos = clipPos(this.doc, start); } else { pos = start ? range$$1.from() : range$$1.to(); } return cursorCoords(this, pos, mode || "page") }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.doc, pos), mode || "page") }, coordsChar: function(coords, mode) { coords = fromCoordSystem(this, coords, mode || "page"); return coordsChar(this, coords.left, coords.top) }, lineAtHeight: function(height, mode) { height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; return lineAtHeight(this.doc, height + this.display.viewOffset) }, heightAtLine: function(line, mode, includeWidgets) { var end = false, lineObj; if (typeof line == "number") { var last = this.doc.first + this.doc.size - 1; if (line < this.doc.first) { line = this.doc.first; } else if (line > last) { line = last; end = true; } lineObj = getLine(this.doc, line); } else { lineObj = line; } return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0) }, defaultTextHeight: function() { return textHeight(this.display) }, defaultCharWidth: function() { return charWidth(this.display) }, getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, addWidget: function(pos, node, scroll, vert, horiz) { var display = this.display; pos = cursorCoords(this, clipPos(this.doc, pos)); var top = pos.bottom, left = pos.left; node.style.position = "absolute"; node.setAttribute("cm-ignore-events", "true"); this.display.input.setUneditable(node); display.sizer.appendChild(node); if (vert == "over") { top = pos.top; } else if (vert == "above" || vert == "near") { var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) { top = pos.top - node.offsetHeight; } else if (pos.bottom + node.offsetHeight <= vspace) { top = pos.bottom; } if (left + node.offsetWidth > hspace) { left = hspace - node.offsetWidth; } } node.style.top = top + "px"; node.style.left = node.style.right = ""; if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth; node.style.right = "0px"; } else { if (horiz == "left") { left = 0; } else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } node.style.left = left + "px"; } if (scroll) { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } }, triggerOnKeyDown: methodOp(onKeyDown), triggerOnKeyPress: methodOp(onKeyPress), triggerOnKeyUp: onKeyUp, triggerOnMouseDown: methodOp(onMouseDown), execCommand: function(cmd) { if (commands.hasOwnProperty(cmd)) { return commands[cmd].call(null, this) } }, triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), findPosH: function(from, amount, unit, visually) { var this$1 = this; var dir = 1; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { cur = findPosH(this$1.doc, cur, dir, unit, visually); if (cur.hitSide) { break } } return cur }, moveH: methodOp(function(dir, unit) { var this$1 = this; this.extendSelectionsBy(function (range$$1) { if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } else { return dir < 0 ? range$$1.from() : range$$1.to() } }, sel_move); }), deleteH: methodOp(function(dir, unit) { var sel = this.doc.sel, doc = this.doc; if (sel.somethingSelected()) { doc.replaceSelection("", null, "+delete"); } else { deleteNearSelection(this, function (range$$1) { var other = findPosH(doc, range$$1.head, dir, unit, false); return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} }); } }), findPosV: function(from, amount, unit, goalColumn) { var this$1 = this; var dir = 1, x = goalColumn; if (amount < 0) { dir = -1; amount = -amount; } var cur = clipPos(this.doc, from); for (var i = 0; i < amount; ++i) { var coords = cursorCoords(this$1, cur, "div"); if (x == null) { x = coords.left; } else { coords.left = x; } cur = findPosV(this$1, coords, dir, unit); if (cur.hitSide) { break } } return cur }, moveV: methodOp(function(dir, unit) { var this$1 = this; var doc = this.doc, goals = []; var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); doc.extendSelectionsBy(function (range$$1) { if (collapse) { return dir < 0 ? range$$1.from() : range$$1.to() } var headPos = cursorCoords(this$1, range$$1.head, "div"); if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } goals.push(headPos.left); var pos = findPosV(this$1, headPos, dir, unit); if (unit == "page" && range$$1 == doc.sel.primary()) { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } return pos }, sel_move); if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) { doc.sel.ranges[i].goalColumn = goals[i]; } } }), // Find the word at the given position (as returned by coordsChar). findWordAt: function(pos) { var doc = this.doc, line = getLine(doc, pos.line).text; var start = pos.ch, end = pos.ch; if (line) { var helper = this.getHelper(pos, "wordChars"); if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } var startChar = line.charAt(start); var check = isWordChar(startChar, helper) ? function (ch) { return isWordChar(ch, helper); } : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; while (start > 0 && check(line.charAt(start - 1))) { --start; } while (end < line.length && check(line.charAt(end))) { ++end; } } return new Range(Pos(pos.line, start), Pos(pos.line, end)) }, toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) { return } if (this.state.overwrite = !this.state.overwrite) { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } else { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } signal(this, "overwriteToggle", this, this.state.overwrite); }, hasFocus: function() { return this.display.input.getField() == activeElt() }, isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), getScrollInfo: function() { var scroller = this.display.scroller; return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, clientHeight: displayHeight(this), clientWidth: displayWidth(this)} }, scrollIntoView: methodOp(function(range$$1, margin) { if (range$$1 == null) { range$$1 = {from: this.doc.sel.primary().head, to: null}; if (margin == null) { margin = this.options.cursorScrollMargin; } } else if (typeof range$$1 == "number") { range$$1 = {from: Pos(range$$1, 0), to: null}; } else if (range$$1.from == null) { range$$1 = {from: range$$1, to: null}; } if (!range$$1.to) { range$$1.to = range$$1.from; } range$$1.margin = margin || 0; if (range$$1.from.line != null) { scrollToRange(this, range$$1); } else { scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); } }), setSize: methodOp(function(width, height) { var this$1 = this; var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; if (width != null) { this.display.wrapper.style.width = interpret(width); } if (height != null) { this.display.wrapper.style.height = interpret(height); } if (this.options.lineWrapping) { clearLineMeasurementCache(this); } var lineNo$$1 = this.display.viewFrom; this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } ++lineNo$$1; }); this.curOp.forceUpdate = true; signal(this, "refresh", this); }), operation: function(f){return runInOp(this, f)}, startOperation: function(){return startOperation(this)}, endOperation: function(){return endOperation(this)}, refresh: methodOp(function() { var oldHeight = this.display.cachedTextHeight; regChange(this); this.curOp.forceUpdate = true; clearCaches(this); scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); updateGutterSpace(this); if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) { estimateLineHeights(this); } signal(this, "refresh", this); }), swapDoc: methodOp(function(doc) { var old = this.doc; old.cm = null; attachDoc(this, doc); clearCaches(this); this.display.input.reset(); scrollToCoords(this, doc.scrollLeft, doc.scrollTop); this.curOp.forceScroll = true; signalLater(this, "swapDoc", this, old); return old }), phrase: function(phraseText) { var phrases = this.options.phrases; return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText }, getInputField: function(){return this.display.input.getField()}, getWrapperElement: function(){return this.display.wrapper}, getScrollerElement: function(){return this.display.scroller}, getGutterElement: function(){return this.display.gutters} }; eventMixin(CodeMirror); CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } helpers[type][name] = value; }; CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { CodeMirror.registerHelper(type, name, value); helpers[type]._global.push({pred: predicate, val: value}); }; } // Used for horizontal relative motion. Dir is -1 or 1 (left or // right), unit can be "char", "column" (like char, but doesn't // cross line boundaries), "word" (across next word), or "group" (to // the start of next group of word or non-word-non-whitespace // chars). The visually param controls whether, in right-to-left // text, direction 1 means to move towards the next index in the // string, or towards the character to the right of the current // position. The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosH(doc, pos, dir, unit, visually) { var oldPos = pos; var origDir = dir; var lineObj = getLine(doc, pos.line); function findNextLine() { var l = pos.line + dir; if (l < doc.first || l >= doc.first + doc.size) { return false } pos = new Pos(l, pos.ch, pos.sticky); return lineObj = getLine(doc, l) } function moveOnce(boundToLine) { var next; if (visually) { next = moveVisually(doc.cm, lineObj, pos, dir); } else { next = moveLogically(lineObj, pos, dir); } if (next == null) { if (!boundToLine && findNextLine()) { pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir); } else { return false } } else { pos = next; } return true } if (unit == "char") { moveOnce(); } else if (unit == "column") { moveOnce(true); } else if (unit == "word" || unit == "group") { var sawType = null, group = unit == "group"; var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); for (var first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) { break } var cur = lineObj.text.charAt(pos.ch) || "\n"; var type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p"; if (group && !first && !type) { type = "s"; } if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} break } if (type) { sawType = type; } if (dir > 0 && !moveOnce(!first)) { break } } } var result = skipAtomic(doc, pos, oldPos, origDir, true); if (equalCursorPos(oldPos, result)) { result.hitSide = true; } return result } // For relative vertical movement. Dir may be -1 or 1. Unit can be // "page" or "line". The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosV(cm, pos, dir, unit) { var doc = cm.doc, x = pos.left, y; if (unit == "page") { var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3; } var target; for (;;) { target = coordsChar(cm, x, y); if (!target.outside) { break } if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } y += dir * 5; } return target } // CONTENTEDITABLE INPUT STYLE var ContentEditableInput = function(cm) { this.cm = cm; this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; this.polling = new Delayed(); this.composing = null; this.gracePeriod = false; this.readDOMTimeout = null; }; ContentEditableInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = input.cm; var div = input.div = display.lineDiv; disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); on(div, "paste", function (e) { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } // IE doesn't fire input events, so we schedule a read for the pasted content in this way if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } }); on(div, "compositionstart", function (e) { this$1.composing = {data: e.data, done: false}; }); on(div, "compositionupdate", function (e) { if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } }); on(div, "compositionend", function (e) { if (this$1.composing) { if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } this$1.composing.done = true; } }); on(div, "touchstart", function () { return input.forceCompositionEnd(); }); on(div, "input", function () { if (!this$1.composing) { this$1.readFromDOMSoon(); } }); function onCopyCut(e) { if (signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.operation(function () { cm.setSelections(ranges.ranges, 0, sel_dontScroll); cm.replaceSelection("", null, "cut"); }); } } if (e.clipboardData) { e.clipboardData.clearData(); var content = lastCopied.text.join("\n"); // iOS exposes the clipboard API, but seems to discard content inserted into it e.clipboardData.setData("Text", content); if (e.clipboardData.getData("Text") == content) { e.preventDefault(); return } } // Old-fashioned briefly-focus-a-textarea hack var kludge = hiddenTextarea(), te = kludge.firstChild; cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); te.value = lastCopied.text.join("\n"); var hadFocus = document.activeElement; selectInput(te); setTimeout(function () { cm.display.lineSpace.removeChild(kludge); hadFocus.focus(); if (hadFocus == div) { input.showPrimarySelection(); } }, 50); } on(div, "copy", onCopyCut); on(div, "cut", onCopyCut); }; ContentEditableInput.prototype.prepareSelection = function () { var result = prepareSelection(this.cm, false); result.focus = this.cm.state.focused; return result }; ContentEditableInput.prototype.showSelection = function (info, takeFocus) { if (!info || !this.cm.display.view.length) { return } if (info.focus || takeFocus) { this.showPrimarySelection(); } this.showMultipleSelections(info); }; ContentEditableInput.prototype.getSelection = function () { return this.cm.display.wrapper.ownerDocument.getSelection() }; ContentEditableInput.prototype.showPrimarySelection = function () { var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); var from = prim.from(), to = prim.to(); if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { sel.removeAllRanges(); return } var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) { return } var view = cm.display.view; var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || {node: view[0].measure.map[2], offset: 0}; var end = to.line < cm.display.viewTo && posToDOM(cm, to); if (!end) { var measure = view[view.length - 1].measure; var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; } if (!start || !end) { sel.removeAllRanges(); return } var old = sel.rangeCount && sel.getRangeAt(0), rng; try { rng = range(start.node, start.offset, end.offset, end.node); } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible if (rng) { if (!gecko && cm.state.focused) { sel.collapse(start.node, start.offset); if (!rng.collapsed) { sel.removeAllRanges(); sel.addRange(rng); } } else { sel.removeAllRanges(); sel.addRange(rng); } if (old && sel.anchorNode == null) { sel.addRange(old); } else if (gecko) { this.startGracePeriod(); } } this.rememberSelection(); }; ContentEditableInput.prototype.startGracePeriod = function () { var this$1 = this; clearTimeout(this.gracePeriod); this.gracePeriod = setTimeout(function () { this$1.gracePeriod = false; if (this$1.selectionChanged()) { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } }, 20); }; ContentEditableInput.prototype.showMultipleSelections = function (info) { removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); }; ContentEditableInput.prototype.rememberSelection = function () { var sel = this.getSelection(); this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; }; ContentEditableInput.prototype.selectionInEditor = function () { var sel = this.getSelection(); if (!sel.rangeCount) { return false } var node = sel.getRangeAt(0).commonAncestorContainer; return contains(this.div, node) }; ContentEditableInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor") { if (!this.selectionInEditor()) { this.showSelection(this.prepareSelection(), true); } this.div.focus(); } }; ContentEditableInput.prototype.blur = function () { this.div.blur(); }; ContentEditableInput.prototype.getField = function () { return this.div }; ContentEditableInput.prototype.supportsTouch = function () { return true }; ContentEditableInput.prototype.receivedFocus = function () { var input = this; if (this.selectionInEditor()) { this.pollSelection(); } else { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } function poll() { if (input.cm.state.focused) { input.pollSelection(); input.polling.set(input.cm.options.pollInterval, poll); } } this.polling.set(this.cm.options.pollInterval, poll); }; ContentEditableInput.prototype.selectionChanged = function () { var sel = this.getSelection(); return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset }; ContentEditableInput.prototype.pollSelection = function () { if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } var sel = this.getSelection(), cm = this.cm; // On Android Chrome (version 56, at least), backspacing into an // uneditable block element will put the cursor in that element, // and then, because it's not editable, hide the virtual keyboard. // Because Android doesn't allow us to actually detect backspace // presses in a sane way, this code checks for when that happens // and simulates a backspace press in this case. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); this.blur(); this.focus(); return } if (this.composing) { return } this.rememberSelection(); var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); var head = domToPos(cm, sel.focusNode, sel.focusOffset); if (anchor && head) { runInOp(cm, function () { setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } }); } }; ContentEditableInput.prototype.pollContent = function () { if (this.readDOMTimeout != null) { clearTimeout(this.readDOMTimeout); this.readDOMTimeout = null; } var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); var from = sel.from(), to = sel.to(); if (from.ch == 0 && from.line > cm.firstLine()) { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) { to = Pos(to.line + 1, 0); } if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } var fromIndex, fromLine, fromNode; if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { fromLine = lineNo(display.view[0].line); fromNode = display.view[0].node; } else { fromLine = lineNo(display.view[fromIndex].line); fromNode = display.view[fromIndex - 1].node.nextSibling; } var toIndex = findViewIndex(cm, to.line); var toLine, toNode; if (toIndex == display.view.length - 1) { toLine = display.viewTo - 1; toNode = display.lineDiv.lastChild; } else { toLine = lineNo(display.view[toIndex + 1].line) - 1; toNode = display.view[toIndex + 1].node.previousSibling; } if (!fromNode) { return false } var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); while (newText.length > 1 && oldText.length > 1) { if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } else { break } } var cutFront = 0, cutEnd = 0; var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) { ++cutFront; } var newBot = lst(newText), oldBot = lst(oldText); var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)); while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { ++cutEnd; } // Try to move start of change to start of selection if ambiguous if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { cutFront--; cutEnd++; } } newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); var chFrom = Pos(fromLine, cutFront); var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { replaceRange(cm.doc, newText, chFrom, chTo, "+input"); return true } }; ContentEditableInput.prototype.ensurePolled = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.reset = function () { this.forceCompositionEnd(); }; ContentEditableInput.prototype.forceCompositionEnd = function () { if (!this.composing) { return } clearTimeout(this.readDOMTimeout); this.composing = null; this.updateFromDOM(); this.div.blur(); this.div.focus(); }; ContentEditableInput.prototype.readFromDOMSoon = function () { var this$1 = this; if (this.readDOMTimeout != null) { return } this.readDOMTimeout = setTimeout(function () { this$1.readDOMTimeout = null; if (this$1.composing) { if (this$1.composing.done) { this$1.composing = null; } else { return } } this$1.updateFromDOM(); }, 80); }; ContentEditableInput.prototype.updateFromDOM = function () { var this$1 = this; if (this.cm.isReadOnly() || !this.pollContent()) { runInOp(this.cm, function () { return regChange(this$1.cm); }); } }; ContentEditableInput.prototype.setUneditable = function (node) { node.contentEditable = "false"; }; ContentEditableInput.prototype.onKeyPress = function (e) { if (e.charCode == 0 || this.composing) { return } e.preventDefault(); if (!this.cm.isReadOnly()) { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } }; ContentEditableInput.prototype.readOnlyChanged = function (val) { this.div.contentEditable = String(val != "nocursor"); }; ContentEditableInput.prototype.onContextMenu = function () {}; ContentEditableInput.prototype.resetPosition = function () {}; ContentEditableInput.prototype.needsContentAttribute = true; function posToDOM(cm, pos) { var view = findViewForLine(cm, pos.line); if (!view || view.hidden) { return null } var line = getLine(cm.doc, pos.line); var info = mapFromLineView(view, line, pos.line); var order = getOrder(line, cm.doc.direction), side = "left"; if (order) { var partPos = getBidiPartAt(order, pos.ch); side = partPos % 2 ? "right" : "left"; } var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); result.offset = result.collapse == "right" ? result.end : result.start; return result } function isInGutter(node) { for (var scan = node; scan; scan = scan.parentNode) { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } return false } function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } function domTextBetween(cm, from, to, fromLine, toLine) { var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; function recognizeMarker(id) { return function (marker) { return marker.id == id; } } function close() { if (closing) { text += lineSep; if (extraLinebreak) { text += lineSep; } closing = extraLinebreak = false; } } function addText(str) { if (str) { close(); text += str; } } function walk(node) { if (node.nodeType == 1) { var cmText = node.getAttribute("cm-text"); if (cmText) { addText(cmText); return } var markerID = node.getAttribute("cm-marker"), range$$1; if (markerID) { var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); if (found.length && (range$$1 = found[0].find(0))) { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } return } if (node.getAttribute("contenteditable") == "false") { return } var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } if (isBlock) { close(); } for (var i = 0; i < node.childNodes.length; i++) { walk(node.childNodes[i]); } if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } if (isBlock) { closing = true; } } else if (node.nodeType == 3) { addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); } } for (;;) { walk(from); if (from == to) { break } from = from.nextSibling; extraLinebreak = false; } return text } function domToPos(cm, node, offset) { var lineNode; if (node == cm.display.lineDiv) { lineNode = cm.display.lineDiv.childNodes[offset]; if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } node = null; offset = 0; } else { for (lineNode = node;; lineNode = lineNode.parentNode) { if (!lineNode || lineNode == cm.display.lineDiv) { return null } if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } } } for (var i = 0; i < cm.display.view.length; i++) { var lineView = cm.display.view[i]; if (lineView.node == lineNode) { return locateNodeInLineView(lineView, node, offset) } } } function locateNodeInLineView(lineView, node, offset) { var wrapper = lineView.text.firstChild, bad = false; if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } if (node == wrapper) { bad = true; node = wrapper.childNodes[offset]; offset = 0; if (!node) { var line = lineView.rest ? lst(lineView.rest) : lineView.line; return badPos(Pos(lineNo(line), line.text.length), bad) } } var textNode = node.nodeType == 3 ? node : null, topNode = node; if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { textNode = node.firstChild; if (offset) { offset = textNode.nodeValue.length; } } while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } var measure = lineView.measure, maps = measure.maps; function find(textNode, topNode, offset) { for (var i = -1; i < (maps ? maps.length : 0); i++) { var map$$1 = i < 0 ? measure.map : maps[i]; for (var j = 0; j < map$$1.length; j += 3) { var curNode = map$$1[j + 2]; if (curNode == textNode || curNode == topNode) { var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); var ch = map$$1[j] + offset; if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } return Pos(line, ch) } } } } var found = find(textNode, topNode, offset); if (found) { return badPos(found, bad) } // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { found = find(after, after.firstChild, 0); if (found) { return badPos(Pos(found.line, found.ch - dist), bad) } else { dist += after.textContent.length; } } for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { found = find(before, before.firstChild, -1); if (found) { return badPos(Pos(found.line, found.ch + dist$1), bad) } else { dist$1 += before.textContent.length; } } } // TEXTAREA INPUT STYLE var TextareaInput = function(cm) { this.cm = cm; // See input.poll and input.reset this.prevInput = ""; // Flag that indicates whether we expect input to appear real soon // now (after some event like 'keypress' or 'input') and are // polling intensively. this.pollingFast = false; // Self-resetting timeout for the poller this.polling = new Delayed(); // Used to work around IE issue with selection being forgotten when focus moves away from textarea this.hasSelection = false; this.composing = null; }; TextareaInput.prototype.init = function (display) { var this$1 = this; var input = this, cm = this.cm; this.createField(display); var te = this.textarea; display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) if (ios) { te.style.width = "0px"; } on(te, "input", function () { if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } input.poll(); }); on(te, "paste", function (e) { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } cm.state.pasteIncoming = true; input.fastPoll(); }); function prepareCopyCut(e) { if (signalDOMEvent(cm, e)) { return } if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}); } else if (!cm.options.lineWiseCopyCut) { return } else { var ranges = copyableRanges(cm); setLastCopied({lineWise: true, text: ranges.text}); if (e.type == "cut") { cm.setSelections(ranges.ranges, null, sel_dontScroll); } else { input.prevInput = ""; te.value = ranges.text.join("\n"); selectInput(te); } } if (e.type == "cut") { cm.state.cutIncoming = true; } } on(te, "cut", prepareCopyCut); on(te, "copy", prepareCopyCut); on(display.scroller, "paste", function (e) { if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } cm.state.pasteIncoming = true; input.focus(); }); // Prevent normal selection in the editor (we handle our own) on(display.lineSpace, "selectstart", function (e) { if (!eventInWidget(display, e)) { e_preventDefault(e); } }); on(te, "compositionstart", function () { var start = cm.getCursor("from"); if (input.composing) { input.composing.range.clear(); } input.composing = { start: start, range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) }; }); on(te, "compositionend", function () { if (input.composing) { input.poll(); input.composing.range.clear(); input.composing = null; } }); }; TextareaInput.prototype.createField = function (_display) { // Wraps and hides input textarea this.wrapper = hiddenTextarea(); // The semihidden textarea that is focused when the editor is // focused, and receives input. this.textarea = this.wrapper.firstChild; }; TextareaInput.prototype.prepareSelection = function () { // Redraw the selection and/or cursor var cm = this.cm, display = cm.display, doc = cm.doc; var result = prepareSelection(cm); // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)); result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)); } return result }; TextareaInput.prototype.showSelection = function (drawn) { var cm = this.cm, display = cm.display; removeChildrenAndAdd(display.cursorDiv, drawn.cursors); removeChildrenAndAdd(display.selectionDiv, drawn.selection); if (drawn.teTop != null) { this.wrapper.style.top = drawn.teTop + "px"; this.wrapper.style.left = drawn.teLeft + "px"; } }; // Reset the input to correspond to the selection (or to be empty, // when not typing and nothing is selected) TextareaInput.prototype.reset = function (typing) { if (this.contextMenuPending || this.composing) { return } var cm = this.cm; if (cm.somethingSelected()) { this.prevInput = ""; var content = cm.getSelection(); this.textarea.value = content; if (cm.state.focused) { selectInput(this.textarea); } if (ie && ie_version >= 9) { this.hasSelection = content; } } else if (!typing) { this.prevInput = this.textarea.value = ""; if (ie && ie_version >= 9) { this.hasSelection = null; } } }; TextareaInput.prototype.getField = function () { return this.textarea }; TextareaInput.prototype.supportsTouch = function () { return false }; TextareaInput.prototype.focus = function () { if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { try { this.textarea.focus(); } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM } }; TextareaInput.prototype.blur = function () { this.textarea.blur(); }; TextareaInput.prototype.resetPosition = function () { this.wrapper.style.top = this.wrapper.style.left = 0; }; TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; // Poll for input changes, using the normal rate of polling. This // runs as long as the editor is focused. TextareaInput.prototype.slowPoll = function () { var this$1 = this; if (this.pollingFast) { return } this.polling.set(this.cm.options.pollInterval, function () { this$1.poll(); if (this$1.cm.state.focused) { this$1.slowPoll(); } }); }; // When an event has just come in that is likely to add or change // something in the input textarea, we poll faster, to ensure that // the change appears on the screen quickly. TextareaInput.prototype.fastPoll = function () { var missed = false, input = this; input.pollingFast = true; function p() { var changed = input.poll(); if (!changed && !missed) {missed = true; input.polling.set(60, p);} else {input.pollingFast = false; input.slowPoll();} } input.polling.set(20, p); }; // Read input from the textarea, and update the document to match. // When something is selected, it is present in the textarea, and // selected (unless it is huge, in which case a placeholder is // used). When nothing is selected, the cursor sits after previously // seen text (can be empty), which is stored in prevInput (we must // not reset the textarea when typing, because that breaks IME). TextareaInput.prototype.poll = function () { var this$1 = this; var cm = this.cm, input = this.textarea, prevInput = this.prevInput; // Since this is called a *lot*, try to bail out as cheaply as // possible when it is clear that nothing happened. hasSelection // will be the case when there is a lot of text in the textarea, // in which case reading its value would be expensive. if (this.contextMenuPending || !cm.state.focused || (hasSelection(input) && !prevInput && !this.composing) || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) { return false } var text = input.value; // If nothing changed, bail. if (text == prevInput && !cm.somethingSelected()) { return false } // Work around nonsensical selection resetting in IE9/10, and // inexplicable appearance of private area unicode characters on // some key combos in Mac (#2689). if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { cm.display.input.reset(); return false } if (cm.doc.sel == cm.display.selForContextMenu) { var first = text.charCodeAt(0); if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } } // Find the part of the input that is actually new var same = 0, l = Math.min(prevInput.length, text.length); while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } runInOp(cm, function () { applyTextInput(cm, text.slice(same), prevInput.length - same, null, this$1.composing ? "*compose" : null); // Don't leave long text in the textarea, since it makes further polling slow if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } else { this$1.prevInput = text; } if (this$1.composing) { this$1.composing.range.clear(); this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), {className: "CodeMirror-composing"}); } }); return true }; TextareaInput.prototype.ensurePolled = function () { if (this.pollingFast && this.poll()) { this.pollingFast = false; } }; TextareaInput.prototype.onKeyPress = function () { if (ie && ie_version >= 9) { this.hasSelection = null; } this.fastPoll(); }; TextareaInput.prototype.onContextMenu = function (e) { var input = this, cm = input.cm, display = cm.display, te = input.textarea; if (input.contextMenuPending) { input.contextMenuPending(); } var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; if (!pos || presto) { return } // Opera is difficult. // Reset the current text selection only if the click is done outside of the selection // and 'resetSelectionOnContextMenu' option is true. var reset = cm.options.resetSelectionOnContextMenu; if (reset && cm.doc.sel.contains(pos) == -1) { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); input.wrapper.style.cssText = "position: static"; 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);"; var oldScrollY; if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) display.input.focus(); if (webkit) { window.scrollTo(null, oldScrollY); } display.input.reset(); // Adds "Select all" to context menu in FF if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } input.contextMenuPending = rehide; display.selForContextMenu = cm.doc.sel; clearTimeout(display.detectingSelectAll); // Select-all will be greyed out if there's nothing to select, so // this adds a zero-width space so that we can later check whether // it got selected. function prepareSelectAllHack() { if (te.selectionStart != null) { var selected = cm.somethingSelected(); var extval = "\u200b" + (selected ? te.value : ""); te.value = "\u21da"; // Used to catch context-menu undo te.value = extval; input.prevInput = selected ? "" : "\u200b"; te.selectionStart = 1; te.selectionEnd = extval.length; // Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu = cm.doc.sel; } } function rehide() { if (input.contextMenuPending != rehide) { return } input.contextMenuPending = false; input.wrapper.style.cssText = oldWrapperCSS; te.style.cssText = oldCSS; if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } // Try to detect the user choosing select-all if (te.selectionStart != null) { if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } var i = 0, poll = function () { if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200b") { operation(cm, selectAll)(cm); } else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500); } else { display.selForContextMenu = null; display.input.reset(); } }; display.detectingSelectAll = setTimeout(poll, 200); } } if (ie && ie_version >= 9) { prepareSelectAllHack(); } if (captureRightClick) { e_stop(e); var mouseup = function () { off(window, "mouseup", mouseup); setTimeout(rehide, 20); }; on(window, "mouseup", mouseup); } else { setTimeout(rehide, 50); } }; TextareaInput.prototype.readOnlyChanged = function (val) { if (!val) { this.reset(); } this.textarea.disabled = val == "nocursor"; }; TextareaInput.prototype.setUneditable = function () {}; TextareaInput.prototype.needsContentAttribute = false; function fromTextArea(textarea, options) { options = options ? copyObj(options) : {}; options.value = textarea.value; if (!options.tabindex && textarea.tabIndex) { options.tabindex = textarea.tabIndex; } if (!options.placeholder && textarea.placeholder) { options.placeholder = textarea.placeholder; } // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { var hasFocus = activeElt(); options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body; } function save() {textarea.value = cm.getValue();} var realSubmit; if (textarea.form) { on(textarea.form, "submit", save); // Deplorable hack to make the submit method do the right thing. if (!options.leaveSubmitMethodAlone) { var form = textarea.form; realSubmit = form.submit; try { var wrappedSubmit = form.submit = function () { save(); form.submit = realSubmit; form.submit(); form.submit = wrappedSubmit; }; } catch(e) {} } } options.finishInit = function (cm) { cm.save = save; cm.getTextArea = function () { return textarea; }; cm.toTextArea = function () { cm.toTextArea = isNaN; // Prevent this from being ran twice save(); textarea.parentNode.removeChild(cm.getWrapperElement()); textarea.style.display = ""; if (textarea.form) { off(textarea.form, "submit", save); if (typeof textarea.form.submit == "function") { textarea.form.submit = realSubmit; } } }; }; textarea.style.display = "none"; var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, options); return cm } function addLegacyProps(CodeMirror) { CodeMirror.off = off; CodeMirror.on = on; CodeMirror.wheelEventPixels = wheelEventPixels; CodeMirror.Doc = Doc; CodeMirror.splitLines = splitLinesAuto; CodeMirror.countColumn = countColumn; CodeMirror.findColumn = findColumn; CodeMirror.isWordChar = isWordCharBasic; CodeMirror.Pass = Pass; CodeMirror.signal = signal; CodeMirror.Line = Line; CodeMirror.changeEnd = changeEnd; CodeMirror.scrollbarModel = scrollbarModel; CodeMirror.Pos = Pos; CodeMirror.cmpPos = cmp; CodeMirror.modes = modes; CodeMirror.mimeModes = mimeModes; CodeMirror.resolveMode = resolveMode; CodeMirror.getMode = getMode; CodeMirror.modeExtensions = modeExtensions; CodeMirror.extendMode = extendMode; CodeMirror.copyState = copyState; CodeMirror.startState = startState; CodeMirror.innerMode = innerMode; CodeMirror.commands = commands; CodeMirror.keyMap = keyMap; CodeMirror.keyName = keyName; CodeMirror.isModifierKey = isModifierKey; CodeMirror.lookupKey = lookupKey; CodeMirror.normalizeKeyMap = normalizeKeyMap; CodeMirror.StringStream = StringStream; CodeMirror.SharedTextMarker = SharedTextMarker; CodeMirror.TextMarker = TextMarker; CodeMirror.LineWidget = LineWidget; CodeMirror.e_preventDefault = e_preventDefault; CodeMirror.e_stopPropagation = e_stopPropagation; CodeMirror.e_stop = e_stop; CodeMirror.addClass = addClass; CodeMirror.contains = contains; CodeMirror.rmClass = rmClass; CodeMirror.keyNames = keyNames; } // EDITOR CONSTRUCTOR defineOptions(CodeMirror); addEditorMethods(CodeMirror); // Set up methods on CodeMirror's prototype to redirect to the editor's document. var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { CodeMirror.prototype[prop] = (function(method) { return function() {return method.apply(this.doc, arguments)} })(Doc.prototype[prop]); } } eventMixin(Doc); CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) CodeMirror.defineMode = function(name/*, mode, …*/) { if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } defineMode.apply(this, arguments); }; CodeMirror.defineMIME = defineMIME; // Minimal default mode. CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); CodeMirror.defineMIME("text/plain", "null"); // EXTENSIONS CodeMirror.defineExtension = function (name, func) { CodeMirror.prototype[name] = func; }; CodeMirror.defineDocExtension = function (name, func) { Doc.prototype[name] = func; }; CodeMirror.fromTextArea = fromTextArea; addLegacyProps(CodeMirror); CodeMirror.version = "5.43.0"; return CodeMirror; }))); ================================================ FILE: third_party/CodeMirror/mode/apl/apl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("apl", function() { var builtInOps = { ".": "innerProduct", "\\": "scan", "/": "reduce", "⌿": "reduce1Axis", "⍀": "scan1Axis", "¨": "each", "⍣": "power" }; var builtInFuncs = { "+": ["conjugate", "add"], "−": ["negate", "subtract"], "×": ["signOf", "multiply"], "÷": ["reciprocal", "divide"], "⌈": ["ceiling", "greaterOf"], "⌊": ["floor", "lesserOf"], "∣": ["absolute", "residue"], "⍳": ["indexGenerate", "indexOf"], "?": ["roll", "deal"], "⋆": ["exponentiate", "toThePowerOf"], "⍟": ["naturalLog", "logToTheBase"], "○": ["piTimes", "circularFuncs"], "!": ["factorial", "binomial"], "⌹": ["matrixInverse", "matrixDivide"], "<": [null, "lessThan"], "≤": [null, "lessThanOrEqual"], "=": [null, "equals"], ">": [null, "greaterThan"], "≥": [null, "greaterThanOrEqual"], "≠": [null, "notEqual"], "≡": ["depth", "match"], "≢": [null, "notMatch"], "∈": ["enlist", "membership"], "⍷": [null, "find"], "∪": ["unique", "union"], "∩": [null, "intersection"], "∼": ["not", "without"], "∨": [null, "or"], "∧": [null, "and"], "⍱": [null, "nor"], "⍲": [null, "nand"], "⍴": ["shapeOf", "reshape"], ",": ["ravel", "catenate"], "⍪": [null, "firstAxisCatenate"], "⌽": ["reverse", "rotate"], "⊖": ["axis1Reverse", "axis1Rotate"], "⍉": ["transpose", null], "↑": ["first", "take"], "↓": [null, "drop"], "⊂": ["enclose", "partitionWithAxis"], "⊃": ["diclose", "pick"], "⌷": [null, "index"], "⍋": ["gradeUp", null], "⍒": ["gradeDown", null], "⊤": ["encode", null], "⊥": ["decode", null], "⍕": ["format", "formatByExample"], "⍎": ["execute", null], "⊣": ["stop", "left"], "⊢": ["pass", "right"] }; var isOperator = /[\.\/⌿⍀¨⍣]/; var isNiladic = /⍬/; var isFunction = /[\+−×÷⌈⌊∣⍳\?⋆⍟○!⌹<≤=>≥≠≡≢∈⍷∪∩∼∨∧⍱⍲⍴,⍪⌽⊖⍉↑↓⊂⊃⌷⍋⍒⊤⊥⍕⍎⊣⊢]/; var isArrow = /←/; var isComment = /[⍝#].*$/; var stringEater = function(type) { var prev; prev = false; return function(c) { prev = c; if (c === type) { return prev === "\\"; } return true; }; }; return { startState: function() { return { prev: false, func: false, op: false, string: false, escape: false }; }, token: function(stream, state) { var ch, funcName; if (stream.eatSpace()) { return null; } ch = stream.next(); if (ch === '"' || ch === "'") { stream.eatWhile(stringEater(ch)); stream.next(); state.prev = true; return "string"; } if (/[\[{\(]/.test(ch)) { state.prev = false; return null; } if (/[\]}\)]/.test(ch)) { state.prev = true; return null; } if (isNiladic.test(ch)) { state.prev = false; return "niladic"; } if (/[¯\d]/.test(ch)) { if (state.func) { state.func = false; state.prev = false; } else { state.prev = true; } stream.eatWhile(/[\w\.]/); return "number"; } if (isOperator.test(ch)) { return "operator apl-" + builtInOps[ch]; } if (isArrow.test(ch)) { return "apl-arrow"; } if (isFunction.test(ch)) { funcName = "apl-"; if (builtInFuncs[ch] != null) { if (state.prev) { funcName += builtInFuncs[ch][1]; } else { funcName += builtInFuncs[ch][0]; } } state.func = true; state.prev = false; return "function " + funcName; } if (isComment.test(ch)) { stream.skipToEnd(); return "comment"; } if (ch === "∘" && stream.peek() === ".") { stream.next(); return "function jot-dot"; } stream.eatWhile(/[\w\$_]/); state.prev = true; return "keyword"; } }; }); CodeMirror.defineMIME("text/apl", "apl"); }); ================================================ FILE: third_party/CodeMirror/mode/apl/index.html ================================================ CodeMirror: APL mode

APL mode

Simple mode that tries to handle APL as well as it can.

It attempts to label functions/operators based upon monadic/dyadic usage (but this is far from fully fleshed out). This means there are meaningful classnames so hover states can have popups etc.

MIME types defined: text/apl (APL code)

================================================ FILE: third_party/CodeMirror/mode/asciiarmor/asciiarmor.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function errorIfNotEmpty(stream) { var nonWS = stream.match(/^\s*\S/); stream.skipToEnd(); return nonWS ? "error" : null; } CodeMirror.defineMode("asciiarmor", function() { return { token: function(stream, state) { var m; if (state.state == "top") { if (stream.sol() && (m = stream.match(/^-----BEGIN (.*)?-----\s*$/))) { state.state = "headers"; state.type = m[1]; return "tag"; } return errorIfNotEmpty(stream); } else if (state.state == "headers") { if (stream.sol() && stream.match(/^\w+:/)) { state.state = "header"; return "atom"; } else { var result = errorIfNotEmpty(stream); if (result) state.state = "body"; return result; } } else if (state.state == "header") { stream.skipToEnd(); state.state = "headers"; return "string"; } else if (state.state == "body") { if (stream.sol() && (m = stream.match(/^-----END (.*)?-----\s*$/))) { if (m[1] != state.type) return "error"; state.state = "end"; return "tag"; } else { if (stream.eatWhile(/[A-Za-z0-9+\/=]/)) { return null; } else { stream.next(); return "error"; } } } else if (state.state == "end") { return errorIfNotEmpty(stream); } }, blankLine: function(state) { if (state.state == "headers") state.state = "body"; }, startState: function() { return {state: "top", type: null}; } }; }); CodeMirror.defineMIME("application/pgp", "asciiarmor"); CodeMirror.defineMIME("application/pgp-encrypted", "asciiarmor"); CodeMirror.defineMIME("application/pgp-keys", "asciiarmor"); CodeMirror.defineMIME("application/pgp-signature", "asciiarmor"); }); ================================================ FILE: third_party/CodeMirror/mode/asciiarmor/index.html ================================================ CodeMirror: ASCII Armor (PGP) mode

ASCII Armor (PGP) mode

MIME types defined: application/pgp, application/pgp-encrypted, application/pgp-keys, application/pgp-signature

================================================ FILE: third_party/CodeMirror/mode/asn.1/asn.1.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("asn.1", function(config, parserConfig) { var indentUnit = config.indentUnit, keywords = parserConfig.keywords || {}, cmipVerbs = parserConfig.cmipVerbs || {}, compareTypes = parserConfig.compareTypes || {}, status = parserConfig.status || {}, tags = parserConfig.tags || {}, storage = parserConfig.storage || {}, modifier = parserConfig.modifier || {}, accessTypes = parserConfig.accessTypes|| {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false; var isOperatorChar = /[\|\^]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[\[\]\(\){}:=,;]/.test(ch)) { curPunc = ch; return "punctuation"; } if (ch == "-"){ if (stream.eat("-")) { stream.skipToEnd(); return "comment"; } } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\-]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) return "keyword"; if (cmipVerbs.propertyIsEnumerable(cur)) return "variable cmipVerbs"; if (compareTypes.propertyIsEnumerable(cur)) return "atom compareTypes"; if (status.propertyIsEnumerable(cur)) return "comment status"; if (tags.propertyIsEnumerable(cur)) return "variable-3 tags"; if (storage.propertyIsEnumerable(cur)) return "builtin storage"; if (modifier.propertyIsEnumerable(cur)) return "string-2 modifier"; if (accessTypes.propertyIsEnumerable(cur)) return "atom accessTypes"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped){ var afterNext = stream.peek(); //look if the character if the quote is like the B in '10100010'B if (afterNext){ afterNext = afterNext.toLowerCase(); if(afterNext == "b" || afterNext == "h" || afterNext == "o") stream.next(); } end = true; break; } escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { var indent = state.indented; if (state.context && state.context.type == "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } //Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; curPunc = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement"){ popContext(state); } else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))) pushContext(state, stream.column(), "statement"); state.startOfLine = false; return style; }, electricChars: "{}", lineComment: "--", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } CodeMirror.defineMIME("text/x-ttcn-asn", { name: "asn.1", keywords: words("DEFINITIONS OBJECTS IF DERIVED INFORMATION ACTION" + " REPLY ANY NAMED CHARACTERIZED BEHAVIOUR REGISTERED" + " WITH AS IDENTIFIED CONSTRAINED BY PRESENT BEGIN" + " IMPORTS FROM UNITS SYNTAX MIN-ACCESS MAX-ACCESS" + " MINACCESS MAXACCESS REVISION STATUS DESCRIPTION" + " SEQUENCE SET COMPONENTS OF CHOICE DistinguishedName" + " ENUMERATED SIZE MODULE END INDEX AUGMENTS EXTENSIBILITY" + " IMPLIED EXPORTS"), cmipVerbs: words("ACTIONS ADD GET NOTIFICATIONS REPLACE REMOVE"), compareTypes: words("OPTIONAL DEFAULT MANAGED MODULE-TYPE MODULE_IDENTITY" + " MODULE-COMPLIANCE OBJECT-TYPE OBJECT-IDENTITY" + " OBJECT-COMPLIANCE MODE CONFIRMED CONDITIONAL" + " SUBORDINATE SUPERIOR CLASS TRUE FALSE NULL" + " TEXTUAL-CONVENTION"), status: words("current deprecated mandatory obsolete"), tags: words("APPLICATION AUTOMATIC EXPLICIT IMPLICIT PRIVATE TAGS" + " UNIVERSAL"), storage: words("BOOLEAN INTEGER OBJECT IDENTIFIER BIT OCTET STRING" + " UTCTime InterfaceIndex IANAifType CMIP-Attribute" + " REAL PACKAGE PACKAGES IpAddress PhysAddress" + " NetworkAddress BITS BMPString TimeStamp TimeTicks" + " TruthValue RowStatus DisplayString GeneralString" + " GraphicString IA5String NumericString" + " PrintableString SnmpAdminAtring TeletexString" + " UTF8String VideotexString VisibleString StringStore" + " ISO646String T61String UniversalString Unsigned32" + " Integer32 Gauge Gauge32 Counter Counter32 Counter64"), modifier: words("ATTRIBUTE ATTRIBUTES MANDATORY-GROUP MANDATORY-GROUPS" + " GROUP GROUPS ELEMENTS EQUALITY ORDERING SUBSTRINGS" + " DEFINED"), accessTypes: words("not-accessible accessible-for-notify read-only" + " read-create read-write"), multiLineStrings: true }); }); ================================================ FILE: third_party/CodeMirror/mode/asn.1/index.html ================================================  CodeMirror: ASN.1 mode

ASN.1 example


Language: Abstract Syntax Notation One (ASN.1)

MIME types defined: text/x-ttcn-asn


The development of this mode has been sponsored by Ericsson .

Coded by Asmelash Tsegay Gebretsadkan

================================================ FILE: third_party/CodeMirror/mode/asterisk/asterisk.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /* * ===================================================================================== * * Filename: mode/asterisk/asterisk.js * * Description: CodeMirror mode for Asterisk dialplan * * Created: 05/17/2012 09:20:25 PM * Revision: none * * Author: Stas Kobzar (stas@modulis.ca), * Company: Modulis.ca Inc. * * ===================================================================================== */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("asterisk", function() { var atoms = ["exten", "same", "include","ignorepat","switch"], dpcmd = ["#include","#exec"], apps = [ "addqueuemember","adsiprog","aelsub","agentlogin","agentmonitoroutgoing","agi", "alarmreceiver","amd","answer","authenticate","background","backgrounddetect", "bridge","busy","callcompletioncancel","callcompletionrequest","celgenuserevent", "changemonitor","chanisavail","channelredirect","chanspy","clearhash","confbridge", "congestion","continuewhile","controlplayback","dahdiacceptr2call","dahdibarge", "dahdiras","dahdiscan","dahdisendcallreroutingfacility","dahdisendkeypadfacility", "datetime","dbdel","dbdeltree","deadagi","dial","dictate","directory","disa", "dumpchan","eagi","echo","endwhile","exec","execif","execiftime","exitwhile","extenspy", "externalivr","festival","flash","followme","forkcdr","getcpeid","gosub","gosubif", "goto","gotoif","gotoiftime","hangup","iax2provision","ices","importvar","incomplete", "ivrdemo","jabberjoin","jabberleave","jabbersend","jabbersendgroup","jabberstatus", "jack","log","macro","macroexclusive","macroexit","macroif","mailboxexists","meetme", "meetmeadmin","meetmechanneladmin","meetmecount","milliwatt","minivmaccmess","minivmdelete", "minivmgreet","minivmmwi","minivmnotify","minivmrecord","mixmonitor","monitor","morsecode", "mp3player","mset","musiconhold","nbscat","nocdr","noop","odbc","odbc","odbcfinish", "originate","ospauth","ospfinish","osplookup","ospnext","page","park","parkandannounce", "parkedcall","pausemonitor","pausequeuemember","pickup","pickupchan","playback","playtones", "privacymanager","proceeding","progress","queue","queuelog","raiseexception","read","readexten", "readfile","receivefax","receivefax","receivefax","record","removequeuemember", "resetcdr","retrydial","return","ringing","sayalpha","saycountedadj","saycountednoun", "saycountpl","saydigits","saynumber","sayphonetic","sayunixtime","senddtmf","sendfax", "sendfax","sendfax","sendimage","sendtext","sendurl","set","setamaflags", "setcallerpres","setmusiconhold","sipaddheader","sipdtmfmode","sipremoveheader","skel", "slastation","slatrunk","sms","softhangup","speechactivategrammar","speechbackground", "speechcreate","speechdeactivategrammar","speechdestroy","speechloadgrammar","speechprocessingsound", "speechstart","speechunloadgrammar","stackpop","startmusiconhold","stopmixmonitor","stopmonitor", "stopmusiconhold","stopplaytones","system","testclient","testserver","transfer","tryexec", "trysystem","unpausemonitor","unpausequeuemember","userevent","verbose","vmauthenticate", "vmsayname","voicemail","voicemailmain","wait","waitexten","waitfornoise","waitforring", "waitforsilence","waitmusiconhold","waituntil","while","zapateller" ]; function basicToken(stream,state){ var cur = ''; var ch = stream.next(); // comment if(ch == ";") { stream.skipToEnd(); return "comment"; } // context if(ch == '[') { stream.skipTo(']'); stream.eat(']'); return "header"; } // string if(ch == '"') { stream.skipTo('"'); return "string"; } if(ch == "'") { stream.skipTo("'"); return "string-2"; } // dialplan commands if(ch == '#') { stream.eatWhile(/\w/); cur = stream.current(); if(dpcmd.indexOf(cur) !== -1) { stream.skipToEnd(); return "strong"; } } // application args if(ch == '$'){ var ch1 = stream.peek(); if(ch1 == '{'){ stream.skipTo('}'); stream.eat('}'); return "variable-3"; } } // extension stream.eatWhile(/\w/); cur = stream.current(); if(atoms.indexOf(cur) !== -1) { state.extenStart = true; switch(cur) { case 'same': state.extenSame = true; break; case 'include': case 'switch': case 'ignorepat': state.extenInclude = true;break; default:break; } return "atom"; } } return { startState: function() { return { extenStart: false, extenSame: false, extenInclude: false, extenExten: false, extenPriority: false, extenApplication: false }; }, token: function(stream, state) { var cur = ''; if(stream.eatSpace()) return null; // extension started if(state.extenStart){ stream.eatWhile(/[^\s]/); cur = stream.current(); if(/^=>?$/.test(cur)){ state.extenExten = true; state.extenStart = false; return "strong"; } else { state.extenStart = false; stream.skipToEnd(); return "error"; } } else if(state.extenExten) { // set exten and priority state.extenExten = false; state.extenPriority = true; stream.eatWhile(/[^,]/); if(state.extenInclude) { stream.skipToEnd(); state.extenPriority = false; state.extenInclude = false; } if(state.extenSame) { state.extenPriority = false; state.extenSame = false; state.extenApplication = true; } return "tag"; } else if(state.extenPriority) { state.extenPriority = false; state.extenApplication = true; stream.next(); // get comma if(state.extenSame) return null; stream.eatWhile(/[^,]/); return "number"; } else if(state.extenApplication) { stream.eatWhile(/,/); cur = stream.current(); if(cur === ',') return null; stream.eatWhile(/\w/); cur = stream.current().toLowerCase(); state.extenApplication = false; if(apps.indexOf(cur) !== -1){ return "def strong"; } } else{ return basicToken(stream,state); } return null; } }; }); CodeMirror.defineMIME("text/x-asterisk", "asterisk"); }); ================================================ FILE: third_party/CodeMirror/mode/asterisk/index.html ================================================ CodeMirror: Asterisk dialplan mode

Asterisk dialplan mode

MIME types defined: text/x-asterisk.

================================================ FILE: third_party/CodeMirror/mode/brainfuck/brainfuck.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Brainfuck mode created by Michael Kaminsky https://github.com/mkaminsky11 (function(mod) { if (typeof exports == "object" && typeof module == "object") mod(require("../../lib/codemirror")) else if (typeof define == "function" && define.amd) define(["../../lib/codemirror"], mod) else mod(CodeMirror) })(function(CodeMirror) { "use strict" var reserve = "><+-.,[]".split(""); /* comments can be either: placed behind lines +++ this is a comment where reserved characters cannot be used or in a loop [ this is ok to use [ ] and stuff ] or preceded by # */ CodeMirror.defineMode("brainfuck", function() { return { startState: function() { return { commentLine: false, left: 0, right: 0, commentLoop: false } }, token: function(stream, state) { if (stream.eatSpace()) return null if(stream.sol()){ state.commentLine = false; } var ch = stream.next().toString(); if(reserve.indexOf(ch) !== -1){ if(state.commentLine === true){ if(stream.eol()){ state.commentLine = false; } return "comment"; } if(ch === "]" || ch === "["){ if(ch === "["){ state.left++; } else{ state.right++; } return "bracket"; } else if(ch === "+" || ch === "-"){ return "keyword"; } else if(ch === "<" || ch === ">"){ return "atom"; } else if(ch === "." || ch === ","){ return "def"; } } else{ state.commentLine = true; if(stream.eol()){ state.commentLine = false; } return "comment"; } if(stream.eol()){ state.commentLine = false; } } }; }); CodeMirror.defineMIME("text/x-brainfuck","brainfuck") }); ================================================ FILE: third_party/CodeMirror/mode/brainfuck/index.html ================================================ CodeMirror: Brainfuck mode

Brainfuck mode

A mode for Brainfuck

MIME types defined: text/x-brainfuck

================================================ FILE: third_party/CodeMirror/mode/clike/clike.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function Context(indented, column, type, info, align, prev) { this.indented = indented; this.column = column; this.type = type; this.info = info; this.align = align; this.prev = prev; } function pushContext(state, col, type, info) { var indent = state.indented; if (state.context && state.context.type == "statement" && type != "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, info, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } function typeBefore(stream, state, pos) { if (state.prevToken == "variable" || state.prevToken == "type") return true; if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; } function isTopScope(context) { for (;;) { if (!context || context.type == "top") return true; if (context.type == "}" && context.prev.info != "namespace") return false; context = context.prev; } } CodeMirror.defineMode("clike", function(config, parserConfig) { var indentUnit = config.indentUnit, statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, dontAlignCalls = parserConfig.dontAlignCalls, keywords = parserConfig.keywords || {}, types = parserConfig.types || {}, builtin = parserConfig.builtin || {}, blockKeywords = parserConfig.blockKeywords || {}, defKeywords = parserConfig.defKeywords || {}, atoms = parserConfig.atoms || {}, hooks = parserConfig.hooks || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false, indentSwitch = parserConfig.indentSwitch !== false, namespaceSeparator = parserConfig.namespaceSeparator, isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, numberStart = parserConfig.numberStart || /[\d\.]/, number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/, // An optional function that takes a {string} token and returns true if it // should be treated as a builtin. isReservedIdentifier = parserConfig.isReservedIdentifier || false; var curPunc, isDefKeyword; function tokenBase(stream, state) { var ch = stream.next(); if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (isPunctuationChar.test(ch)) { curPunc = ch; return null; } if (numberStart.test(ch)) { stream.backUp(1) if (stream.match(number)) return "number" stream.next() } if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} return "operator"; } stream.eatWhile(isIdentifierChar); if (namespaceSeparator) while (stream.match(namespaceSeparator)) stream.eatWhile(isIdentifierChar); var cur = stream.current(); if (contains(keywords, cur)) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; if (contains(defKeywords, cur)) isDefKeyword = true; return "keyword"; } if (contains(types, cur)) return "type"; if (contains(builtin, cur) || (isReservedIdentifier && isReservedIdentifier(cur))) { if (contains(blockKeywords, cur)) curPunc = "newstatement"; return "builtin"; } if (contains(atoms, cur)) return "atom"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function maybeEOL(stream, state) { if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), indented: 0, startOfLine: true, prevToken: null }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) { maybeEOL(stream, state); return null; } curPunc = isDefKeyword = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) while (state.context.type == "statement") popContext(state); else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || (ctx.type == "statement" && curPunc == "newstatement"))) { pushContext(state, stream.column(), "statement", stream.current()); } if (style == "variable" && ((state.prevToken == "def" || (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && isTopScope(state.context) && stream.match(/^\s*\(/, false))))) style = "def"; if (hooks.token) { var result = hooks.token(stream, state, style); if (result !== undefined) style = result; } if (style == "def" && parserConfig.styleDefs === false) style = "variable"; state.startOfLine = false; state.prevToken = isDefKeyword ? "def" : style || curPunc; maybeEOL(stream, state); return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); var closing = firstChar == ctx.type; if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; if (parserConfig.dontIndentStatements) while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) ctx = ctx.prev if (hooks.indent) { var hook = hooks.indent(state, ctx, textAfter, indentUnit); if (typeof hook == "number") return hook } var switchBlock = ctx.prev && ctx.prev.info == "switch"; if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev return ctx.indented } if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); if (ctx.align && (!dontAlignCalls || ctx.type != ")")) return ctx.column + (closing ? 0 : 1); if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; return ctx.indented + (closing ? 0 : indentUnit) + (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); }, electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", lineComment: "//", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function contains(words, word) { if (typeof words === "function") { return words(word); } else { return words.propertyIsEnumerable(word); } } var cKeywords = "auto if break case register continue return default do sizeof " + "static else struct switch extern typedef union for goto while enum const " + "volatile inline restrict asm fortran"; // Do not use this. Use the cTypes function below. This is global just to avoid // excessive calls when cTypes is being called multiple times during a parse. var basicCTypes = words("int long char short double float unsigned signed " + "void bool"); // Do not use this. Use the objCTypes function below. This is global just to avoid // excessive calls when objCTypes is being called multiple times during a parse. var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL"); // Returns true if identifier is a "C" type. // C type is defined as those that are reserved by the compiler (basicTypes), // and those that end in _t (Reserved by POSIX for types) // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html function cTypes(identifier) { return contains(basicCTypes, identifier) || /.+_t/.test(identifier); } // Returns true if identifier is a "Objective C" type. function objCTypes(identifier) { return cTypes(identifier) || contains(basicObjCTypes, identifier); } var cBlockKeywords = "case do else for if switch while struct enum union"; var cDefKeywords = "struct enum union"; function cppHook(stream, state) { if (!state.startOfLine) return false for (var ch, next = null; ch = stream.peek();) { if (ch == "\\" && stream.match(/^.$/)) { next = cppHook break } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { break } stream.next() } state.tokenize = next return "meta" } function pointerHook(_stream, state) { if (state.prevToken == "type") return "type"; return false; } // For C and C++ (and ObjC): identifiers starting with __ // or _ followed by a capital letter are reserved for the compiler. function cIsReservedIdentifier(token) { if (!token || token.length < 2) return false; if (token[0] != '_') return false; return (token[1] == '_') || (token[1] !== token[1].toLowerCase()); } function cpp14Literal(stream) { stream.eatWhile(/[\w\.']/); return "number"; } function cpp11StringHook(stream, state) { stream.backUp(1); // Raw strings. if (stream.match(/(R|u8R|uR|UR|LR)/)) { var match = stream.match(/"([^\s\\()]{0,16})\(/); if (!match) { return false; } state.cpp11RawStringDelim = match[1]; state.tokenize = tokenRawString; return tokenRawString(stream, state); } // Unicode strings/chars. if (stream.match(/(u8|u|U|L)/)) { if (stream.match(/["']/, /* eat */ false)) { return "string"; } return false; } // Ignore this hook. stream.next(); return false; } function cppLooksLikeConstructor(word) { var lastTwo = /(\w+)::~?(\w+)$/.exec(word); return lastTwo && lastTwo[1] == lastTwo[2]; } // C#-style strings where "" escapes a quote. function tokenAtString(stream, state) { var next; while ((next = stream.next()) != null) { if (next == '"' && !stream.eat('"')) { state.tokenize = null; break; } } return "string"; } // C++11 raw string literal is "( anything )", where // can be a string up to 16 characters long. function tokenRawString(stream, state) { // Escape characters that have special regex meanings. var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); var match = stream.match(new RegExp(".*?\\)" + delim + '"')); if (match) state.tokenize = null; else stream.skipToEnd(); return "string"; } function def(mimes, mode) { if (typeof mimes == "string") mimes = [mimes]; var words = []; function add(obj) { if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) words.push(prop); } add(mode.keywords); add(mode.types); add(mode.builtin); add(mode.atoms); if (words.length) { mode.helperType = mimes[0]; CodeMirror.registerHelper("hintWords", mimes[0], words); } for (var i = 0; i < mimes.length; ++i) CodeMirror.defineMIME(mimes[i], mode); } def(["text/x-csrc", "text/x-c", "text/x-chdr"], { name: "clike", keywords: words(cKeywords), types: cTypes, blockKeywords: words(cBlockKeywords), defKeywords: words(cDefKeywords), typeFirstDefinitions: true, atoms: words("NULL true false"), isReservedIdentifier: cIsReservedIdentifier, hooks: { "#": cppHook, "*": pointerHook, }, modeProps: {fold: ["brace", "include"]} }); def(["text/x-c++src", "text/x-c++hdr"], { name: "clike", // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20. keywords: words(cKeywords + "alignas alignof and and_eq audit axiom bitand bitor catch " + "class compl concept constexpr const_cast decltype delete dynamic_cast " + "explicit export final friend import module mutable namespace new noexcept " + "not not_eq operator or or_eq override private protected public " + "reinterpret_cast requires static_assert static_cast template this " + "thread_local throw try typeid typename using virtual xor xor_eq"), types: cTypes, blockKeywords: words(cBlockKeywords + " class try catch"), defKeywords: words(cDefKeywords + " class namespace"), typeFirstDefinitions: true, atoms: words("true false NULL nullptr"), dontIndentStatements: /^template$/, isIdentifierChar: /[\w\$_~\xa1-\uffff]/, isReservedIdentifier: cIsReservedIdentifier, hooks: { "#": cppHook, "*": pointerHook, "u": cpp11StringHook, "U": cpp11StringHook, "L": cpp11StringHook, "R": cpp11StringHook, "0": cpp14Literal, "1": cpp14Literal, "2": cpp14Literal, "3": cpp14Literal, "4": cpp14Literal, "5": cpp14Literal, "6": cpp14Literal, "7": cpp14Literal, "8": cpp14Literal, "9": cpp14Literal, token: function(stream, state, style) { if (style == "variable" && stream.peek() == "(" && (state.prevToken == ";" || state.prevToken == null || state.prevToken == "}") && cppLooksLikeConstructor(stream.current())) return "def"; } }, namespaceSeparator: "::", modeProps: {fold: ["brace", "include"]} }); def("text/x-java", { name: "clike", keywords: words("abstract assert break case catch class const continue default " + "do else enum extends final finally float for goto if implements import " + "instanceof interface native new package private protected public " + "return static strictfp super switch synchronized this throw throws transient " + "try volatile while @interface"), types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + "Integer Long Number Object Short String StringBuffer StringBuilder Void"), blockKeywords: words("catch class do else finally for if switch try while"), defKeywords: words("class interface enum @interface"), typeFirstDefinitions: true, atoms: words("true false null"), number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, hooks: { "@": function(stream) { // Don't match the @interface keyword. if (stream.match('interface', false)) return false; stream.eatWhile(/[\w\$_]/); return "meta"; } }, modeProps: {fold: ["brace", "import"]} }); def("text/x-csharp", { name: "clike", keywords: words("abstract as async await base break case catch checked class const continue" + " default delegate do else enum event explicit extern finally fixed for" + " foreach goto if implicit in interface internal is lock namespace new" + " operator out override params private protected public readonly ref return sealed" + " sizeof stackalloc static struct switch this throw try typeof unchecked" + " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + " global group into join let orderby partial remove select set value var yield"), types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + " UInt64 bool byte char decimal double short int long object" + " sbyte float string ushort uint ulong"), blockKeywords: words("catch class do else finally for foreach if struct switch try while"), defKeywords: words("class interface namespace struct var"), typeFirstDefinitions: true, atoms: words("true false null"), hooks: { "@": function(stream, state) { if (stream.eat('"')) { state.tokenize = tokenAtString; return tokenAtString(stream, state); } stream.eatWhile(/[\w\$_]/); return "meta"; } } }); function tokenTripleString(stream, state) { var escaped = false; while (!stream.eol()) { if (!escaped && stream.match('"""')) { state.tokenize = null; break; } escaped = stream.next() == "\\" && !escaped; } return "string"; } function tokenNestedComment(depth) { return function (stream, state) { var ch while (ch = stream.next()) { if (ch == "*" && stream.eat("/")) { if (depth == 1) { state.tokenize = null break } else { state.tokenize = tokenNestedComment(depth - 1) return state.tokenize(stream, state) } } else if (ch == "/" && stream.eat("*")) { state.tokenize = tokenNestedComment(depth + 1) return state.tokenize(stream, state) } } return "comment" } } def("text/x-scala", { name: "clike", keywords: words( /* scala */ "abstract case catch class def do else extends final finally for forSome if " + "implicit import lazy match new null object override package private protected return " + "sealed super this throw trait try type val var while with yield _ " + /* package scala */ "assert assume require print println printf readLine readBoolean readByte readShort " + "readChar readInt readLong readFloat readDouble" ), types: words( "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + /* package java.lang */ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" ), multiLineStrings: true, blockKeywords: words("catch class enum do else finally for forSome if match switch try while"), defKeywords: words("class enum def object package trait type val var"), atoms: words("true false null"), indentStatements: false, indentSwitch: false, isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; }, '"': function(stream, state) { if (!stream.match('""')) return false; state.tokenize = tokenTripleString; return state.tokenize(stream, state); }, "'": function(stream) { stream.eatWhile(/[\w\$_\xa1-\uffff]/); return "atom"; }, "=": function(stream, state) { var cx = state.context if (cx.type == "}" && cx.align && stream.eat(">")) { state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev) return "operator" } else { return false } }, "/": function(stream, state) { if (!stream.eat("*")) return false state.tokenize = tokenNestedComment(1) return state.tokenize(stream, state) } }, modeProps: {closeBrackets: {pairs: '()[]{}""', triples: '"'}} }); function tokenKotlinString(tripleString){ return function (stream, state) { var escaped = false, next, end = false; while (!stream.eol()) { if (!tripleString && !escaped && stream.match('"') ) {end = true; break;} if (tripleString && stream.match('"""')) {end = true; break;} next = stream.next(); if(!escaped && next == "$" && stream.match('{')) stream.skipTo("}"); escaped = !escaped && next == "\\" && !tripleString; } if (end || !tripleString) state.tokenize = null; return "string"; } } def("text/x-kotlin", { name: "clike", keywords: words( /*keywords*/ "package as typealias class interface this super val operator " + "var fun for is in This throw return annotation " + "break continue object if else while do try when !in !is as? " + /*soft keywords*/ "file import where by get set abstract enum open inner override private public internal " + "protected catch finally out final vararg reified dynamic companion constructor init " + "sealed field property receiver param sparam lateinit data inline noinline tailrec " + "external annotation crossinline const operator infix suspend actual expect setparam" ), types: words( /* package java.lang */ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " + "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " + "LazyThreadSafetyMode LongArray Nothing ShortArray Unit" ), intendSwitch: false, indentStatements: false, multiLineStrings: true, number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, blockKeywords: words("catch class do else finally for if where try while enum"), defKeywords: words("class val var object interface fun"), atoms: words("true false null this"), hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; }, '*': function(_stream, state) { return state.prevToken == '.' ? 'variable' : 'operator'; }, '"': function(stream, state) { state.tokenize = tokenKotlinString(stream.match('""')); return state.tokenize(stream, state); }, indent: function(state, ctx, textAfter, indentUnit) { var firstChar = textAfter && textAfter.charAt(0); if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "") return state.indented; if (state.prevToken == "operator" && textAfter != "}" || state.prevToken == "variable" && firstChar == "." || (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".") return indentUnit * 2 + ctx.indented; if (ctx.align && ctx.type == "}") return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit); } }, modeProps: {closeBrackets: {triples: '"'}} }); def(["x-shader/x-vertex", "x-shader/x-fragment"], { name: "clike", keywords: words("sampler1D sampler2D sampler3D samplerCube " + "sampler1DShadow sampler2DShadow " + "const attribute uniform varying " + "break continue discard return " + "for while do if else struct " + "in out inout"), types: words("float int bool void " + "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + "mat2 mat3 mat4"), blockKeywords: words("for while do if else struct"), builtin: words("radians degrees sin cos tan asin acos atan " + "pow exp log exp2 sqrt inversesqrt " + "abs sign floor ceil fract mod min max clamp mix step smoothstep " + "length distance dot cross normalize ftransform faceforward " + "reflect refract matrixCompMult " + "lessThan lessThanEqual greaterThan greaterThanEqual " + "equal notEqual any all not " + "texture1D texture1DProj texture1DLod texture1DProjLod " + "texture2D texture2DProj texture2DLod texture2DProjLod " + "texture3D texture3DProj texture3DLod texture3DProjLod " + "textureCube textureCubeLod " + "shadow1D shadow2D shadow1DProj shadow2DProj " + "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + "dFdx dFdy fwidth " + "noise1 noise2 noise3 noise4"), atoms: words("true false " + "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + "gl_FogCoord gl_PointCoord " + "gl_Position gl_PointSize gl_ClipVertex " + "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + "gl_TexCoord gl_FogFragCoord " + "gl_FragCoord gl_FrontFacing " + "gl_FragData gl_FragDepth " + "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + "gl_ProjectionMatrixInverseTranspose " + "gl_ModelViewProjectionMatrixInverseTranspose " + "gl_TextureMatrixInverseTranspose " + "gl_NormalScale gl_DepthRange gl_ClipPlane " + "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + "gl_FrontLightModelProduct gl_BackLightModelProduct " + "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + "gl_FogParameters " + "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + "gl_MaxDrawBuffers"), indentSwitch: false, hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); def("text/x-nesc", { name: "clike", keywords: words(cKeywords + " as atomic async call command component components configuration event generic " + "implementation includes interface module new norace nx_struct nx_union post provides " + "signal task uses abstract extends"), types: cTypes, blockKeywords: words(cBlockKeywords), atoms: words("null true false"), hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); def("text/x-objectivec", { name: "clike", keywords: words(cKeywords + " bycopy byref in inout oneway out self super atomic nonatomic retain copy " + "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " + "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " + "@public @package @private @protected @required @optional @try @catch @finally @import " + "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available"), types: objCTypes, builtin: words("FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINED " + "NS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER " + "NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN " + "NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT"), blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"), defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"), dontIndentStatements: /^@.*$/, typeFirstDefinitions: true, atoms: words("YES NO NULL Nil nil true false nullptr"), isReservedIdentifier: cIsReservedIdentifier, hooks: { "#": cppHook, "*": pointerHook, }, modeProps: {fold: ["brace", "include"]} }); def("text/x-squirrel", { name: "clike", keywords: words("base break clone continue const default delete enum extends function in class" + " foreach local resume return this throw typeof yield constructor instanceof static"), types: cTypes, blockKeywords: words("case catch class else for foreach if switch try while"), defKeywords: words("function local class"), typeFirstDefinitions: true, atoms: words("true false null"), hooks: {"#": cppHook}, modeProps: {fold: ["brace", "include"]} }); // Ceylon Strings need to deal with interpolation var stringTokenizer = null; function tokenCeylonString(type) { return function(stream, state) { var escaped = false, next, end = false; while (!stream.eol()) { if (!escaped && stream.match('"') && (type == "single" || stream.match('""'))) { end = true; break; } if (!escaped && stream.match('``')) { stringTokenizer = tokenCeylonString(type); end = true; break; } next = stream.next(); escaped = type == "single" && !escaped && next == "\\"; } if (end) state.tokenize = null; return "string"; } } def("text/x-ceylon", { name: "clike", keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + " exists extends finally for function given if import in interface is let module new" + " nonempty object of out outer package return satisfies super switch then this throw" + " try value void while"), types: function(word) { // In Ceylon all identifiers that start with an uppercase are types var first = word.charAt(0); return (first === first.toUpperCase() && first !== first.toLowerCase()); }, blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), defKeywords: words("class dynamic function interface module object package value"), builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + " native optional sealed see serializable shared suppressWarnings tagged throws variable"), isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, numberStart: /[\d#$]/, number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, multiLineStrings: true, typeFirstDefinitions: true, atoms: words("true false null larger smaller equal empty finished"), indentSwitch: false, styleDefs: false, hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; }, '"': function(stream, state) { state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); return state.tokenize(stream, state); }, '`': function(stream, state) { if (!stringTokenizer || !stream.match('`')) return false; state.tokenize = stringTokenizer; stringTokenizer = null; return state.tokenize(stream, state); }, "'": function(stream) { stream.eatWhile(/[\w\$_\xa1-\uffff]/); return "atom"; }, token: function(_stream, state, style) { if ((style == "variable" || style == "type") && state.prevToken == ".") { return "variable-2"; } } }, modeProps: { fold: ["brace", "import"], closeBrackets: {triples: '"'} } }); }); ================================================ FILE: third_party/CodeMirror/mode/clike/index.html ================================================ CodeMirror: C-like mode

C-like mode

C++ example

Objective-C example

Java example

Scala example

Kotlin mode

Ceylon mode

Simple mode that tries to handle C-like languages as well as it can. Takes two configuration parameters: keywords, an object whose property names are the keywords in the language, and useCPP, which determines whether C preprocessor directives are recognized.

MIME types defined: text/x-csrc (C), text/x-c++src (C++), text/x-java (Java), text/x-csharp (C#), text/x-objectivec (Objective-C), text/x-scala (Scala), text/x-vertex x-shader/x-fragment (shader programs), text/x-squirrel (Squirrel) and text/x-ceylon (Ceylon)

================================================ FILE: third_party/CodeMirror/mode/clike/scala.html ================================================ CodeMirror: Scala mode

Scala mode

================================================ FILE: third_party/CodeMirror/mode/clike/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-c"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("indent", "[type void] [def foo]([type void*] [variable a], [type int] [variable b]) {", " [type int] [variable c] [operator =] [variable b] [operator +]", " [number 1];", " [keyword return] [operator *][variable a];", "}"); MT("indent_switch", "[keyword switch] ([variable x]) {", " [keyword case] [number 10]:", " [keyword return] [number 20];", " [keyword default]:", " [variable printf]([string \"foo %c\"], [variable x]);", "}"); MT("def", "[type void] [def foo]() {}", "[keyword struct] [def bar]{}", "[keyword enum] [def zot]{}", "[keyword union] [def ugh]{}", "[type int] [type *][def baz]() {}"); MT("def_new_line", "::[variable std]::[variable SomeTerribleType][operator <][variable T][operator >]", "[def SomeLongMethodNameThatDoesntFitIntoOneLine]([keyword const] [variable MyType][operator &] [variable param]) {}") MT("double_block", "[keyword for] (;;)", " [keyword for] (;;)", " [variable x][operator ++];", "[keyword return];"); MT("preprocessor", "[meta #define FOO 3]", "[type int] [variable foo];", "[meta #define BAR\\]", "[meta 4]", "[type unsigned] [type int] [variable bar] [operator =] [number 8];", "[meta #include ][comment // comment]") MT("c_underscores", "[builtin __FOO];", "[builtin _Complex];", "[builtin __aName];", "[variable _aName];"); MT("c_types", "[type int];", "[type long];", "[type char];", "[type short];", "[type double];", "[type float];", "[type unsigned];", "[type signed];", "[type void];", "[type bool];", "[type foo_t];", "[variable foo_T];", "[variable _t];"); var mode_cpp = CodeMirror.getMode({indentUnit: 2}, "text/x-c++src"); function MTCPP(name) { test.mode(name, mode_cpp, Array.prototype.slice.call(arguments, 1)); } MTCPP("cpp14_literal", "[number 10'000];", "[number 0b10'000];", "[number 0x10'000];", "[string '100000'];"); MTCPP("ctor_dtor", "[def Foo::Foo]() {}", "[def Foo::~Foo]() {}"); MTCPP("cpp_underscores", "[builtin __FOO];", "[builtin _Complex];", "[builtin __aName];", "[variable _aName];"); var mode_objc = CodeMirror.getMode({indentUnit: 2}, "text/x-objectivec"); function MTOBJC(name) { test.mode(name, mode_objc, Array.prototype.slice.call(arguments, 1)); } MTOBJC("objc_underscores", "[builtin __FOO];", "[builtin _Complex];", "[builtin __aName];", "[variable _aName];"); MTOBJC("objc_interface", "[keyword @interface] [def foo] {", " [type int] [variable bar];", "}", "[keyword @property] ([keyword atomic], [keyword nullable]) [variable NSString][operator *] [variable a];", "[keyword @property] ([keyword nonatomic], [keyword assign]) [type int] [variable b];", "[operator -]([type instancetype])[variable initWithFoo]:([type int])[variable a] " + "[builtin NS_DESIGNATED_INITIALIZER];", "[keyword @end]"); MTOBJC("objc_implementation", "[keyword @implementation] [def foo] {", " [type int] [variable bar];", "}", "[keyword @property] ([keyword readwrite]) [type SEL] [variable a];", "[operator -]([type instancetype])[variable initWithFoo]:([type int])[variable a] {", " [keyword if](([keyword self] [operator =] [[[keyword super] [variable init] ]])) {}", " [keyword return] [keyword self];", "}", "[keyword @end]"); MTOBJC("objc_types", "[type int];", "[type foo_t];", "[variable foo_T];", "[type id];", "[type SEL];", "[type instancetype];", "[type Class];", "[type Protocol];", "[type BOOL];" ); var mode_scala = CodeMirror.getMode({indentUnit: 2}, "text/x-scala"); function MTSCALA(name) { test.mode("scala_" + name, mode_scala, Array.prototype.slice.call(arguments, 1)); } MTSCALA("nested_comments", "[comment /*]", "[comment But wait /* this is a nested comment */ for real]", "[comment /**** let * me * show * you ****/]", "[comment ///// let / me / show / you /////]", "[comment */]"); })(); ================================================ FILE: third_party/CodeMirror/mode/clojure/clojure.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports === "object" && typeof module === "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define === "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("clojure", function (options) { var atoms = ["false", "nil", "true"]; var specialForms = [".", "catch", "def", "do", "if", "monitor-enter", "monitor-exit", "new", "quote", "recur", "set!", "throw", "try", "var"]; var coreSymbols = ["*", "*'", "*1", "*2", "*3", "*agent*", "*allow-unresolved-vars*", "*assert*", "*clojure-version*", "*command-line-args*", "*compile-files*", "*compile-path*", "*compiler-options*", "*data-readers*", "*default-data-reader-fn*", "*e", "*err*", "*file*", "*flush-on-newline*", "*fn-loader*", "*in*", "*math-context*", "*ns*", "*out*", "*print-dup*", "*print-length*", "*print-level*", "*print-meta*", "*print-namespace-maps*", "*print-readably*", "*read-eval*", "*reader-resolver*", "*source-path*", "*suppress-read*", "*unchecked-math*", "*use-context-classloader*", "*verbose-defrecords*", "*warn-on-reflection*", "+", "+'", "-", "-'", "->", "->>", "->ArrayChunk", "->Eduction", "->Vec", "->VecNode", "->VecSeq", "-cache-protocol-fn", "-reset-methods", "..", "/", "<", "<=", "=", "==", ">", ">=", "EMPTY-NODE", "Inst", "StackTraceElement->vec", "Throwable->map", "accessor", "aclone", "add-classpath", "add-watch", "agent", "agent-error", "agent-errors", "aget", "alength", "alias", "all-ns", "alter", "alter-meta!", "alter-var-root", "amap", "ancestors", "and", "any?", "apply", "areduce", "array-map", "as->", "aset", "aset-boolean", "aset-byte", "aset-char", "aset-double", "aset-float", "aset-int", "aset-long", "aset-short", "assert", "assoc", "assoc!", "assoc-in", "associative?", "atom", "await", "await-for", "await1", "bases", "bean", "bigdec", "bigint", "biginteger", "binding", "bit-and", "bit-and-not", "bit-clear", "bit-flip", "bit-not", "bit-or", "bit-set", "bit-shift-left", "bit-shift-right", "bit-test", "bit-xor", "boolean", "boolean-array", "boolean?", "booleans", "bound-fn", "bound-fn*", "bound?", "bounded-count", "butlast", "byte", "byte-array", "bytes", "bytes?", "case", "cast", "cat", "char", "char-array", "char-escape-string", "char-name-string", "char?", "chars", "chunk", "chunk-append", "chunk-buffer", "chunk-cons", "chunk-first", "chunk-next", "chunk-rest", "chunked-seq?", "class", "class?", "clear-agent-errors", "clojure-version", "coll?", "comment", "commute", "comp", "comparator", "compare", "compare-and-set!", "compile", "complement", "completing", "concat", "cond", "cond->", "cond->>", "condp", "conj", "conj!", "cons", "constantly", "construct-proxy", "contains?", "count", "counted?", "create-ns", "create-struct", "cycle", "dec", "dec'", "decimal?", "declare", "dedupe", "default-data-readers", "definline", "definterface", "defmacro", "defmethod", "defmulti", "defn", "defn-", "defonce", "defprotocol", "defrecord", "defstruct", "deftype", "delay", "delay?", "deliver", "denominator", "deref", "derive", "descendants", "destructure", "disj", "disj!", "dissoc", "dissoc!", "distinct", "distinct?", "doall", "dorun", "doseq", "dosync", "dotimes", "doto", "double", "double-array", "double?", "doubles", "drop", "drop-last", "drop-while", "eduction", "empty", "empty?", "ensure", "ensure-reduced", "enumeration-seq", "error-handler", "error-mode", "eval", "even?", "every-pred", "every?", "ex-data", "ex-info", "extend", "extend-protocol", "extend-type", "extenders", "extends?", "false?", "ffirst", "file-seq", "filter", "filterv", "find", "find-keyword", "find-ns", "find-protocol-impl", "find-protocol-method", "find-var", "first", "flatten", "float", "float-array", "float?", "floats", "flush", "fn", "fn?", "fnext", "fnil", "for", "force", "format", "frequencies", "future", "future-call", "future-cancel", "future-cancelled?", "future-done?", "future?", "gen-class", "gen-interface", "gensym", "get", "get-in", "get-method", "get-proxy-class", "get-thread-bindings", "get-validator", "group-by", "halt-when", "hash", "hash-combine", "hash-map", "hash-ordered-coll", "hash-set", "hash-unordered-coll", "ident?", "identical?", "identity", "if-let", "if-not", "if-some", "ifn?", "import", "in-ns", "inc", "inc'", "indexed?", "init-proxy", "inst-ms", "inst-ms*", "inst?", "instance?", "int", "int-array", "int?", "integer?", "interleave", "intern", "interpose", "into", "into-array", "ints", "io!", "isa?", "iterate", "iterator-seq", "juxt", "keep", "keep-indexed", "key", "keys", "keyword", "keyword?", "last", "lazy-cat", "lazy-seq", "let", "letfn", "line-seq", "list", "list*", "list?", "load", "load-file", "load-reader", "load-string", "loaded-libs", "locking", "long", "long-array", "longs", "loop", "macroexpand", "macroexpand-1", "make-array", "make-hierarchy", "map", "map-entry?", "map-indexed", "map?", "mapcat", "mapv", "max", "max-key", "memfn", "memoize", "merge", "merge-with", "meta", "method-sig", "methods", "min", "min-key", "mix-collection-hash", "mod", "munge", "name", "namespace", "namespace-munge", "nat-int?", "neg-int?", "neg?", "newline", "next", "nfirst", "nil?", "nnext", "not", "not-any?", "not-empty", "not-every?", "not=", "ns", "ns-aliases", "ns-imports", "ns-interns", "ns-map", "ns-name", "ns-publics", "ns-refers", "ns-resolve", "ns-unalias", "ns-unmap", "nth", "nthnext", "nthrest", "num", "number?", "numerator", "object-array", "odd?", "or", "parents", "partial", "partition", "partition-all", "partition-by", "pcalls", "peek", "persistent!", "pmap", "pop", "pop!", "pop-thread-bindings", "pos-int?", "pos?", "pr", "pr-str", "prefer-method", "prefers", "primitives-classnames", "print", "print-ctor", "print-dup", "print-method", "print-simple", "print-str", "printf", "println", "println-str", "prn", "prn-str", "promise", "proxy", "proxy-call-with-super", "proxy-mappings", "proxy-name", "proxy-super", "push-thread-bindings", "pvalues", "qualified-ident?", "qualified-keyword?", "qualified-symbol?", "quot", "rand", "rand-int", "rand-nth", "random-sample", "range", "ratio?", "rational?", "rationalize", "re-find", "re-groups", "re-matcher", "re-matches", "re-pattern", "re-seq", "read", "read-line", "read-string", "reader-conditional", "reader-conditional?", "realized?", "record?", "reduce", "reduce-kv", "reduced", "reduced?", "reductions", "ref", "ref-history-count", "ref-max-history", "ref-min-history", "ref-set", "refer", "refer-clojure", "reify", "release-pending-sends", "rem", "remove", "remove-all-methods", "remove-method", "remove-ns", "remove-watch", "repeat", "repeatedly", "replace", "replicate", "require", "reset!", "reset-meta!", "reset-vals!", "resolve", "rest", "restart-agent", "resultset-seq", "reverse", "reversible?", "rseq", "rsubseq", "run!", "satisfies?", "second", "select-keys", "send", "send-off", "send-via", "seq", "seq?", "seqable?", "seque", "sequence", "sequential?", "set", "set-agent-send-executor!", "set-agent-send-off-executor!", "set-error-handler!", "set-error-mode!", "set-validator!", "set?", "short", "short-array", "shorts", "shuffle", "shutdown-agents", "simple-ident?", "simple-keyword?", "simple-symbol?", "slurp", "some", "some->", "some->>", "some-fn", "some?", "sort", "sort-by", "sorted-map", "sorted-map-by", "sorted-set", "sorted-set-by", "sorted?", "special-symbol?", "spit", "split-at", "split-with", "str", "string?", "struct", "struct-map", "subs", "subseq", "subvec", "supers", "swap!", "swap-vals!", "symbol", "symbol?", "sync", "tagged-literal", "tagged-literal?", "take", "take-last", "take-nth", "take-while", "test", "the-ns", "thread-bound?", "time", "to-array", "to-array-2d", "trampoline", "transduce", "transient", "tree-seq", "true?", "type", "unchecked-add", "unchecked-add-int", "unchecked-byte", "unchecked-char", "unchecked-dec", "unchecked-dec-int", "unchecked-divide-int", "unchecked-double", "unchecked-float", "unchecked-inc", "unchecked-inc-int", "unchecked-int", "unchecked-long", "unchecked-multiply", "unchecked-multiply-int", "unchecked-negate", "unchecked-negate-int", "unchecked-remainder-int", "unchecked-short", "unchecked-subtract", "unchecked-subtract-int", "underive", "unquote", "unquote-splicing", "unreduced", "unsigned-bit-shift-right", "update", "update-in", "update-proxy", "uri?", "use", "uuid?", "val", "vals", "var-get", "var-set", "var?", "vary-meta", "vec", "vector", "vector-of", "vector?", "volatile!", "volatile?", "vreset!", "vswap!", "when", "when-first", "when-let", "when-not", "when-some", "while", "with-bindings", "with-bindings*", "with-in-str", "with-loading-context", "with-local-vars", "with-meta", "with-open", "with-out-str", "with-precision", "with-redefs", "with-redefs-fn", "xml-seq", "zero?", "zipmap"]; var haveBodyParameter = [ "->", "->>", "as->", "binding", "bound-fn", "case", "catch", "comment", "cond", "cond->", "cond->>", "condp", "def", "definterface", "defmethod", "defn", "defmacro", "defprotocol", "defrecord", "defstruct", "deftype", "do", "doseq", "dotimes", "doto", "extend", "extend-protocol", "extend-type", "fn", "for", "future", "if", "if-let", "if-not", "if-some", "let", "letfn", "locking", "loop", "ns", "proxy", "reify", "struct-map", "some->", "some->>", "try", "when", "when-first", "when-let", "when-not", "when-some", "while", "with-bindings", "with-bindings*", "with-in-str", "with-loading-context", "with-local-vars", "with-meta", "with-open", "with-out-str", "with-precision", "with-redefs", "with-redefs-fn"]; CodeMirror.registerHelper("hintWords", "clojure", [].concat(atoms, specialForms, coreSymbols)); var atom = createLookupMap(atoms); var specialForm = createLookupMap(specialForms); var coreSymbol = createLookupMap(coreSymbols); var hasBodyParameter = createLookupMap(haveBodyParameter); var delimiter = /^(?:[\\\[\]\s"(),;@^`{}~]|$)/; var numberLiteral = /^(?:[+\-]?\d+(?:(?:N|(?:[eE][+\-]?\d+))|(?:\.?\d*(?:M|(?:[eE][+\-]?\d+))?)|\/\d+|[xX][0-9a-fA-F]+|r[0-9a-zA-Z]+)?(?=[\\\[\]\s"#'(),;@^`{}~]|$))/; 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"(),;@^`{}~]|$))/; // simple-namespace := /^[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*/ // simple-symbol := /^(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)/ // qualified-symbol := ((<.>)*)? var qualifiedSymbol = /^(?:(?:[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*(?:\.[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*\/)?(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*(?=[\\\[\]\s"(),;@^`{}~]|$))/; function base(stream, state) { if (stream.eatSpace()) return ["space", null]; if (stream.match(numberLiteral)) return [null, "number"]; if (stream.match(characterLiteral)) return [null, "string-2"]; if (stream.eat(/^"/)) return (state.tokenize = inString)(stream, state); if (stream.eat(/^[(\[{]/)) return ["open", "bracket"]; if (stream.eat(/^[)\]}]/)) return ["close", "bracket"]; if (stream.eat(/^;/)) {stream.skipToEnd(); return ["space", "comment"];} if (stream.eat(/^[#'@^`~]/)) return [null, "meta"]; var matches = stream.match(qualifiedSymbol); var symbol = matches && matches[0]; if (!symbol) { // advance stream by at least one character so we don't get stuck. stream.next(); stream.eatWhile(function (c) {return !is(c, delimiter);}); return [null, "error"]; } if (symbol === "comment" && state.lastToken === "(") return (state.tokenize = inComment)(stream, state); if (is(symbol, atom) || symbol.charAt(0) === ":") return ["symbol", "atom"]; if (is(symbol, specialForm) || is(symbol, coreSymbol)) return ["symbol", "keyword"]; if (state.lastToken === "(") return ["symbol", "builtin"]; // other operator return ["symbol", "variable"]; } function inString(stream, state) { var escaped = false, next; while (next = stream.next()) { if (next === "\"" && !escaped) {state.tokenize = base; break;} escaped = !escaped && next === "\\"; } return [null, "string"]; } function inComment(stream, state) { var parenthesisCount = 1; var next; while (next = stream.next()) { if (next === ")") parenthesisCount--; if (next === "(") parenthesisCount++; if (parenthesisCount === 0) { stream.backUp(1); state.tokenize = base; break; } } return ["space", "comment"]; } function createLookupMap(words) { var obj = {}; for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function is(value, test) { if (test instanceof RegExp) return test.test(value); if (test instanceof Object) return test.propertyIsEnumerable(value); } return { startState: function () { return { ctx: {prev: null, start: 0, indentTo: 0}, lastToken: null, tokenize: base }; }, token: function (stream, state) { if (stream.sol() && (typeof state.ctx.indentTo !== "number")) state.ctx.indentTo = state.ctx.start + 1; var typeStylePair = state.tokenize(stream, state); var type = typeStylePair[0]; var style = typeStylePair[1]; var current = stream.current(); if (type !== "space") { if (state.lastToken === "(" && state.ctx.indentTo === null) { if (type === "symbol" && is(current, hasBodyParameter)) state.ctx.indentTo = state.ctx.start + options.indentUnit; else state.ctx.indentTo = "next"; } else if (state.ctx.indentTo === "next") { state.ctx.indentTo = stream.column(); } state.lastToken = current; } if (type === "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null}; else if (type === "close") state.ctx = state.ctx.prev || state.ctx; return style; }, indent: function (state) { var i = state.ctx.indentTo; return (typeof i === "number") ? i : state.ctx.start + 1; }, closeBrackets: {pairs: "()[]{}\"\""}, lineComment: ";;" }; }); CodeMirror.defineMIME("text/x-clojure", "clojure"); CodeMirror.defineMIME("text/x-clojurescript", "clojure"); CodeMirror.defineMIME("application/edn", "clojure"); }); ================================================ FILE: third_party/CodeMirror/mode/clojure/index.html ================================================ CodeMirror: Clojure mode

Clojure mode

MIME types defined: text/x-clojure.

================================================ FILE: third_party/CodeMirror/mode/clojure/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function () { var mode = CodeMirror.getMode({indentUnit: 2}, "clojure"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("atoms", "[atom false]", "[atom nil]", "[atom true]" ); MT("keywords", "[atom :foo]", "[atom ::bar]", "[atom :foo/bar]", "[atom :foo.bar/baz]" ); MT("numbers", "[number 42] [number +42] [number -421]", "[number 42N] [number +42N] [number -42N]", "[number 0.42] [number +0.42] [number -0.42]", "[number 42M] [number +42M] [number -42M]", "[number 42.42M] [number +42.42M] [number -42.42M]", "[number 1/42] [number +1/42] [number -1/42]", "[number 0x42af] [number +0x42af] [number -0x42af]", "[number 0x42AF] [number +0x42AF] [number -0x42AF]", "[number 1e2] [number 1e+2] [number 1e-2]", "[number +1e2] [number +1e+2] [number +1e-2]", "[number -1e2] [number -1e+2] [number -1e-2]", "[number -1.0e2] [number -0.1e+2] [number -1.01e-2]", "[number 1E2] [number 1E+2] [number 1E-2]", "[number +1E2] [number +1E+2] [number +1E-2]", "[number -1E2] [number -1E+2] [number -1E-2]", "[number -1.0E2] [number -0.1E+2] [number -1.01E-2]", "[number 2r101010] [number +2r101010] [number -2r101010]", "[number 2r101010] [number +2r101010] [number -2r101010]", "[number 8r52] [number +8r52] [number -8r52]", "[number 36rhello] [number +36rhello] [number -36rhello]", "[number 36rz] [number +36rz] [number -36rz]", "[number 36rZ] [number +36rZ] [number -36rZ]", // invalid numbers "[error 42foo]", "[error 42Nfoo]", "[error 42Mfoo]", "[error 42.42Mfoo]", "[error 42.42M!]", "[error 42!]", "[error 0x42afm]" ); MT("characters", "[string-2 \\1]", "[string-2 \\a]", "[string-2 \\a\\b\\c]", "[string-2 \\#]", "[string-2 \\\\]", "[string-2 \\\"]", "[string-2 \\(]", "[string-2 \\A]", "[string-2 \\backspace]", "[string-2 \\formfeed]", "[string-2 \\newline]", "[string-2 \\space]", "[string-2 \\return]", "[string-2 \\tab]", "[string-2 \\u1000]", "[string-2 \\uAaAa]", "[string-2 \\u9F9F]", "[string-2 \\o123]", "[string-2 \\符]", "[string-2 \\シ]", "[string-2 \\ۇ]", // FIXME // "[string-2 \\🙂]", // invalid character literals "[error \\abc]", "[error \\a123]", "[error \\a!]", "[error \\newlines]", "[error \\NEWLINE]", "[error \\u9F9FF]", "[error \\o1234]" ); MT("strings", "[string \"I'm a teapot.\"]", "[string \"I'm a \\\"teapot\\\".\"]", "[string \"I'm]", // this is "[string a]", // a multi-line "[string teapot.\"]" // string // TODO unterminated (multi-line) strings? ); MT("comments", "[comment ; this is an in-line comment.]", "[comment ;; this is a line comment.]", "[keyword comment]", "[bracket (][comment comment (foo 1 2 3)][bracket )]" ); MT("reader macro characters", "[meta #][variable _]", "[meta #][variable -Inf]", "[meta ##][variable Inf]", "[meta ##][variable NaN]", "[meta @][variable x]", "[meta ^][bracket {][atom :tag] [variable String][bracket }]", "[meta `][bracket (][builtin f] [variable x][bracket )]", "[meta ~][variable foo#]", "[meta '][number 1]", "[meta '][atom :foo]", "[meta '][string \"foo\"]", "[meta '][variable x]", "[meta '][bracket (][builtin a] [variable b] [variable c][bracket )]", "[meta '][bracket [[][variable a] [variable b] [variable c][bracket ]]]", "[meta '][bracket {][variable a] [number 1] [atom :foo] [number 2] [variable c] [number 3][bracket }]", "[meta '#][bracket {][variable a] [number 1] [atom :foo][bracket }]" ); MT("symbols", "[variable foo!]", "[variable foo#]", "[variable foo$]", "[variable foo&]", "[variable foo']", "[variable foo*]", "[variable foo+]", "[variable foo-]", "[variable foo.]", "[variable foo/bar]", "[variable foo:bar]", "[variable foo<]", "[variable foo=]", "[variable foo>]", "[variable foo?]", "[variable foo_]", "[variable foo|]", "[variable foobarBaz]", "[variable foo¡]", "[variable 符号]", "[variable シンボル]", "[variable ئۇيغۇر]", "[variable 🙂❤🇺🇸]", // invalid symbols "[error 3foo]", "[error 3+]", "[error 3|]", "[error 3_]" ); MT("numbers and other forms", "[number 42][bracket (][builtin foo][bracket )]", "[number 42][bracket [[][variable foo][bracket ]]]", "[number 42][meta #][bracket {][variable foo][bracket }]", "[number 42][bracket {][atom :foo] [variable bar][bracket }]", "[number 42][meta `][variable foo]", "[number 42][meta ~][variable foo]", "[number 42][meta #][variable foo]" ); var specialForms = [".", "catch", "def", "do", "if", "monitor-enter", "monitor-exit", "new", "quote", "recur", "set!", "throw", "try", "var"]; MT("should highlight special forms as keywords", typeTokenPairs("keyword", specialForms) ); var coreSymbols1 = [ "*", "*'", "*1", "*2", "*3", "*agent*", "*allow-unresolved-vars*", "*assert*", "*clojure-version*", "*command-line-args*", "*compile-files*", "*compile-path*", "*compiler-options*", "*data-readers*", "*default-data-reader-fn*", "*e", "*err*", "*file*", "*flush-on-newline*", "*fn-loader*", "*in*", "*math-context*", "*ns*", "*out*", "*print-dup*", "*print-length*", "*print-level*", "*print-meta*", "*print-namespace-maps*", "*print-readably*", "*read-eval*", "*reader-resolver*", "*source-path*", "*suppress-read*", "*unchecked-math*", "*use-context-classloader*", "*verbose-defrecords*", "*warn-on-reflection*", "+", "+'", "-", "-'", "->", "->>", "->ArrayChunk", "->Eduction", "->Vec", "->VecNode", "->VecSeq", "-cache-protocol-fn", "-reset-methods", "..", "/", "<", "<=", "=", "==", ">", ">=", "EMPTY-NODE", "Inst", "StackTraceElement->vec", "Throwable->map", "accessor", "aclone", "add-classpath", "add-watch", "agent", "agent-error", "agent-errors", "aget", "alength", "alias", "all-ns", "alter", "alter-meta!", "alter-var-root", "amap", "ancestors", "and", "any?", "apply", "areduce", "array-map", "as->", "aset", "aset-boolean", "aset-byte", "aset-char", "aset-double", "aset-float", "aset-int", "aset-long", "aset-short", "assert", "assoc", "assoc!", "assoc-in", "associative?", "atom", "await", "await-for", "await1", "bases", "bean", "bigdec", "bigint", "biginteger", "binding", "bit-and", "bit-and-not", "bit-clear", "bit-flip", "bit-not", "bit-or", "bit-set", "bit-shift-left", "bit-shift-right", "bit-test", "bit-xor", "boolean", "boolean-array", "boolean?", "booleans", "bound-fn", "bound-fn*", "bound?", "bounded-count", "butlast", "byte", "byte-array", "bytes", "bytes?", "case", "cast", "cat", "char", "char-array", "char-escape-string", "char-name-string", "char?", "chars", "chunk", "chunk-append", "chunk-buffer", "chunk-cons", "chunk-first", "chunk-next", "chunk-rest", "chunked-seq?", "class", "class?", "clear-agent-errors", "clojure-version", "coll?", "comment", "commute", "comp", "comparator", "compare", "compare-and-set!", "compile", "complement", "completing", "concat", "cond", "cond->", "cond->>", "condp", "conj", "conj!", "cons", "constantly", "construct-proxy", "contains?", "count", "counted?", "create-ns", "create-struct", "cycle", "dec", "dec'", "decimal?", "declare", "dedupe", "default-data-readers", "definline", "definterface", "defmacro", "defmethod", "defmulti", "defn", "defn-", "defonce", "defprotocol", "defrecord", "defstruct", "deftype", "delay", "delay?", "deliver", "denominator", "deref", "derive", "descendants", "destructure", "disj", "disj!", "dissoc", "dissoc!", "distinct", "distinct?", "doall", "dorun", "doseq", "dosync", "dotimes", "doto", "double", "double-array", "double?", "doubles", "drop", "drop-last", "drop-while", "eduction", "empty", "empty?", "ensure", "ensure-reduced", "enumeration-seq", "error-handler", "error-mode", "eval", "even?", "every-pred", "every?", "ex-data", "ex-info", "extend", "extend-protocol", "extend-type", "extenders", "extends?", "false?", "ffirst", "file-seq", "filter", "filterv", "find", "find-keyword", "find-ns", "find-protocol-impl", "find-protocol-method", "find-var", "first", "flatten", "float", "float-array", "float?", "floats", "flush", "fn", "fn?", "fnext", "fnil", "for", "force", "format", "frequencies", "future", "future-call", "future-cancel", "future-cancelled?", "future-done?", "future?", "gen-class", "gen-interface", "gensym", "get", "get-in", "get-method", "get-proxy-class", "get-thread-bindings", "get-validator", "group-by", "halt-when", "hash", "hash-combine", "hash-map", "hash-ordered-coll", "hash-set", "hash-unordered-coll", "ident?", "identical?", "identity", "if-let", "if-not", "if-some", "ifn?", "import", "in-ns", "inc", "inc'", "indexed?", "init-proxy", "inst-ms", "inst-ms*", "inst?", "instance?", "int", "int-array", "int?", "integer?", "interleave", "intern", "interpose", "into", "into-array", "ints", "io!", "isa?", "iterate", "iterator-seq", "juxt", "keep", "keep-indexed", "key", "keys", "keyword", "keyword?", "last", "lazy-cat", "lazy-seq", "let", "letfn", "line-seq", "list", "list*", "list?", "load", "load-file", "load-reader", "load-string", "loaded-libs", "locking", "long", "long-array", "longs", "loop", "macroexpand", "macroexpand-1", "make-array", "make-hierarchy", "map", "map-entry?", "map-indexed", "map?", "mapcat", "mapv", "max", "max-key", "memfn", "memoize", "merge", "merge-with", "meta", "method-sig", "methods"]; var coreSymbols2 = [ "min", "min-key", "mix-collection-hash", "mod", "munge", "name", "namespace", "namespace-munge", "nat-int?", "neg-int?", "neg?", "newline", "next", "nfirst", "nil?", "nnext", "not", "not-any?", "not-empty", "not-every?", "not=", "ns", "ns-aliases", "ns-imports", "ns-interns", "ns-map", "ns-name", "ns-publics", "ns-refers", "ns-resolve", "ns-unalias", "ns-unmap", "nth", "nthnext", "nthrest", "num", "number?", "numerator", "object-array", "odd?", "or", "parents", "partial", "partition", "partition-all", "partition-by", "pcalls", "peek", "persistent!", "pmap", "pop", "pop!", "pop-thread-bindings", "pos-int?", "pos?", "pr", "pr-str", "prefer-method", "prefers", "primitives-classnames", "print", "print-ctor", "print-dup", "print-method", "print-simple", "print-str", "printf", "println", "println-str", "prn", "prn-str", "promise", "proxy", "proxy-call-with-super", "proxy-mappings", "proxy-name", "proxy-super", "push-thread-bindings", "pvalues", "qualified-ident?", "qualified-keyword?", "qualified-symbol?", "quot", "rand", "rand-int", "rand-nth", "random-sample", "range", "ratio?", "rational?", "rationalize", "re-find", "re-groups", "re-matcher", "re-matches", "re-pattern", "re-seq", "read", "read-line", "read-string", "reader-conditional", "reader-conditional?", "realized?", "record?", "reduce", "reduce-kv", "reduced", "reduced?", "reductions", "ref", "ref-history-count", "ref-max-history", "ref-min-history", "ref-set", "refer", "refer-clojure", "reify", "release-pending-sends", "rem", "remove", "remove-all-methods", "remove-method", "remove-ns", "remove-watch", "repeat", "repeatedly", "replace", "replicate", "require", "reset!", "reset-meta!", "reset-vals!", "resolve", "rest", "restart-agent", "resultset-seq", "reverse", "reversible?", "rseq", "rsubseq", "run!", "satisfies?", "second", "select-keys", "send", "send-off", "send-via", "seq", "seq?", "seqable?", "seque", "sequence", "sequential?", "set", "set-agent-send-executor!", "set-agent-send-off-executor!", "set-error-handler!", "set-error-mode!", "set-validator!", "set?", "short", "short-array", "shorts", "shuffle", "shutdown-agents", "simple-ident?", "simple-keyword?", "simple-symbol?", "slurp", "some", "some->", "some->>", "some-fn", "some?", "sort", "sort-by", "sorted-map", "sorted-map-by", "sorted-set", "sorted-set-by", "sorted?", "special-symbol?", "spit", "split-at", "split-with", "str", "string?", "struct", "struct-map", "subs", "subseq", "subvec", "supers", "swap!", "swap-vals!", "symbol", "symbol?", "sync", "tagged-literal", "tagged-literal?", "take", "take-last", "take-nth", "take-while", "test", "the-ns", "thread-bound?", "time", "to-array", "to-array-2d", "trampoline", "transduce", "transient", "tree-seq", "true?", "type", "unchecked-add", "unchecked-add-int", "unchecked-byte", "unchecked-char", "unchecked-dec", "unchecked-dec-int", "unchecked-divide-int", "unchecked-double", "unchecked-float", "unchecked-inc", "unchecked-inc-int", "unchecked-int", "unchecked-long", "unchecked-multiply", "unchecked-multiply-int", "unchecked-negate", "unchecked-negate-int", "unchecked-remainder-int", "unchecked-short", "unchecked-subtract", "unchecked-subtract-int", "underive", "unquote", "unquote-splicing", "unreduced", "unsigned-bit-shift-right", "update", "update-in", "update-proxy", "uri?", "use", "uuid?", "val", "vals", "var-get", "var-set", "var?", "vary-meta", "vec", "vector", "vector-of", "vector?", "volatile!", "volatile?", "vreset!", "vswap!", "when", "when-first", "when-let", "when-not", "when-some", "while", "with-bindings", "with-bindings*", "with-in-str", "with-loading-context", "with-local-vars", "with-meta", "with-open", "with-out-str", "with-precision", "with-redefs", "with-redefs-fn", "xml-seq", "zero?", "zipmap" ]; MT("should highlight core symbols as keywords (part 1/2)", typeTokenPairs("keyword", coreSymbols1) ); MT("should highlight core symbols as keywords (part 2/2)", typeTokenPairs("keyword", coreSymbols2) ); MT("should properly indent forms in list literals", "[bracket (][builtin foo] [atom :a] [number 1] [atom true] [atom nil][bracket )]", "", "[bracket (][builtin foo] [atom :a]", " [number 1]", " [atom true]", " [atom nil][bracket )]", "", "[bracket (][builtin foo] [atom :a] [number 1]", " [atom true]", " [atom nil][bracket )]", "", "[bracket (]", " [builtin foo]", " [atom :a]", " [number 1]", " [atom true]", " [atom nil][bracket )]", "", "[bracket (][builtin foo] [bracket [[][atom :a][bracket ]]]", " [number 1]", " [atom true]", " [atom nil][bracket )]" ); MT("should properly indent forms in vector literals", "[bracket [[][atom :a] [number 1] [atom true] [atom nil][bracket ]]]", "", "[bracket [[][atom :a]", " [number 1]", " [atom true]", " [atom nil][bracket ]]]", "", "[bracket [[][atom :a] [number 1]", " [atom true]", " [atom nil][bracket ]]]", "", "[bracket [[]", " [variable foo]", " [atom :a]", " [number 1]", " [atom true]", " [atom nil][bracket ]]]" ); MT("should properly indent forms in map literals", "[bracket {][atom :a] [atom :a] [atom :b] [number 1] [atom :c] [atom true] [atom :d] [atom nil] [bracket }]", "", "[bracket {][atom :a] [atom :a]", " [atom :b] [number 1]", " [atom :c] [atom true]", " [atom :d] [atom nil][bracket }]", "", "[bracket {][atom :a]", " [atom :a]", " [atom :b]", " [number 1]", " [atom :c]", " [atom true]", " [atom :d]", " [atom nil][bracket }]", "", "[bracket {]", " [atom :a] [atom :a]", " [atom :b] [number 1]", " [atom :c] [atom true]", " [atom :d] [atom nil][bracket }]" ); MT("should properly indent forms in set literals", "[meta #][bracket {][atom :a] [number 1] [atom true] [atom nil] [bracket }]", "", "[meta #][bracket {][atom :a]", " [number 1]", " [atom true]", " [atom nil][bracket }]", "", "[meta #][bracket {]", " [atom :a]", " [number 1]", " [atom true]", " [atom nil][bracket }]" ); var haveBodyParameter = [ "->", "->>", "as->", "binding", "bound-fn", "case", "catch", "cond", "cond->", "cond->>", "condp", "def", "definterface", "defmethod", "defn", "defmacro", "defprotocol", "defrecord", "defstruct", "deftype", "do", "doseq", "dotimes", "doto", "extend", "extend-protocol", "extend-type", "fn", "for", "future", "if", "if-let", "if-not", "if-some", "let", "letfn", "locking", "loop", "ns", "proxy", "reify", "some->", "some->>", "struct-map", "try", "when", "when-first", "when-let", "when-not", "when-some", "while", "with-bindings", "with-bindings*", "with-in-str", "with-loading-context", "with-local-vars", "with-meta", "with-open", "with-out-str", "with-precision", "with-redefs", "with-redefs-fn"]; function testFormsThatHaveBodyParameter(forms) { for (var i = 0; i < forms.length; i++) { MT("should indent body argument of `" + forms[i] + "` by `options.indentUnit` spaces", "[bracket (][keyword " + forms[i] + "] [variable foo] [variable bar]", " [variable baz]", " [variable qux][bracket )]" ); } } testFormsThatHaveBodyParameter(haveBodyParameter); MT("should indent body argument of `comment` by `options.indentUnit` spaces", "[bracket (][comment comment foo bar]", "[comment baz]", "[comment qux][bracket )]" ); function typeTokenPairs(type, tokens) { return "[" + type + " " + tokens.join("] [" + type + " ") + "]"; } })(); ================================================ FILE: third_party/CodeMirror/mode/cmake/cmake.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) define(["../../lib/codemirror"], mod); else mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("cmake", function () { var variable_regex = /({)?[a-zA-Z0-9_]+(})?/; function tokenString(stream, state) { var current, prev, found_var = false; while (!stream.eol() && (current = stream.next()) != state.pending) { if (current === '$' && prev != '\\' && state.pending == '"') { found_var = true; break; } prev = current; } if (found_var) { stream.backUp(1); } if (current == state.pending) { state.continueString = false; } else { state.continueString = true; } return "string"; } function tokenize(stream, state) { var ch = stream.next(); // Have we found a variable? if (ch === '$') { if (stream.match(variable_regex)) { return 'variable-2'; } return 'variable'; } // Should we still be looking for the end of a string? if (state.continueString) { // If so, go through the loop again stream.backUp(1); return tokenString(stream, state); } // Do we just have a function on our hands? // In 'cmake_minimum_required (VERSION 2.8.8)', 'cmake_minimum_required' is matched if (stream.match(/(\s+)?\w+\(/) || stream.match(/(\s+)?\w+\ \(/)) { stream.backUp(1); return 'def'; } if (ch == "#") { stream.skipToEnd(); return "comment"; } // Have we found a string? if (ch == "'" || ch == '"') { // Store the type (single or double) state.pending = ch; // Perform the looping function to find the end return tokenString(stream, state); } if (ch == '(' || ch == ')') { return 'bracket'; } if (ch.match(/[0-9]/)) { return 'number'; } stream.eatWhile(/[\w-]/); return null; } return { startState: function () { var state = {}; state.inDefinition = false; state.inInclude = false; state.continueString = false; state.pending = false; return state; }, token: function (stream, state) { if (stream.eatSpace()) return null; return tokenize(stream, state); } }; }); CodeMirror.defineMIME("text/x-cmake", "cmake"); }); ================================================ FILE: third_party/CodeMirror/mode/cmake/index.html ================================================ CodeMirror: CMake mode

CMake mode

MIME types defined: text/x-cmake.

================================================ FILE: third_party/CodeMirror/mode/cobol/cobol.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /** * Author: Gautam Mehta * Branched from CodeMirror's Scheme mode */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("cobol", function () { var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", ATOM = "atom", NUMBER = "number", KEYWORD = "keyword", MODTAG = "header", COBOLLINENUM = "def", PERIOD = "link"; function makeKeywords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var atoms = makeKeywords("TRUE FALSE ZEROES ZEROS ZERO SPACES SPACE LOW-VALUE LOW-VALUES "); var keywords = makeKeywords( "ACCEPT ACCESS ACQUIRE ADD ADDRESS " + "ADVANCING AFTER ALIAS ALL ALPHABET " + "ALPHABETIC ALPHABETIC-LOWER ALPHABETIC-UPPER ALPHANUMERIC ALPHANUMERIC-EDITED " + "ALSO ALTER ALTERNATE AND ANY " + "ARE AREA AREAS ARITHMETIC ASCENDING " + "ASSIGN AT ATTRIBUTE AUTHOR AUTO " + "AUTO-SKIP AUTOMATIC B-AND B-EXOR B-LESS " + "B-NOT B-OR BACKGROUND-COLOR BACKGROUND-COLOUR BEEP " + "BEFORE BELL BINARY BIT BITS " + "BLANK BLINK BLOCK BOOLEAN BOTTOM " + "BY CALL CANCEL CD CF " + "CH CHARACTER CHARACTERS CLASS CLOCK-UNITS " + "CLOSE COBOL CODE CODE-SET COL " + "COLLATING COLUMN COMMA COMMIT COMMITMENT " + "COMMON COMMUNICATION COMP COMP-0 COMP-1 " + "COMP-2 COMP-3 COMP-4 COMP-5 COMP-6 " + "COMP-7 COMP-8 COMP-9 COMPUTATIONAL COMPUTATIONAL-0 " + "COMPUTATIONAL-1 COMPUTATIONAL-2 COMPUTATIONAL-3 COMPUTATIONAL-4 COMPUTATIONAL-5 " + "COMPUTATIONAL-6 COMPUTATIONAL-7 COMPUTATIONAL-8 COMPUTATIONAL-9 COMPUTE " + "CONFIGURATION CONNECT CONSOLE CONTAINED CONTAINS " + "CONTENT CONTINUE CONTROL CONTROL-AREA CONTROLS " + "CONVERTING COPY CORR CORRESPONDING COUNT " + "CRT CRT-UNDER CURRENCY CURRENT CURSOR " + "DATA DATE DATE-COMPILED DATE-WRITTEN DAY " + "DAY-OF-WEEK DB DB-ACCESS-CONTROL-KEY DB-DATA-NAME DB-EXCEPTION " + "DB-FORMAT-NAME DB-RECORD-NAME DB-SET-NAME DB-STATUS DBCS " + "DBCS-EDITED DE DEBUG-CONTENTS DEBUG-ITEM DEBUG-LINE " + "DEBUG-NAME DEBUG-SUB-1 DEBUG-SUB-2 DEBUG-SUB-3 DEBUGGING " + "DECIMAL-POINT DECLARATIVES DEFAULT DELETE DELIMITED " + "DELIMITER DEPENDING DESCENDING DESCRIBED DESTINATION " + "DETAIL DISABLE DISCONNECT DISPLAY DISPLAY-1 " + "DISPLAY-2 DISPLAY-3 DISPLAY-4 DISPLAY-5 DISPLAY-6 " + "DISPLAY-7 DISPLAY-8 DISPLAY-9 DIVIDE DIVISION " + "DOWN DROP DUPLICATE DUPLICATES DYNAMIC " + "EBCDIC EGI EJECT ELSE EMI " + "EMPTY EMPTY-CHECK ENABLE END END. END-ACCEPT END-ACCEPT. " + "END-ADD END-CALL END-COMPUTE END-DELETE END-DISPLAY " + "END-DIVIDE END-EVALUATE END-IF END-INVOKE END-MULTIPLY " + "END-OF-PAGE END-PERFORM END-READ END-RECEIVE END-RETURN " + "END-REWRITE END-SEARCH END-START END-STRING END-SUBTRACT " + "END-UNSTRING END-WRITE END-XML ENTER ENTRY " + "ENVIRONMENT EOP EQUAL EQUALS ERASE " + "ERROR ESI EVALUATE EVERY EXCEEDS " + "EXCEPTION EXCLUSIVE EXIT EXTEND EXTERNAL " + "EXTERNALLY-DESCRIBED-KEY FD FETCH FILE FILE-CONTROL " + "FILE-STREAM FILES FILLER FINAL FIND " + "FINISH FIRST FOOTING FOR FOREGROUND-COLOR " + "FOREGROUND-COLOUR FORMAT FREE FROM FULL " + "FUNCTION GENERATE GET GIVING GLOBAL " + "GO GOBACK GREATER GROUP HEADING " + "HIGH-VALUE HIGH-VALUES HIGHLIGHT I-O I-O-CONTROL " + "ID IDENTIFICATION IF IN INDEX " + "INDEX-1 INDEX-2 INDEX-3 INDEX-4 INDEX-5 " + "INDEX-6 INDEX-7 INDEX-8 INDEX-9 INDEXED " + "INDIC INDICATE INDICATOR INDICATORS INITIAL " + "INITIALIZE INITIATE INPUT INPUT-OUTPUT INSPECT " + "INSTALLATION INTO INVALID INVOKE IS " + "JUST JUSTIFIED KANJI KEEP KEY " + "LABEL LAST LD LEADING LEFT " + "LEFT-JUSTIFY LENGTH LENGTH-CHECK LESS LIBRARY " + "LIKE LIMIT LIMITS LINAGE LINAGE-COUNTER " + "LINE LINE-COUNTER LINES LINKAGE LOCAL-STORAGE " + "LOCALE LOCALLY LOCK " + "MEMBER MEMORY MERGE MESSAGE METACLASS " + "MODE MODIFIED MODIFY MODULES MOVE " + "MULTIPLE MULTIPLY NATIONAL NATIVE NEGATIVE " + "NEXT NO NO-ECHO NONE NOT " + "NULL NULL-KEY-MAP NULL-MAP NULLS NUMBER " + "NUMERIC NUMERIC-EDITED OBJECT OBJECT-COMPUTER OCCURS " + "OF OFF OMITTED ON ONLY " + "OPEN OPTIONAL OR ORDER ORGANIZATION " + "OTHER OUTPUT OVERFLOW OWNER PACKED-DECIMAL " + "PADDING PAGE PAGE-COUNTER PARSE PERFORM " + "PF PH PIC PICTURE PLUS " + "POINTER POSITION POSITIVE PREFIX PRESENT " + "PRINTING PRIOR PROCEDURE PROCEDURE-POINTER PROCEDURES " + "PROCEED PROCESS PROCESSING PROGRAM PROGRAM-ID " + "PROMPT PROTECTED PURGE QUEUE QUOTE " + "QUOTES RANDOM RD READ READY " + "REALM RECEIVE RECONNECT RECORD RECORD-NAME " + "RECORDS RECURSIVE REDEFINES REEL REFERENCE " + "REFERENCE-MONITOR REFERENCES RELATION RELATIVE RELEASE " + "REMAINDER REMOVAL RENAMES REPEATED REPLACE " + "REPLACING REPORT REPORTING REPORTS REPOSITORY " + "REQUIRED RERUN RESERVE RESET RETAINING " + "RETRIEVAL RETURN RETURN-CODE RETURNING REVERSE-VIDEO " + "REVERSED REWIND REWRITE RF RH " + "RIGHT RIGHT-JUSTIFY ROLLBACK ROLLING ROUNDED " + "RUN SAME SCREEN SD SEARCH " + "SECTION SECURE SECURITY SEGMENT SEGMENT-LIMIT " + "SELECT SEND SENTENCE SEPARATE SEQUENCE " + "SEQUENTIAL SET SHARED SIGN SIZE " + "SKIP1 SKIP2 SKIP3 SORT SORT-MERGE " + "SORT-RETURN SOURCE SOURCE-COMPUTER SPACE-FILL " + "SPECIAL-NAMES STANDARD STANDARD-1 STANDARD-2 " + "START STARTING STATUS STOP STORE " + "STRING SUB-QUEUE-1 SUB-QUEUE-2 SUB-QUEUE-3 SUB-SCHEMA " + "SUBFILE SUBSTITUTE SUBTRACT SUM SUPPRESS " + "SYMBOLIC SYNC SYNCHRONIZED SYSIN SYSOUT " + "TABLE TALLYING TAPE TENANT TERMINAL " + "TERMINATE TEST TEXT THAN THEN " + "THROUGH THRU TIME TIMES TITLE " + "TO TOP TRAILING TRAILING-SIGN TRANSACTION " + "TYPE TYPEDEF UNDERLINE UNEQUAL UNIT " + "UNSTRING UNTIL UP UPDATE UPON " + "USAGE USAGE-MODE USE USING VALID " + "VALIDATE VALUE VALUES VARYING VLR " + "WAIT WHEN WHEN-COMPILED WITH WITHIN " + "WORDS WORKING-STORAGE WRITE XML XML-CODE " + "XML-EVENT XML-NTEXT XML-TEXT ZERO ZERO-FILL " ); var builtins = makeKeywords("- * ** / + < <= = > >= "); var tests = { digit: /\d/, digit_or_colon: /[\d:]/, hex: /[0-9a-f]/i, sign: /[+-]/, exponent: /e/i, keyword_char: /[^\s\(\[\;\)\]]/, symbol: /[\w*+\-]/ }; function isNumber(ch, stream){ // hex if ( ch === '0' && stream.eat(/x/i) ) { stream.eatWhile(tests.hex); return true; } // leading sign if ( ( ch == '+' || ch == '-' ) && ( tests.digit.test(stream.peek()) ) ) { stream.eat(tests.sign); ch = stream.next(); } if ( tests.digit.test(ch) ) { stream.eat(ch); stream.eatWhile(tests.digit); if ( '.' == stream.peek()) { stream.eat('.'); stream.eatWhile(tests.digit); } if ( stream.eat(tests.exponent) ) { stream.eat(tests.sign); stream.eatWhile(tests.digit); } return true; } return false; } return { startState: function () { return { indentStack: null, indentation: 0, mode: false }; }, token: function (stream, state) { if (state.indentStack == null && stream.sol()) { // update indentation, but only if indentStack is empty state.indentation = 6 ; //stream.indentation(); } // skip spaces if (stream.eatSpace()) { return null; } var returnType = null; switch(state.mode){ case "string": // multi-line string parsing mode var next = false; while ((next = stream.next()) != null) { if (next == "\"" || next == "\'") { state.mode = false; break; } } returnType = STRING; // continue on in string mode break; default: // default parsing mode var ch = stream.next(); var col = stream.column(); if (col >= 0 && col <= 5) { returnType = COBOLLINENUM; } else if (col >= 72 && col <= 79) { stream.skipToEnd(); returnType = MODTAG; } else if (ch == "*" && col == 6) { // comment stream.skipToEnd(); // rest of the line is a comment returnType = COMMENT; } else if (ch == "\"" || ch == "\'") { state.mode = "string"; returnType = STRING; } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) { returnType = ATOM; } else if (ch == ".") { returnType = PERIOD; } else if (isNumber(ch,stream)){ returnType = NUMBER; } else { if (stream.current().match(tests.symbol)) { while (col < 71) { if (stream.eat(tests.symbol) === undefined) { break; } else { col++; } } } if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) { returnType = KEYWORD; } else if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) { returnType = BUILTIN; } else if (atoms && atoms.propertyIsEnumerable(stream.current().toUpperCase())) { returnType = ATOM; } else returnType = null; } } return returnType; }, indent: function (state) { if (state.indentStack == null) return state.indentation; return state.indentStack.indent; } }; }); CodeMirror.defineMIME("text/x-cobol", "cobol"); }); ================================================ FILE: third_party/CodeMirror/mode/cobol/index.html ================================================ CodeMirror: COBOL mode

COBOL mode

Select Theme Select Font Size

================================================ FILE: third_party/CodeMirror/mode/coffeescript/coffeescript.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /** * Link to the project's GitHub page: * https://github.com/pickhardt/coffeescript-codemirror-mode */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("coffeescript", function(conf, parserConf) { var ERRORCLASS = "error"; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); } var operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&&|\?)=)/; var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/; var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/; var atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/; var wordOperators = wordRegexp(["and", "or", "not", "is", "isnt", "in", "instanceof", "typeof"]); var indentKeywords = ["for", "while", "loop", "if", "unless", "else", "switch", "try", "catch", "finally", "class"]; var commonKeywords = ["break", "by", "continue", "debugger", "delete", "do", "in", "of", "new", "return", "then", "this", "@", "throw", "when", "until", "extends"]; var keywords = wordRegexp(indentKeywords.concat(commonKeywords)); indentKeywords = wordRegexp(indentKeywords); var stringPrefixes = /^('{3}|\"{3}|['\"])/; var regexPrefixes = /^(\/{3}|\/)/; var commonConstants = ["Infinity", "NaN", "undefined", "null", "true", "false", "on", "off", "yes", "no"]; var constants = wordRegexp(commonConstants); // Tokenizers function tokenBase(stream, state) { // Handle scope changes if (stream.sol()) { if (state.scope.align === null) state.scope.align = false; var scopeOffset = state.scope.offset; if (stream.eatSpace()) { var lineOffset = stream.indentation(); if (lineOffset > scopeOffset && state.scope.type == "coffee") { return "indent"; } else if (lineOffset < scopeOffset) { return "dedent"; } return null; } else { if (scopeOffset > 0) { dedent(stream, state); } } } if (stream.eatSpace()) { return null; } var ch = stream.peek(); // Handle docco title comment (single line) if (stream.match("####")) { stream.skipToEnd(); return "comment"; } // Handle multi line comments if (stream.match("###")) { state.tokenize = longComment; return state.tokenize(stream, state); } // Single line comment if (ch === "#") { stream.skipToEnd(); return "comment"; } // Handle number literals if (stream.match(/^-?[0-9\.]/, false)) { var floatLiteral = false; // Floats if (stream.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } if (stream.match(/^-?\d+\.\d*/)) { floatLiteral = true; } if (stream.match(/^-?\.\d+/)) { floatLiteral = true; } if (floatLiteral) { // prevent from getting extra . on 1.. if (stream.peek() == "."){ stream.backUp(1); } return "number"; } // Integers var intLiteral = false; // Hex if (stream.match(/^-?0x[0-9a-f]+/i)) { intLiteral = true; } // Decimal if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) { intLiteral = true; } // Zero by itself with no other piece of number. if (stream.match(/^-?0(?![\dx])/i)) { intLiteral = true; } if (intLiteral) { return "number"; } } // Handle strings if (stream.match(stringPrefixes)) { state.tokenize = tokenFactory(stream.current(), false, "string"); return state.tokenize(stream, state); } // Handle regex literals if (stream.match(regexPrefixes)) { if (stream.current() != "/" || stream.match(/^.*\//, false)) { // prevent highlight of division state.tokenize = tokenFactory(stream.current(), true, "string-2"); return state.tokenize(stream, state); } else { stream.backUp(1); } } // Handle operators and delimiters if (stream.match(operators) || stream.match(wordOperators)) { return "operator"; } if (stream.match(delimiters)) { return "punctuation"; } if (stream.match(constants)) { return "atom"; } if (stream.match(atProp) || state.prop && stream.match(identifiers)) { return "property"; } if (stream.match(keywords)) { return "keyword"; } if (stream.match(identifiers)) { return "variable"; } // Handle non-detected items stream.next(); return ERRORCLASS; } function tokenFactory(delimiter, singleline, outclass) { return function(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^'"\/\\]/); if (stream.eat("\\")) { stream.next(); if (singleline && stream.eol()) { return outclass; } } else if (stream.match(delimiter)) { state.tokenize = tokenBase; return outclass; } else { stream.eat(/['"\/]/); } } if (singleline) { if (parserConf.singleLineStringErrors) { outclass = ERRORCLASS; } else { state.tokenize = tokenBase; } } return outclass; }; } function longComment(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^#]/); if (stream.match("###")) { state.tokenize = tokenBase; break; } stream.eatWhile("#"); } return "comment"; } function indent(stream, state, type) { type = type || "coffee"; var offset = 0, align = false, alignOffset = null; for (var scope = state.scope; scope; scope = scope.prev) { if (scope.type === "coffee" || scope.type == "}") { offset = scope.offset + conf.indentUnit; break; } } if (type !== "coffee") { align = null; alignOffset = stream.column() + stream.current().length; } else if (state.scope.align) { state.scope.align = false; } state.scope = { offset: offset, type: type, prev: state.scope, align: align, alignOffset: alignOffset }; } function dedent(stream, state) { if (!state.scope.prev) return; if (state.scope.type === "coffee") { var _indent = stream.indentation(); var matched = false; for (var scope = state.scope; scope; scope = scope.prev) { if (_indent === scope.offset) { matched = true; break; } } if (!matched) { return true; } while (state.scope.prev && state.scope.offset !== _indent) { state.scope = state.scope.prev; } return false; } else { state.scope = state.scope.prev; return false; } } function tokenLexer(stream, state) { var style = state.tokenize(stream, state); var current = stream.current(); // Handle scope changes. if (current === "return") { state.dedent = true; } if (((current === "->" || current === "=>") && stream.eol()) || style === "indent") { indent(stream, state); } var delimiter_index = "[({".indexOf(current); if (delimiter_index !== -1) { indent(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); } if (indentKeywords.exec(current)){ indent(stream, state); } if (current == "then"){ dedent(stream, state); } if (style === "dedent") { if (dedent(stream, state)) { return ERRORCLASS; } } delimiter_index = "])}".indexOf(current); if (delimiter_index !== -1) { while (state.scope.type == "coffee" && state.scope.prev) state.scope = state.scope.prev; if (state.scope.type == current) state.scope = state.scope.prev; } if (state.dedent && stream.eol()) { if (state.scope.type == "coffee" && state.scope.prev) state.scope = state.scope.prev; state.dedent = false; } return style; } var external = { startState: function(basecolumn) { return { tokenize: tokenBase, scope: {offset:basecolumn || 0, type:"coffee", prev: null, align: false}, prop: false, dedent: 0 }; }, token: function(stream, state) { var fillAlign = state.scope.align === null && state.scope; if (fillAlign && stream.sol()) fillAlign.align = false; var style = tokenLexer(stream, state); if (style && style != "comment") { if (fillAlign) fillAlign.align = true; state.prop = style == "punctuation" && stream.current() == "." } return style; }, indent: function(state, text) { if (state.tokenize != tokenBase) return 0; var scope = state.scope; var closer = text && "])}".indexOf(text.charAt(0)) > -1; if (closer) while (scope.type == "coffee" && scope.prev) scope = scope.prev; var closes = closer && scope.type === text.charAt(0); if (scope.align) return scope.alignOffset - (closes ? 1 : 0); else return (closes ? scope.prev : scope).offset; }, lineComment: "#", fold: "indent" }; return external; }); // IANA registered media type // https://www.iana.org/assignments/media-types/ CodeMirror.defineMIME("application/vnd.coffeescript", "coffeescript"); CodeMirror.defineMIME("text/x-coffeescript", "coffeescript"); CodeMirror.defineMIME("text/coffeescript", "coffeescript"); }); ================================================ FILE: third_party/CodeMirror/mode/coffeescript/index.html ================================================ CodeMirror: CoffeeScript mode

CoffeeScript mode

MIME types defined: application/vnd.coffeescript, text/coffeescript, text/x-coffeescript.

The CoffeeScript mode was written by Jeff Pickhardt.

================================================ FILE: third_party/CodeMirror/mode/commonlisp/commonlisp.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("commonlisp", function (config) { 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)$/; var assumeBody = /^with|^def|^do|^prog|case$|^cond$|bind$|when$|unless$/; var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/; var symbol = /[^\s'`,@()\[\]";]/; var type; function readSym(stream) { var ch; while (ch = stream.next()) { if (ch == "\\") stream.next(); else if (!symbol.test(ch)) { stream.backUp(1); break; } } return stream.current(); } function base(stream, state) { if (stream.eatSpace()) {type = "ws"; return null;} if (stream.match(numLiteral)) return "number"; var ch = stream.next(); if (ch == "\\") ch = stream.next(); if (ch == '"') return (state.tokenize = inString)(stream, state); else if (ch == "(") { type = "open"; return "bracket"; } else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; } else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; } else if (/['`,@]/.test(ch)) return null; else if (ch == "|") { if (stream.skipTo("|")) { stream.next(); return "symbol"; } else { stream.skipToEnd(); return "error"; } } else if (ch == "#") { var ch = stream.next(); if (ch == "(") { type = "open"; return "bracket"; } else if (/[+\-=\.']/.test(ch)) return null; else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null; else if (ch == "|") return (state.tokenize = inComment)(stream, state); else if (ch == ":") { readSym(stream); return "meta"; } else if (ch == "\\") { stream.next(); readSym(stream); return "string-2" } else return "error"; } else { var name = readSym(stream); if (name == ".") return null; type = "symbol"; if (name == "nil" || name == "t" || name.charAt(0) == ":") return "atom"; if (state.lastType == "open" && (specialForm.test(name) || assumeBody.test(name))) return "keyword"; if (name.charAt(0) == "&") return "variable-2"; return "variable"; } } function inString(stream, state) { var escaped = false, next; while (next = stream.next()) { if (next == '"' && !escaped) { state.tokenize = base; break; } escaped = !escaped && next == "\\"; } return "string"; } function inComment(stream, state) { var next, last; while (next = stream.next()) { if (next == "#" && last == "|") { state.tokenize = base; break; } last = next; } type = "ws"; return "comment"; } return { startState: function () { return {ctx: {prev: null, start: 0, indentTo: 0}, lastType: null, tokenize: base}; }, token: function (stream, state) { if (stream.sol() && typeof state.ctx.indentTo != "number") state.ctx.indentTo = state.ctx.start + 1; type = null; var style = state.tokenize(stream, state); if (type != "ws") { if (state.ctx.indentTo == null) { if (type == "symbol" && assumeBody.test(stream.current())) state.ctx.indentTo = state.ctx.start + config.indentUnit; else state.ctx.indentTo = "next"; } else if (state.ctx.indentTo == "next") { state.ctx.indentTo = stream.column(); } state.lastType = type; } if (type == "open") state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null}; else if (type == "close") state.ctx = state.ctx.prev || state.ctx; return style; }, indent: function (state, _textAfter) { var i = state.ctx.indentTo; return typeof i == "number" ? i : state.ctx.start + 1; }, closeBrackets: {pairs: "()[]{}\"\""}, lineComment: ";;", blockCommentStart: "#|", blockCommentEnd: "|#" }; }); CodeMirror.defineMIME("text/x-common-lisp", "commonlisp"); }); ================================================ FILE: third_party/CodeMirror/mode/commonlisp/index.html ================================================ CodeMirror: Common Lisp mode

Common Lisp mode

MIME types defined: text/x-common-lisp.

================================================ FILE: third_party/CodeMirror/mode/crystal/crystal.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("crystal", function(config) { function wordRegExp(words, end) { return new RegExp((end ? "" : "^") + "(?:" + words.join("|") + ")" + (end ? "$" : "\\b")); } function chain(tokenize, stream, state) { state.tokenize.push(tokenize); return tokenize(stream, state); } var operators = /^(?:[-+/%|&^]|\*\*?|[<>]{2})/; var conditionalOperators = /^(?:[=!]~|===|<=>|[<>=!]=?|[|&]{2}|~)/; var indexingOperators = /^(?:\[\][?=]?)/; var anotherOperators = /^(?:\.(?:\.{2})?|->|[?:])/; var idents = /^[a-z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/; var types = /^[A-Z_\u009F-\uFFFF][a-zA-Z0-9_\u009F-\uFFFF]*/; var keywords = wordRegExp([ "abstract", "alias", "as", "asm", "begin", "break", "case", "class", "def", "do", "else", "elsif", "end", "ensure", "enum", "extend", "for", "fun", "if", "include", "instance_sizeof", "lib", "macro", "module", "next", "of", "out", "pointerof", "private", "protected", "rescue", "return", "require", "select", "sizeof", "struct", "super", "then", "type", "typeof", "uninitialized", "union", "unless", "until", "when", "while", "with", "yield", "__DIR__", "__END_LINE__", "__FILE__", "__LINE__" ]); var atomWords = wordRegExp(["true", "false", "nil", "self"]); var indentKeywordsArray = [ "def", "fun", "macro", "class", "module", "struct", "lib", "enum", "union", "do", "for" ]; var indentKeywords = wordRegExp(indentKeywordsArray); var indentExpressionKeywordsArray = ["if", "unless", "case", "while", "until", "begin", "then"]; var indentExpressionKeywords = wordRegExp(indentExpressionKeywordsArray); var dedentKeywordsArray = ["end", "else", "elsif", "rescue", "ensure"]; var dedentKeywords = wordRegExp(dedentKeywordsArray); var dedentPunctualsArray = ["\\)", "\\}", "\\]"]; var dedentPunctuals = new RegExp("^(?:" + dedentPunctualsArray.join("|") + ")$"); var nextTokenizer = { "def": tokenFollowIdent, "fun": tokenFollowIdent, "macro": tokenMacroDef, "class": tokenFollowType, "module": tokenFollowType, "struct": tokenFollowType, "lib": tokenFollowType, "enum": tokenFollowType, "union": tokenFollowType }; var matching = {"[": "]", "{": "}", "(": ")", "<": ">"}; function tokenBase(stream, state) { if (stream.eatSpace()) { return null; } // Macros if (state.lastToken != "\\" && stream.match("{%", false)) { return chain(tokenMacro("%", "%"), stream, state); } if (state.lastToken != "\\" && stream.match("{{", false)) { return chain(tokenMacro("{", "}"), stream, state); } // Comments if (stream.peek() == "#") { stream.skipToEnd(); return "comment"; } // Variables and keywords var matched; if (stream.match(idents)) { stream.eat(/[?!]/); matched = stream.current(); if (stream.eat(":")) { return "atom"; } else if (state.lastToken == ".") { return "property"; } else if (keywords.test(matched)) { if (indentKeywords.test(matched)) { if (!(matched == "fun" && state.blocks.indexOf("lib") >= 0) && !(matched == "def" && state.lastToken == "abstract")) { state.blocks.push(matched); state.currentIndent += 1; } } else if ((state.lastStyle == "operator" || !state.lastStyle) && indentExpressionKeywords.test(matched)) { state.blocks.push(matched); state.currentIndent += 1; } else if (matched == "end") { state.blocks.pop(); state.currentIndent -= 1; } if (nextTokenizer.hasOwnProperty(matched)) { state.tokenize.push(nextTokenizer[matched]); } return "keyword"; } else if (atomWords.test(matched)) { return "atom"; } return "variable"; } // Class variables and instance variables // or attributes if (stream.eat("@")) { if (stream.peek() == "[") { return chain(tokenNest("[", "]", "meta"), stream, state); } stream.eat("@"); stream.match(idents) || stream.match(types); return "variable-2"; } // Constants and types if (stream.match(types)) { return "tag"; } // Symbols or ':' operator if (stream.eat(":")) { if (stream.eat("\"")) { return chain(tokenQuote("\"", "atom", false), stream, state); } else if (stream.match(idents) || stream.match(types) || stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators)) { return "atom"; } stream.eat(":"); return "operator"; } // Strings if (stream.eat("\"")) { return chain(tokenQuote("\"", "string", true), stream, state); } // Strings or regexps or macro variables or '%' operator if (stream.peek() == "%") { var style = "string"; var embed = true; var delim; if (stream.match("%r")) { // Regexps style = "string-2"; delim = stream.next(); } else if (stream.match("%w")) { embed = false; delim = stream.next(); } else if (stream.match("%q")) { embed = false; delim = stream.next(); } else { if(delim = stream.match(/^%([^\w\s=])/)) { delim = delim[1]; } else if (stream.match(/^%[a-zA-Z0-9_\u009F-\uFFFF]*/)) { // Macro variables return "meta"; } else { // '%' operator return "operator"; } } if (matching.hasOwnProperty(delim)) { delim = matching[delim]; } return chain(tokenQuote(delim, style, embed), stream, state); } // Here Docs if (matched = stream.match(/^<<-('?)([A-Z]\w*)\1/)) { return chain(tokenHereDoc(matched[2], !matched[1]), stream, state) } // Characters if (stream.eat("'")) { stream.match(/^(?:[^']|\\(?:[befnrtv0'"]|[0-7]{3}|u(?:[0-9a-fA-F]{4}|\{[0-9a-fA-F]{1,6}\})))/); stream.eat("'"); return "atom"; } // Numbers if (stream.eat("0")) { if (stream.eat("x")) { stream.match(/^[0-9a-fA-F]+/); } else if (stream.eat("o")) { stream.match(/^[0-7]+/); } else if (stream.eat("b")) { stream.match(/^[01]+/); } return "number"; } if (stream.eat(/^\d/)) { stream.match(/^\d*(?:\.\d+)?(?:[eE][+-]?\d+)?/); return "number"; } // Operators if (stream.match(operators)) { stream.eat("="); // Operators can follow assign symbol. return "operator"; } if (stream.match(conditionalOperators) || stream.match(anotherOperators)) { return "operator"; } // Parens and braces if (matched = stream.match(/[({[]/, false)) { matched = matched[0]; return chain(tokenNest(matched, matching[matched], null), stream, state); } // Escapes if (stream.eat("\\")) { stream.next(); return "meta"; } stream.next(); return null; } function tokenNest(begin, end, style, started) { return function (stream, state) { if (!started && stream.match(begin)) { state.tokenize[state.tokenize.length - 1] = tokenNest(begin, end, style, true); state.currentIndent += 1; return style; } var nextStyle = tokenBase(stream, state); if (stream.current() === end) { state.tokenize.pop(); state.currentIndent -= 1; nextStyle = style; } return nextStyle; }; } function tokenMacro(begin, end, started) { return function (stream, state) { if (!started && stream.match("{" + begin)) { state.currentIndent += 1; state.tokenize[state.tokenize.length - 1] = tokenMacro(begin, end, true); return "meta"; } if (stream.match(end + "}")) { state.currentIndent -= 1; state.tokenize.pop(); return "meta"; } return tokenBase(stream, state); }; } function tokenMacroDef(stream, state) { if (stream.eatSpace()) { return null; } var matched; if (matched = stream.match(idents)) { if (matched == "def") { return "keyword"; } stream.eat(/[?!]/); } state.tokenize.pop(); return "def"; } function tokenFollowIdent(stream, state) { if (stream.eatSpace()) { return null; } if (stream.match(idents)) { stream.eat(/[!?]/); } else { stream.match(operators) || stream.match(conditionalOperators) || stream.match(indexingOperators); } state.tokenize.pop(); return "def"; } function tokenFollowType(stream, state) { if (stream.eatSpace()) { return null; } stream.match(types); state.tokenize.pop(); return "def"; } function tokenQuote(end, style, embed) { return function (stream, state) { var escaped = false; while (stream.peek()) { if (!escaped) { if (stream.match("{%", false)) { state.tokenize.push(tokenMacro("%", "%")); return style; } if (stream.match("{{", false)) { state.tokenize.push(tokenMacro("{", "}")); return style; } if (embed && stream.match("#{", false)) { state.tokenize.push(tokenNest("#{", "}", "meta")); return style; } var ch = stream.next(); if (ch == end) { state.tokenize.pop(); return style; } escaped = embed && ch == "\\"; } else { stream.next(); escaped = false; } } return style; }; } function tokenHereDoc(phrase, embed) { return function (stream, state) { if (stream.sol()) { stream.eatSpace() if (stream.match(phrase)) { state.tokenize.pop(); return "string"; } } var escaped = false; while (stream.peek()) { if (!escaped) { if (stream.match("{%", false)) { state.tokenize.push(tokenMacro("%", "%")); return "string"; } if (stream.match("{{", false)) { state.tokenize.push(tokenMacro("{", "}")); return "string"; } if (embed && stream.match("#{", false)) { state.tokenize.push(tokenNest("#{", "}", "meta")); return "string"; } escaped = embed && stream.next() == "\\"; } else { stream.next(); escaped = false; } } return "string"; } } return { startState: function () { return { tokenize: [tokenBase], currentIndent: 0, lastToken: null, lastStyle: null, blocks: [] }; }, token: function (stream, state) { var style = state.tokenize[state.tokenize.length - 1](stream, state); var token = stream.current(); if (style && style != "comment") { state.lastToken = token; state.lastStyle = style; } return style; }, indent: function (state, textAfter) { textAfter = textAfter.replace(/^\s*(?:\{%)?\s*|\s*(?:%\})?\s*$/g, ""); if (dedentKeywords.test(textAfter) || dedentPunctuals.test(textAfter)) { return config.indentUnit * (state.currentIndent - 1); } return config.indentUnit * state.currentIndent; }, fold: "indent", electricInput: wordRegExp(dedentPunctualsArray.concat(dedentKeywordsArray), true), lineComment: '#' }; }); CodeMirror.defineMIME("text/x-crystal", "crystal"); }); ================================================ FILE: third_party/CodeMirror/mode/crystal/index.html ================================================ CodeMirror: Crystal mode

Crystal mode

MIME types defined: text/x-crystal.

================================================ FILE: third_party/CodeMirror/mode/css/css.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("css", function(config, parserConfig) { var inline = parserConfig.inline if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css"); var indentUnit = config.indentUnit, tokenHooks = parserConfig.tokenHooks, documentTypes = parserConfig.documentTypes || {}, mediaTypes = parserConfig.mediaTypes || {}, mediaFeatures = parserConfig.mediaFeatures || {}, mediaValueKeywords = parserConfig.mediaValueKeywords || {}, propertyKeywords = parserConfig.propertyKeywords || {}, nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {}, fontProperties = parserConfig.fontProperties || {}, counterDescriptors = parserConfig.counterDescriptors || {}, colorKeywords = parserConfig.colorKeywords || {}, valueKeywords = parserConfig.valueKeywords || {}, allowNested = parserConfig.allowNested, lineComment = parserConfig.lineComment, supportsAtComponent = parserConfig.supportsAtComponent === true; var type, override; function ret(style, tp) { type = tp; return style; } // Tokenizers function tokenBase(stream, state) { var ch = stream.next(); if (tokenHooks[ch]) { var result = tokenHooks[ch](stream, state); if (result !== false) return result; } if (ch == "@") { stream.eatWhile(/[\w\\\-]/); return ret("def", stream.current()); } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) { return ret(null, "compare"); } else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "#") { stream.eatWhile(/[\w\\\-]/); return ret("atom", "hash"); } else if (ch == "!") { stream.match(/^\s*\w*/); return ret("keyword", "important"); } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (ch === "-") { if (/[\d.]/.test(stream.peek())) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (stream.match(/^-[\w\\\-]*/)) { stream.eatWhile(/[\w\\\-]/); if (stream.match(/^\s*:/, false)) return ret("variable-2", "variable-definition"); return ret("variable-2", "variable"); } else if (stream.match(/^\w+-/)) { return ret("meta", "meta"); } } else if (/[,+>*\/]/.test(ch)) { return ret(null, "select-op"); } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) { return ret("qualifier", "qualifier"); } else if (/[:;{}\[\]\(\)]/.test(ch)) { return ret(null, ch); } else if (stream.match(/[\w-.]+(?=\()/)) { if (/^(url(-prefix)?|domain|regexp)$/.test(stream.current().toLowerCase())) { state.tokenize = tokenParenthesized; } return ret("variable callee", "variable"); } else if (/[\w\\\-]/.test(ch)) { stream.eatWhile(/[\w\\\-]/); return ret("property", "word"); } else { return ret(null, null); } } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { if (quote == ")") stream.backUp(1); break; } escaped = !escaped && ch == "\\"; } if (ch == quote || !escaped && quote != ")") state.tokenize = null; return ret("string", "string"); }; } function tokenParenthesized(stream, state) { stream.next(); // Must be '(' if (!stream.match(/\s*[\"\')]/, false)) state.tokenize = tokenString(")"); else state.tokenize = null; return ret(null, "("); } // Context management function Context(type, indent, prev) { this.type = type; this.indent = indent; this.prev = prev; } function pushContext(state, stream, type, indent) { state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context); return type; } function popContext(state) { if (state.context.prev) state.context = state.context.prev; return state.context.type; } function pass(type, stream, state) { return states[state.context.type](type, stream, state); } function popAndPass(type, stream, state, n) { for (var i = n || 1; i > 0; i--) state.context = state.context.prev; return pass(type, stream, state); } // Parser function wordAsValue(stream) { var word = stream.current().toLowerCase(); if (valueKeywords.hasOwnProperty(word)) override = "atom"; else if (colorKeywords.hasOwnProperty(word)) override = "keyword"; else override = "variable"; } var states = {}; states.top = function(type, stream, state) { if (type == "{") { return pushContext(state, stream, "block"); } else if (type == "}" && state.context.prev) { return popContext(state); } else if (supportsAtComponent && /@component/i.test(type)) { return pushContext(state, stream, "atComponentBlock"); } else if (/^@(-moz-)?document$/i.test(type)) { return pushContext(state, stream, "documentTypes"); } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) { return pushContext(state, stream, "atBlock"); } else if (/^@(font-face|counter-style)/i.test(type)) { state.stateArg = type; return "restricted_atBlock_before"; } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) { return "keyframes"; } else if (type && type.charAt(0) == "@") { return pushContext(state, stream, "at"); } else if (type == "hash") { override = "builtin"; } else if (type == "word") { override = "tag"; } else if (type == "variable-definition") { return "maybeprop"; } else if (type == "interpolation") { return pushContext(state, stream, "interpolation"); } else if (type == ":") { return "pseudo"; } else if (allowNested && type == "(") { return pushContext(state, stream, "parens"); } return state.context.type; }; states.block = function(type, stream, state) { if (type == "word") { var word = stream.current().toLowerCase(); if (propertyKeywords.hasOwnProperty(word)) { override = "property"; return "maybeprop"; } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) { override = "string-2"; return "maybeprop"; } else if (allowNested) { override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag"; return "block"; } else { override += " error"; return "maybeprop"; } } else if (type == "meta") { return "block"; } else if (!allowNested && (type == "hash" || type == "qualifier")) { override = "error"; return "block"; } else { return states.top(type, stream, state); } }; states.maybeprop = function(type, stream, state) { if (type == ":") return pushContext(state, stream, "prop"); return pass(type, stream, state); }; states.prop = function(type, stream, state) { if (type == ";") return popContext(state); if (type == "{" && allowNested) return pushContext(state, stream, "propBlock"); if (type == "}" || type == "{") return popAndPass(type, stream, state); if (type == "(") return pushContext(state, stream, "parens"); if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) { override += " error"; } else if (type == "word") { wordAsValue(stream); } else if (type == "interpolation") { return pushContext(state, stream, "interpolation"); } return "prop"; }; states.propBlock = function(type, _stream, state) { if (type == "}") return popContext(state); if (type == "word") { override = "property"; return "maybeprop"; } return state.context.type; }; states.parens = function(type, stream, state) { if (type == "{" || type == "}") return popAndPass(type, stream, state); if (type == ")") return popContext(state); if (type == "(") return pushContext(state, stream, "parens"); if (type == "interpolation") return pushContext(state, stream, "interpolation"); if (type == "word") wordAsValue(stream); return "parens"; }; states.pseudo = function(type, stream, state) { if (type == "meta") return "pseudo"; if (type == "word") { override = "variable-3"; return state.context.type; } return pass(type, stream, state); }; states.documentTypes = function(type, stream, state) { if (type == "word" && documentTypes.hasOwnProperty(stream.current())) { override = "tag"; return state.context.type; } else { return states.atBlock(type, stream, state); } }; states.atBlock = function(type, stream, state) { if (type == "(") return pushContext(state, stream, "atBlock_parens"); if (type == "}" || type == ";") return popAndPass(type, stream, state); if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top"); if (type == "interpolation") return pushContext(state, stream, "interpolation"); if (type == "word") { var word = stream.current().toLowerCase(); if (word == "only" || word == "not" || word == "and" || word == "or") override = "keyword"; else if (mediaTypes.hasOwnProperty(word)) override = "attribute"; else if (mediaFeatures.hasOwnProperty(word)) override = "property"; else if (mediaValueKeywords.hasOwnProperty(word)) override = "keyword"; else if (propertyKeywords.hasOwnProperty(word)) override = "property"; else if (nonStandardPropertyKeywords.hasOwnProperty(word)) override = "string-2"; else if (valueKeywords.hasOwnProperty(word)) override = "atom"; else if (colorKeywords.hasOwnProperty(word)) override = "keyword"; else override = "error"; } return state.context.type; }; states.atComponentBlock = function(type, stream, state) { if (type == "}") return popAndPass(type, stream, state); if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false); if (type == "word") override = "error"; return state.context.type; }; states.atBlock_parens = function(type, stream, state) { if (type == ")") return popContext(state); if (type == "{" || type == "}") return popAndPass(type, stream, state, 2); return states.atBlock(type, stream, state); }; states.restricted_atBlock_before = function(type, stream, state) { if (type == "{") return pushContext(state, stream, "restricted_atBlock"); if (type == "word" && state.stateArg == "@counter-style") { override = "variable"; return "restricted_atBlock_before"; } return pass(type, stream, state); }; states.restricted_atBlock = function(type, stream, state) { if (type == "}") { state.stateArg = null; return popContext(state); } if (type == "word") { if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) || (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase()))) override = "error"; else override = "property"; return "maybeprop"; } return "restricted_atBlock"; }; states.keyframes = function(type, stream, state) { if (type == "word") { override = "variable"; return "keyframes"; } if (type == "{") return pushContext(state, stream, "top"); return pass(type, stream, state); }; states.at = function(type, stream, state) { if (type == ";") return popContext(state); if (type == "{" || type == "}") return popAndPass(type, stream, state); if (type == "word") override = "tag"; else if (type == "hash") override = "builtin"; return "at"; }; states.interpolation = function(type, stream, state) { if (type == "}") return popContext(state); if (type == "{" || type == ";") return popAndPass(type, stream, state); if (type == "word") override = "variable"; else if (type != "variable" && type != "(" && type != ")") override = "error"; return "interpolation"; }; return { startState: function(base) { return {tokenize: null, state: inline ? "block" : "top", stateArg: null, context: new Context(inline ? "block" : "top", base || 0, null)}; }, token: function(stream, state) { if (!state.tokenize && stream.eatSpace()) return null; var style = (state.tokenize || tokenBase)(stream, state); if (style && typeof style == "object") { type = style[1]; style = style[0]; } override = style; if (type != "comment") state.state = states[state.state](type, stream, state); return override; }, indent: function(state, textAfter) { var cx = state.context, ch = textAfter && textAfter.charAt(0); var indent = cx.indent; if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev; if (cx.prev) { if (ch == "}" && (cx.type == "block" || cx.type == "top" || cx.type == "interpolation" || cx.type == "restricted_atBlock")) { // Resume indentation from parent context. cx = cx.prev; indent = cx.indent; } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || ch == "{" && (cx.type == "at" || cx.type == "atBlock")) { // Dedent relative to current context. indent = Math.max(0, cx.indent - indentUnit); } } return indent; }, electricChars: "}", blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", lineComment: lineComment, fold: "brace" }; }); function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) { keys[array[i].toLowerCase()] = true; } return keys; } var documentTypes_ = [ "domain", "regexp", "url", "url-prefix" ], documentTypes = keySet(documentTypes_); var mediaTypes_ = [ "all", "aural", "braille", "handheld", "print", "projection", "screen", "tty", "tv", "embossed" ], mediaTypes = keySet(mediaTypes_); 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", "orientation", "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio", "pointer", "any-pointer", "hover", "any-hover" ], mediaFeatures = keySet(mediaFeatures_); var mediaValueKeywords_ = [ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover", "interlace", "progressive" ], mediaValueKeywords = keySet(mediaValueKeywords_); 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-blend-mode", "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", "caret-color", "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-rows", "grid-column", "grid-column-end", "grid-column-gap", "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap", "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", "justify-items", "justify-self", "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", "marks", "marquee-direction", "marquee-loop", "marquee-play-count", "marquee-speed", "marquee-style", "max-height", "max-width", "min-height", "min-width", "mix-blend-mode", "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", "place-content", "place-items", "place-self", "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", "user-select", "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", // SVG-specific "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" ], propertyKeywords = keySet(propertyKeywords_); 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" ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_); var fontProperties_ = [ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings", "font-stretch", "font-weight", "font-style" ], fontProperties = keySet(fontProperties_); var counterDescriptors_ = [ "additive-symbols", "fallback", "negative", "pad", "prefix", "range", "speak-as", "suffix", "symbols", "system" ], counterDescriptors = keySet(counterDescriptors_); 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" ], colorKeywords = keySet(colorKeywords_); 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", "auto-flow", "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", "color", "color-burn", "color-dodge", "column", "column-reverse", "compact", "condensed", "contain", "content", "contents", "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop", "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal", "decimal-leading-zero", "default", "default-button", "dense", "destination-atop", "destination-in", "destination-out", "destination-over", "devanagari", "difference", "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", "exclusion", "expanded", "extends", "extra-condensed", "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes", "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove", "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew", "help", "hidden", "hide", "higher", "highlight", "highlighttext", "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "icon", "ignore", "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite", "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis", "inline-block", "inline-flex", "inline-grid", "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", "lighten", "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", "luminosity", "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", "multiply", "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", "opacity", "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", "row-resize", "row-reverse", "rtl", "run-in", "running", "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen", "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield", "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end", "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", "soft-light", "solid", "somali", "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square", "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub", "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "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", "transform", "translate", "translate3d", "translateX", "translateY", "translateZ", "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "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", "wrap", "wrap-reverse", "x-large", "x-small", "xor", "xx-large", "xx-small" ], valueKeywords = keySet(valueKeywords_); var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_) .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_) .concat(valueKeywords_); CodeMirror.registerHelper("hintWords", "css", allWords); function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return ["comment", "comment"]; } CodeMirror.defineMIME("text/css", { documentTypes: documentTypes, mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, fontProperties: fontProperties, counterDescriptors: counterDescriptors, colorKeywords: colorKeywords, valueKeywords: valueKeywords, tokenHooks: { "/": function(stream, state) { if (!stream.eat("*")) return false; state.tokenize = tokenCComment; return tokenCComment(stream, state); } }, name: "css" }); CodeMirror.defineMIME("text/x-scss", { mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, fontProperties: fontProperties, allowNested: true, lineComment: "//", tokenHooks: { "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); return ["comment", "comment"]; } else if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else { return ["operator", "operator"]; } }, ":": function(stream) { if (stream.match(/\s*\{/, false)) return [null, null] return false; }, "$": function(stream) { stream.match(/^[\w-]+/); if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"]; return ["variable-2", "variable"]; }, "#": function(stream) { if (!stream.eat("{")) return false; return [null, "interpolation"]; } }, name: "css", helperType: "scss" }); CodeMirror.defineMIME("text/x-less", { mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, mediaValueKeywords: mediaValueKeywords, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, colorKeywords: colorKeywords, valueKeywords: valueKeywords, fontProperties: fontProperties, allowNested: true, lineComment: "//", tokenHooks: { "/": function(stream, state) { if (stream.eat("/")) { stream.skipToEnd(); return ["comment", "comment"]; } else if (stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else { return ["operator", "operator"]; } }, "@": function(stream) { if (stream.eat("{")) return [null, "interpolation"]; if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false; stream.eatWhile(/[\w\\\-]/); if (stream.match(/^\s*:/, false)) return ["variable-2", "variable-definition"]; return ["variable-2", "variable"]; }, "&": function() { return ["atom", "atom"]; } }, name: "css", helperType: "less" }); CodeMirror.defineMIME("text/x-gss", { documentTypes: documentTypes, mediaTypes: mediaTypes, mediaFeatures: mediaFeatures, propertyKeywords: propertyKeywords, nonStandardPropertyKeywords: nonStandardPropertyKeywords, fontProperties: fontProperties, counterDescriptors: counterDescriptors, colorKeywords: colorKeywords, valueKeywords: valueKeywords, supportsAtComponent: true, tokenHooks: { "/": function(stream, state) { if (!stream.eat("*")) return false; state.tokenize = tokenCComment; return tokenCComment(stream, state); } }, name: "css", helperType: "gss" }); }); ================================================ FILE: third_party/CodeMirror/mode/css/gss.html ================================================ CodeMirror: Closure Stylesheets (GSS) mode

Closure Stylesheets (GSS) mode

A mode for Closure Stylesheets (GSS).

MIME type defined: text/x-gss.

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/css/gss_test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { "use strict"; var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-gss"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "gss"); } MT("atComponent", "[def @component] {", "[tag foo] {", " [property color]: [keyword black];", "}", "}"); })(); ================================================ FILE: third_party/CodeMirror/mode/css/index.html ================================================ CodeMirror: CSS mode

CSS mode

MIME types defined: text/css, text/x-scss (demo), text/x-less (demo).

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/css/less.html ================================================ CodeMirror: LESS mode

LESS mode

The LESS mode is a sub-mode of the CSS mode (defined in css.js).

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/css/less_test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { "use strict"; var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-less"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "less"); } MT("variable", "[variable-2 @base]: [atom #f04615];", "[qualifier .class] {", " [property width]: [variable&callee percentage]([number 0.5]); [comment // returns `50%`]", " [property color]: [variable&callee saturate]([variable-2 @base], [number 5%]);", "}"); MT("amp", "[qualifier .child], [qualifier .sibling] {", " [qualifier .parent] [atom &] {", " [property color]: [keyword black];", " }", " [atom &] + [atom &] {", " [property color]: [keyword red];", " }", "}"); MT("mixin", "[qualifier .mixin] ([variable dark]; [variable-2 @color]) {", " [property color]: [variable&callee darken]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable light]; [variable-2 @color]) {", " [property color]: [variable&callee lighten]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable-2 @_]; [variable-2 @color]) {", " [property display]: [atom block];", "}", "[variable-2 @switch]: [variable light];", "[qualifier .class] {", " [qualifier .mixin]([variable-2 @switch]; [atom #888]);", "}"); MT("nest", "[qualifier .one] {", " [def @media] ([property width]: [number 400px]) {", " [property font-size]: [number 1.2em];", " [def @media] [attribute print] [keyword and] [property color] {", " [property color]: [keyword blue];", " }", " }", "}"); MT("interpolation", ".@{[variable foo]} { [property font-weight]: [atom bold]; }"); })(); ================================================ FILE: third_party/CodeMirror/mode/css/scss.html ================================================ CodeMirror: SCSS mode

SCSS mode

The SCSS mode is a sub-mode of the CSS mode (defined in css.js).

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/css/scss_test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-scss"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "scss"); } MT('url_with_quotation', "[tag foo] { [property background]:[variable&callee url]([string test.jpg]) }"); MT('url_with_double_quotes', "[tag foo] { [property background]:[variable&callee url]([string \"test.jpg\"]) }"); MT('url_with_single_quotes', "[tag foo] { [property background]:[variable&callee url]([string \'test.jpg\']) }"); MT('string', "[def @import] [string \"compass/css3\"]"); MT('important_keyword', "[tag foo] { [property background]:[variable&callee url]([string \'test.jpg\']) [keyword !important] }"); MT('variable', "[variable-2 $blue]:[atom #333]"); MT('variable_as_attribute', "[tag foo] { [property color]:[variable-2 $blue] }"); MT('numbers', "[tag foo] { [property padding]:[number 10px] [number 10] [number 10em] [number 8in] }"); MT('number_percentage', "[tag foo] { [property width]:[number 80%] }"); MT('selector', "[builtin #hello][qualifier .world]{}"); MT('singleline_comment', "[comment // this is a comment]"); MT('multiline_comment', "[comment /*foobar*/]"); MT('attribute_with_hyphen', "[tag foo] { [property font-size]:[number 10px] }"); MT('string_after_attribute', "[tag foo] { [property content]:[string \"::\"] }"); MT('directives', "[def @include] [qualifier .mixin]"); MT('basic_structure', "[tag p] { [property background]:[keyword red]; }"); MT('nested_structure', "[tag p] { [tag a] { [property color]:[keyword red]; } }"); MT('mixin', "[def @mixin] [tag table-base] {}"); MT('number_without_semicolon', "[tag p] {[property width]:[number 12]}", "[tag a] {[property color]:[keyword red];}"); MT('atom_in_nested_block', "[tag p] { [tag a] { [property color]:[atom #000]; } }"); MT('interpolation_in_property', "[tag foo] { #{[variable-2 $hello]}:[number 2]; }"); MT('interpolation_in_selector', "[tag foo]#{[variable-2 $hello]} { [property color]:[atom #000]; }"); MT('interpolation_error', "[tag foo]#{[variable foo]} { [property color]:[atom #000]; }"); MT("divide_operator", "[tag foo] { [property width]:[number 4] [operator /] [number 2] }"); MT('nested_structure_with_id_selector', "[tag p] { [builtin #hello] { [property color]:[keyword red]; } }"); MT('indent_mixin', "[def @mixin] [tag container] (", " [variable-2 $a]: [number 10],", " [variable-2 $b]: [number 10])", "{}"); MT('indent_nested', "[tag foo] {", " [tag bar] {", " }", "}"); MT('indent_parentheses', "[tag foo] {", " [property color]: [variable&callee darken]([variable-2 $blue],", " [number 9%]);", "}"); MT('indent_vardef', "[variable-2 $name]:", " [string 'val'];", "[tag tag] {", " [tag inner] {", " [property margin]: [number 3px];", " }", "}"); })(); ================================================ FILE: third_party/CodeMirror/mode/css/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "css"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Error, because "foobarhello" is neither a known type or property, but // property was expected (after "and"), and it should be in parentheses. MT("atMediaUnknownType", "[def @media] [attribute screen] [keyword and] [error foobarhello] { }"); // Soft error, because "foobarhello" is not a known property or type. MT("atMediaUnknownProperty", "[def @media] [attribute screen] [keyword and] ([error foobarhello]) { }"); // Make sure nesting works with media queries MT("atMediaMaxWidthNested", "[def @media] [attribute screen] [keyword and] ([property max-width]: [number 25px]) { [tag foo] { } }"); MT("atMediaFeatureValueKeyword", "[def @media] ([property orientation]: [keyword landscape]) { }"); MT("atMediaUnknownFeatureValueKeyword", "[def @media] ([property orientation]: [error upsidedown]) { }"); MT("atMediaUppercase", "[def @MEDIA] ([property orienTAtion]: [keyword landScape]) { }"); MT("tagSelector", "[tag foo] { }"); MT("classSelector", "[qualifier .foo-bar_hello] { }"); MT("idSelector", "[builtin #foo] { [error #foo] }"); MT("tagSelectorUnclosed", "[tag foo] { [property margin]: [number 0] } [tag bar] { }"); MT("tagStringNoQuotes", "[tag foo] { [property font-family]: [variable hello] [variable world]; }"); MT("tagStringDouble", "[tag foo] { [property font-family]: [string \"hello world\"]; }"); MT("tagStringSingle", "[tag foo] { [property font-family]: [string 'hello world']; }"); MT("tagColorKeyword", "[tag foo] {", " [property color]: [keyword black];", " [property color]: [keyword navy];", " [property color]: [keyword yellow];", "}"); MT("tagColorHex3", "[tag foo] { [property background]: [atom #fff]; }"); MT("tagColorHex4", "[tag foo] { [property background]: [atom #ffff]; }"); MT("tagColorHex6", "[tag foo] { [property background]: [atom #ffffff]; }"); MT("tagColorHex8", "[tag foo] { [property background]: [atom #ffffffff]; }"); MT("tagColorHex5Invalid", "[tag foo] { [property background]: [atom&error #fffff]; }"); MT("tagColorHexInvalid", "[tag foo] { [property background]: [atom&error #ffg]; }"); MT("tagNegativeNumber", "[tag foo] { [property margin]: [number -5px]; }"); MT("tagPositiveNumber", "[tag foo] { [property padding]: [number 5px]; }"); MT("tagVendor", "[tag foo] { [meta -foo-][property box-sizing]: [meta -foo-][atom border-box]; }"); MT("tagBogusProperty", "[tag foo] { [property&error barhelloworld]: [number 0]; }"); MT("tagTwoProperties", "[tag foo] { [property margin]: [number 0]; [property padding]: [number 0]; }"); MT("tagTwoPropertiesURL", "[tag foo] { [property background]: [variable&callee url]([string //example.com/foo.png]); [property padding]: [number 0]; }"); MT("indent_tagSelector", "[tag strong], [tag em] {", " [property background]: [variable&callee rgba](", " [number 255], [number 255], [number 0], [number .2]", " );", "}"); MT("indent_atMedia", "[def @media] {", " [tag foo] {", " [property color]:", " [keyword yellow];", " }", "}"); MT("indent_comma", "[tag foo] {", " [property font-family]: [variable verdana],", " [atom sans-serif];", "}"); MT("indent_parentheses", "[tag foo]:[variable-3 before] {", " [property background]: [variable&callee url](", "[string blahblah]", "[string etc]", "[string ]) [keyword !important];", "}"); MT("font_face", "[def @font-face] {", " [property font-family]: [string 'myfont'];", " [error nonsense]: [string 'abc'];", " [property src]: [variable&callee url]([string http://blah]),", " [variable&callee url]([string http://foo]);", "}"); MT("empty_url", "[def @import] [variable&callee url]() [attribute screen];"); MT("parens", "[qualifier .foo] {", " [property background-image]: [variable&callee fade]([atom #000], [number 20%]);", " [property border-image]: [variable&callee linear-gradient](", " [atom to] [atom bottom],", " [variable&callee fade]([atom #000], [number 20%]) [number 0%],", " [variable&callee fade]([atom #000], [number 20%]) [number 100%]", " );", "}"); MT("css_variable", ":[variable-3 root] {", " [variable-2 --main-color]: [atom #06c];", "}", "[tag h1][builtin #foo] {", " [property color]: [variable&callee var]([variable-2 --main-color]);", "}"); MT("blank_css_variable", ":[variable-3 root] {", " [variable-2 --]: [atom #06c];", "}", "[tag h1][builtin #foo] {", " [property color]: [variable&callee var]([variable-2 --]);", "}"); MT("supports", "[def @supports] ([keyword not] (([property text-align-last]: [atom justify]) [keyword or] ([meta -moz-][property text-align-last]: [atom justify])) {", " [property text-align-last]: [atom justify];", "}"); MT("document", "[def @document] [variable&callee url]([string http://blah]),", " [variable&callee url-prefix]([string https://]),", " [variable&callee domain]([string blah.com]),", " [variable&callee regexp]([string \".*blah.+\"]) {", " [builtin #id] {", " [property background-color]: [keyword white];", " }", " [tag foo] {", " [property font-family]: [variable Verdana], [atom sans-serif];", " }", "}"); MT("document_url", "[def @document] [variable&callee url]([string http://blah]) { [qualifier .class] { } }"); MT("document_urlPrefix", "[def @document] [variable&callee url-prefix]([string https://]) { [builtin #id] { } }"); MT("document_domain", "[def @document] [variable&callee domain]([string blah.com]) { [tag foo] { } }"); MT("document_regexp", "[def @document] [variable&callee regexp]([string \".*blah.+\"]) { [builtin #id] { } }"); MT("counter-style", "[def @counter-style] [variable binary] {", " [property system]: [atom numeric];", " [property symbols]: [number 0] [number 1];", " [property suffix]: [string \".\"];", " [property range]: [atom infinite];", " [property speak-as]: [atom numeric];", "}"); MT("counter-style-additive-symbols", "[def @counter-style] [variable simple-roman] {", " [property system]: [atom additive];", " [property additive-symbols]: [number 10] [variable X], [number 5] [variable V], [number 1] [variable I];", " [property range]: [number 1] [number 49];", "}"); MT("counter-style-use", "[tag ol][qualifier .roman] { [property list-style]: [variable simple-roman]; }"); MT("counter-style-symbols", "[tag ol] { [property list-style]: [variable&callee symbols]([atom cyclic] [string \"*\"] [string \"\\2020\"] [string \"\\2021\"] [string \"\\A7\"]); }"); MT("comment-does-not-disrupt", "[def @font-face] [comment /* foo */] {", " [property src]: [variable&callee url]([string x]);", " [property font-family]: [variable One];", "}") })(); ================================================ FILE: third_party/CodeMirror/mode/cypher/cypher.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // By the Neo4j Team and contributors. // https://github.com/neo4j-contrib/CodeMirror (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var wordRegexp = function(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); }; CodeMirror.defineMode("cypher", function(config) { var tokenBase = function(stream/*, state*/) { var ch = stream.next(); if (ch ==='"') { stream.match(/.*?"/); return "string"; } if (ch === "'") { stream.match(/.*?'/); return "string"; } if (/[{}\(\),\.;\[\]]/.test(ch)) { curPunc = ch; return "node"; } else if (ch === "/" && stream.eat("/")) { stream.skipToEnd(); return "comment"; } else if (operatorChars.test(ch)) { stream.eatWhile(operatorChars); return null; } else { stream.eatWhile(/[_\w\d]/); if (stream.eat(":")) { stream.eatWhile(/[\w\d_\-]/); return "atom"; } var word = stream.current(); if (funcs.test(word)) return "builtin"; if (preds.test(word)) return "def"; if (keywords.test(word)) return "keyword"; return "variable"; } }; var pushContext = function(state, type, col) { return state.context = { prev: state.context, indent: state.indent, col: col, type: type }; }; var popContext = function(state) { state.indent = state.context.indent; return state.context = state.context.prev; }; var indentUnit = config.indentUnit; var curPunc; 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"]); var preds = wordRegexp(["all", "and", "any", "contains", "exists", "has", "in", "none", "not", "or", "single", "xor"]); 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"]); var operatorChars = /[*+\-<>=&|~%^]/; return { startState: function(/*base*/) { return { tokenize: tokenBase, context: null, indent: 0, col: 0 }; }, token: function(stream, state) { if (stream.sol()) { if (state.context && (state.context.align == null)) { state.context.align = false; } state.indent = stream.indentation(); } if (stream.eatSpace()) { return null; } var style = state.tokenize(stream, state); if (style !== "comment" && state.context && (state.context.align == null) && state.context.type !== "pattern") { state.context.align = true; } if (curPunc === "(") { pushContext(state, ")", stream.column()); } else if (curPunc === "[") { pushContext(state, "]", stream.column()); } else if (curPunc === "{") { pushContext(state, "}", stream.column()); } else if (/[\]\}\)]/.test(curPunc)) { while (state.context && state.context.type === "pattern") { popContext(state); } if (state.context && curPunc === state.context.type) { popContext(state); } } else if (curPunc === "." && state.context && state.context.type === "pattern") { popContext(state); } else if (/atom|string|variable/.test(style) && state.context) { if (/[\}\]]/.test(state.context.type)) { pushContext(state, "pattern", stream.column()); } else if (state.context.type === "pattern" && !state.context.align) { state.context.align = true; state.context.col = stream.column(); } } return style; }, indent: function(state, textAfter) { var firstChar = textAfter && textAfter.charAt(0); var context = state.context; if (/[\]\}]/.test(firstChar)) { while (context && context.type === "pattern") { context = context.prev; } } var closing = context && firstChar === context.type; if (!context) return 0; if (context.type === "keywords") return CodeMirror.commands.newlineAndIndent; if (context.align) return context.col + (closing ? 0 : 1); return context.indent + (closing ? 0 : indentUnit); } }; }); CodeMirror.modeExtensions["cypher"] = { autoFormatLineBreaks: function(text) { var i, lines, reProcessedPortion; var lines = text.split("\n"); var reProcessedPortion = /\s+\b(return|where|order by|match|with|skip|limit|create|delete|set)\b\s/g; for (var i = 0; i < lines.length; i++) lines[i] = lines[i].replace(reProcessedPortion, " \n$1 ").trim(); return lines.join("\n"); } }; CodeMirror.defineMIME("application/x-cypher-query", "cypher"); }); ================================================ FILE: third_party/CodeMirror/mode/cypher/index.html ================================================ CodeMirror: Cypher Mode for CodeMirror

Cypher Mode for CodeMirror

MIME types defined: application/x-cypher-query

================================================ FILE: third_party/CodeMirror/mode/cypher/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "cypher"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("unbalancedDoubledQuotedString", "[string \"a'b\"][variable c]"); MT("unbalancedSingleQuotedString", "[string 'a\"b'][variable c]"); MT("doubleQuotedString", "[string \"a\"][variable b]"); MT("singleQuotedString", "[string 'a'][variable b]"); MT("single attribute (with content)", "[node {][atom a:][string 'a'][node }]"); MT("multiple attribute, singleQuotedString (with content)", "[node {][atom a:][string 'a'][node ,][atom b:][string 'b'][node }]"); MT("multiple attribute, doubleQuotedString (with content)", "[node {][atom a:][string \"a\"][node ,][atom b:][string \"b\"][node }]"); MT("single attribute (without content)", "[node {][atom a:][string 'a'][node }]"); MT("multiple attribute, singleQuotedString (without content)", "[node {][atom a:][string ''][node ,][atom b:][string ''][node }]"); MT("multiple attribute, doubleQuotedString (without content)", "[node {][atom a:][string \"\"][node ,][atom b:][string \"\"][node }]"); })(); ================================================ FILE: third_party/CodeMirror/mode/d/d.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("d", function(config, parserConfig) { var indentUnit = config.indentUnit, statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, keywords = parserConfig.keywords || {}, builtin = parserConfig.builtin || {}, blockKeywords = parserConfig.blockKeywords || {}, atoms = parserConfig.atoms || {}, hooks = parserConfig.hooks || {}, multiLineStrings = parserConfig.multiLineStrings; var isOperatorChar = /[+\-*&%=<>!?|\/]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (ch == '"' || ch == "'" || ch == "`") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[\[\]{}\(\),;\:\.]/.test(ch)) { curPunc = ch; return null; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (ch == "/") { if (stream.eat("+")) { state.tokenize = tokenNestedComment; return tokenNestedComment(stream, state); } if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_\xa1-\uffff]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "keyword"; } if (builtin.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "builtin"; } if (atoms.propertyIsEnumerable(cur)) return "atom"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenNestedComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "+"); } return "comment"; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { var indent = state.indented; if (state.context && state.context.type == "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; curPunc = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement") popContext(state); else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement")) pushContext(state, stream.column(), "statement"); state.startOfLine = false; return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass; var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; var closing = firstChar == ctx.type; if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); else if (ctx.align) return ctx.column + (closing ? 0 : 1); else return ctx.indented + (closing ? 0 : indentUnit); }, electricChars: "{}", blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", lineComment: "//", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var blockKeywords = "body catch class do else enum for foreach foreach_reverse if in interface mixin " + "out scope struct switch try union unittest version while with"; CodeMirror.defineMIME("text/x-d", { name: "d", keywords: words("abstract alias align asm assert auto break case cast cdouble cent cfloat const continue " + "debug default delegate delete deprecated export extern final finally function goto immutable " + "import inout invariant is lazy macro module new nothrow override package pragma private " + "protected public pure ref return shared short static super synchronized template this " + "throw typedef typeid typeof volatile __FILE__ __LINE__ __gshared __traits __vector __parameters " + blockKeywords), blockKeywords: words(blockKeywords), builtin: words("bool byte char creal dchar double float idouble ifloat int ireal long real short ubyte " + "ucent uint ulong ushort wchar wstring void size_t sizediff_t"), atoms: words("exit failure success true false null"), hooks: { "@": function(stream, _state) { stream.eatWhile(/[\w\$_]/); return "meta"; } } }); }); ================================================ FILE: third_party/CodeMirror/mode/d/index.html ================================================ CodeMirror: D mode

D mode

Simple mode that handle D-Syntax (DLang Homepage).

MIME types defined: text/x-d .

================================================ FILE: third_party/CodeMirror/mode/d/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "d"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("nested_comments", "[comment /+]","[comment comment]","[comment +/]","[variable void] [variable main](){}"); })(); ================================================ FILE: third_party/CodeMirror/mode/dart/dart.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../clike/clike")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../clike/clike"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var keywords = ("this super static final const abstract class extends external factory " + "implements mixin get native set typedef with enum throw rethrow " + "assert break case continue default in return new deferred async await covariant " + "try catch finally do else for if switch while import library export " + "part of show hide is as").split(" "); var blockKeywords = "try catch finally do else for if switch while".split(" "); var atoms = "true false null".split(" "); var builtins = "void bool num int double dynamic var String".split(" "); function set(words) { var obj = {}; for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function pushInterpolationStack(state) { (state.interpolationStack || (state.interpolationStack = [])).push(state.tokenize); } function popInterpolationStack(state) { return (state.interpolationStack || (state.interpolationStack = [])).pop(); } function sizeInterpolationStack(state) { return state.interpolationStack ? state.interpolationStack.length : 0; } CodeMirror.defineMIME("application/dart", { name: "clike", keywords: set(keywords), blockKeywords: set(blockKeywords), builtin: set(builtins), atoms: set(atoms), hooks: { "@": function(stream) { stream.eatWhile(/[\w\$_\.]/); return "meta"; }, // custom string handling to deal with triple-quoted strings and string interpolation "'": function(stream, state) { return tokenString("'", stream, state, false); }, "\"": function(stream, state) { return tokenString("\"", stream, state, false); }, "r": function(stream, state) { var peek = stream.peek(); if (peek == "'" || peek == "\"") { return tokenString(stream.next(), stream, state, true); } return false; }, "}": function(_stream, state) { // "}" is end of interpolation, if interpolation stack is non-empty if (sizeInterpolationStack(state) > 0) { state.tokenize = popInterpolationStack(state); return null; } return false; }, "/": function(stream, state) { if (!stream.eat("*")) return false state.tokenize = tokenNestedComment(1) return state.tokenize(stream, state) } } }); function tokenString(quote, stream, state, raw) { var tripleQuoted = false; if (stream.eat(quote)) { if (stream.eat(quote)) tripleQuoted = true; else return "string"; //empty string } function tokenStringHelper(stream, state) { var escaped = false; while (!stream.eol()) { if (!raw && !escaped && stream.peek() == "$") { pushInterpolationStack(state); state.tokenize = tokenInterpolation; return "string"; } var next = stream.next(); if (next == quote && !escaped && (!tripleQuoted || stream.match(quote + quote))) { state.tokenize = null; break; } escaped = !raw && !escaped && next == "\\"; } return "string"; } state.tokenize = tokenStringHelper; return tokenStringHelper(stream, state); } function tokenInterpolation(stream, state) { stream.eat("$"); if (stream.eat("{")) { // let clike handle the content of ${...}, // we take over again when "}" appears (see hooks). state.tokenize = null; } else { state.tokenize = tokenInterpolationIdentifier; } return null; } function tokenInterpolationIdentifier(stream, state) { stream.eatWhile(/[\w_]/); state.tokenize = popInterpolationStack(state); return "variable"; } function tokenNestedComment(depth) { return function (stream, state) { var ch while (ch = stream.next()) { if (ch == "*" && stream.eat("/")) { if (depth == 1) { state.tokenize = null break } else { state.tokenize = tokenNestedComment(depth - 1) return state.tokenize(stream, state) } } else if (ch == "/" && stream.eat("*")) { state.tokenize = tokenNestedComment(depth + 1) return state.tokenize(stream, state) } } return "comment" } } CodeMirror.registerHelper("hintWords", "application/dart", keywords.concat(atoms).concat(builtins)); // This is needed to make loading through meta.js work. CodeMirror.defineMode("dart", function(conf) { return CodeMirror.getMode(conf, "application/dart"); }, "clike"); }); ================================================ FILE: third_party/CodeMirror/mode/dart/index.html ================================================ CodeMirror: Dart mode

Dart mode

================================================ FILE: third_party/CodeMirror/mode/diff/diff.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("diff", function() { var TOKEN_NAMES = { '+': 'positive', '-': 'negative', '@': 'meta' }; return { token: function(stream) { var tw_pos = stream.string.search(/[\t ]+?$/); if (!stream.sol() || tw_pos === 0) { stream.skipToEnd(); return ("error " + ( TOKEN_NAMES[stream.string.charAt(0)] || '')).replace(/ $/, ''); } var token_name = TOKEN_NAMES[stream.peek()] || stream.skipToEnd(); if (tw_pos === -1) { stream.skipToEnd(); } else { stream.pos = tw_pos; } return token_name; } }; }); CodeMirror.defineMIME("text/x-diff", "diff"); }); ================================================ FILE: third_party/CodeMirror/mode/diff/index.html ================================================ CodeMirror: Diff mode

Diff mode

MIME types defined: text/x-diff.

================================================ FILE: third_party/CodeMirror/mode/django/django.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../../addon/mode/overlay")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../../addon/mode/overlay"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("django:inner", function() { var keywords = ["block", "endblock", "for", "endfor", "true", "false", "filter", "endfilter", "loop", "none", "self", "super", "if", "elif", "endif", "as", "else", "import", "with", "endwith", "without", "context", "ifequal", "endifequal", "ifnotequal", "endifnotequal", "extends", "include", "load", "comment", "endcomment", "empty", "url", "static", "trans", "blocktrans", "endblocktrans", "now", "regroup", "lorem", "ifchanged", "endifchanged", "firstof", "debug", "cycle", "csrf_token", "autoescape", "endautoescape", "spaceless", "endspaceless", "ssi", "templatetag", "verbatim", "endverbatim", "widthratio"], filters = ["add", "addslashes", "capfirst", "center", "cut", "date", "default", "default_if_none", "dictsort", "dictsortreversed", "divisibleby", "escape", "escapejs", "filesizeformat", "first", "floatformat", "force_escape", "get_digit", "iriencode", "join", "last", "length", "length_is", "linebreaks", "linebreaksbr", "linenumbers", "ljust", "lower", "make_list", "phone2numeric", "pluralize", "pprint", "random", "removetags", "rjust", "safe", "safeseq", "slice", "slugify", "stringformat", "striptags", "time", "timesince", "timeuntil", "title", "truncatechars", "truncatechars_html", "truncatewords", "truncatewords_html", "unordered_list", "upper", "urlencode", "urlize", "urlizetrunc", "wordcount", "wordwrap", "yesno"], operators = ["==", "!=", "<", ">", "<=", ">="], wordOperators = ["in", "not", "or", "and"]; keywords = new RegExp("^\\b(" + keywords.join("|") + ")\\b"); filters = new RegExp("^\\b(" + filters.join("|") + ")\\b"); operators = new RegExp("^\\b(" + operators.join("|") + ")\\b"); wordOperators = new RegExp("^\\b(" + wordOperators.join("|") + ")\\b"); // We have to return "null" instead of null, in order to avoid string // styling as the default, when using Django templates inside HTML // element attributes function tokenBase (stream, state) { // Attempt to identify a variable, template or comment tag respectively if (stream.match("{{")) { state.tokenize = inVariable; return "tag"; } else if (stream.match("{%")) { state.tokenize = inTag; return "tag"; } else if (stream.match("{#")) { state.tokenize = inComment; return "comment"; } // Ignore completely any stream series that do not match the // Django template opening tags. while (stream.next() != null && !stream.match(/\{[{%#]/, false)) {} return null; } // A string can be included in either single or double quotes (this is // the delimiter). Mark everything as a string until the start delimiter // occurs again. function inString (delimiter, previousTokenizer) { return function (stream, state) { if (!state.escapeNext && stream.eat(delimiter)) { state.tokenize = previousTokenizer; } else { if (state.escapeNext) { state.escapeNext = false; } var ch = stream.next(); // Take into account the backslash for escaping characters, such as // the string delimiter. if (ch == "\\") { state.escapeNext = true; } } return "string"; }; } // Apply Django template variable syntax highlighting function inVariable (stream, state) { // Attempt to match a dot that precedes a property if (state.waitDot) { state.waitDot = false; if (stream.peek() != ".") { return "null"; } // Dot followed by a non-word character should be considered an error. if (stream.match(/\.\W+/)) { return "error"; } else if (stream.eat(".")) { state.waitProperty = true; return "null"; } else { throw Error ("Unexpected error while waiting for property."); } } // Attempt to match a pipe that precedes a filter if (state.waitPipe) { state.waitPipe = false; if (stream.peek() != "|") { return "null"; } // Pipe followed by a non-word character should be considered an error. if (stream.match(/\.\W+/)) { return "error"; } else if (stream.eat("|")) { state.waitFilter = true; return "null"; } else { throw Error ("Unexpected error while waiting for filter."); } } // Highlight properties if (state.waitProperty) { state.waitProperty = false; if (stream.match(/\b(\w+)\b/)) { state.waitDot = true; // A property can be followed by another property state.waitPipe = true; // A property can be followed by a filter return "property"; } } // Highlight filters if (state.waitFilter) { state.waitFilter = false; if (stream.match(filters)) { return "variable-2"; } } // Ignore all white spaces if (stream.eatSpace()) { state.waitProperty = false; return "null"; } // Identify numbers if (stream.match(/\b\d+(\.\d+)?\b/)) { return "number"; } // Identify strings if (stream.match("'")) { state.tokenize = inString("'", state.tokenize); return "string"; } else if (stream.match('"')) { state.tokenize = inString('"', state.tokenize); return "string"; } // Attempt to find the variable if (stream.match(/\b(\w+)\b/) && !state.foundVariable) { state.waitDot = true; state.waitPipe = true; // A property can be followed by a filter return "variable"; } // If found closing tag reset if (stream.match("}}")) { state.waitProperty = null; state.waitFilter = null; state.waitDot = null; state.waitPipe = null; state.tokenize = tokenBase; return "tag"; } // If nothing was found, advance to the next character stream.next(); return "null"; } function inTag (stream, state) { // Attempt to match a dot that precedes a property if (state.waitDot) { state.waitDot = false; if (stream.peek() != ".") { return "null"; } // Dot followed by a non-word character should be considered an error. if (stream.match(/\.\W+/)) { return "error"; } else if (stream.eat(".")) { state.waitProperty = true; return "null"; } else { throw Error ("Unexpected error while waiting for property."); } } // Attempt to match a pipe that precedes a filter if (state.waitPipe) { state.waitPipe = false; if (stream.peek() != "|") { return "null"; } // Pipe followed by a non-word character should be considered an error. if (stream.match(/\.\W+/)) { return "error"; } else if (stream.eat("|")) { state.waitFilter = true; return "null"; } else { throw Error ("Unexpected error while waiting for filter."); } } // Highlight properties if (state.waitProperty) { state.waitProperty = false; if (stream.match(/\b(\w+)\b/)) { state.waitDot = true; // A property can be followed by another property state.waitPipe = true; // A property can be followed by a filter return "property"; } } // Highlight filters if (state.waitFilter) { state.waitFilter = false; if (stream.match(filters)) { return "variable-2"; } } // Ignore all white spaces if (stream.eatSpace()) { state.waitProperty = false; return "null"; } // Identify numbers if (stream.match(/\b\d+(\.\d+)?\b/)) { return "number"; } // Identify strings if (stream.match("'")) { state.tokenize = inString("'", state.tokenize); return "string"; } else if (stream.match('"')) { state.tokenize = inString('"', state.tokenize); return "string"; } // Attempt to match an operator if (stream.match(operators)) { return "operator"; } // Attempt to match a word operator if (stream.match(wordOperators)) { return "keyword"; } // Attempt to match a keyword var keywordMatch = stream.match(keywords); if (keywordMatch) { if (keywordMatch[0] == "comment") { state.blockCommentTag = true; } return "keyword"; } // Attempt to match a variable if (stream.match(/\b(\w+)\b/)) { state.waitDot = true; state.waitPipe = true; // A property can be followed by a filter return "variable"; } // If found closing tag reset if (stream.match("%}")) { state.waitProperty = null; state.waitFilter = null; state.waitDot = null; state.waitPipe = null; // If the tag that closes is a block comment tag, we want to mark the // following code as comment, until the tag closes. if (state.blockCommentTag) { state.blockCommentTag = false; // Release the "lock" state.tokenize = inBlockComment; } else { state.tokenize = tokenBase; } return "tag"; } // If nothing was found, advance to the next character stream.next(); return "null"; } // Mark everything as comment inside the tag and the tag itself. function inComment (stream, state) { if (stream.match(/^.*?#\}/)) state.tokenize = tokenBase else stream.skipToEnd() return "comment"; } // Mark everything as a comment until the `blockcomment` tag closes. function inBlockComment (stream, state) { if (stream.match(/\{%\s*endcomment\s*%\}/, false)) { state.tokenize = inTag; stream.match("{%"); return "tag"; } else { stream.next(); return "comment"; } } return { startState: function () { return {tokenize: tokenBase}; }, token: function (stream, state) { return state.tokenize(stream, state); }, blockCommentStart: "{% comment %}", blockCommentEnd: "{% endcomment %}" }; }); CodeMirror.defineMode("django", function(config) { var htmlBase = CodeMirror.getMode(config, "text/html"); var djangoInner = CodeMirror.getMode(config, "django:inner"); return CodeMirror.overlayMode(htmlBase, djangoInner); }); CodeMirror.defineMIME("text/x-django", "django"); }); ================================================ FILE: third_party/CodeMirror/mode/django/index.html ================================================ CodeMirror: Django template mode

Django template mode

Mode for HTML with embedded Django template markup.

MIME types defined: text/x-django

================================================ FILE: third_party/CodeMirror/mode/dockerfile/dockerfile.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/simple")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../addon/mode/simple"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var from = "from"; var fromRegex = new RegExp("^(\\s*)\\b(" + from + ")\\b", "i"); var shells = ["run", "cmd", "entrypoint", "shell"]; var shellsAsArrayRegex = new RegExp("^(\\s*)(" + shells.join('|') + ")(\\s+\\[)", "i"); var expose = "expose"; var exposeRegex = new RegExp("^(\\s*)(" + expose + ")(\\s+)", "i"); var others = [ "arg", "from", "maintainer", "label", "env", "add", "copy", "volume", "user", "workdir", "onbuild", "stopsignal", "healthcheck", "shell" ]; // Collect all Dockerfile directives var instructions = [from, expose].concat(shells).concat(others), instructionRegex = "(" + instructions.join('|') + ")", instructionOnlyLine = new RegExp("^(\\s*)" + instructionRegex + "(\\s*)(#.*)?$", "i"), instructionWithArguments = new RegExp("^(\\s*)" + instructionRegex + "(\\s+)", "i"); CodeMirror.defineSimpleMode("dockerfile", { start: [ // Block comment: This is a line starting with a comment { regex: /^\s*#.*$/, sol: true, token: "comment" }, { regex: fromRegex, token: [null, "keyword"], sol: true, next: "from" }, // Highlight an instruction without any arguments (for convenience) { regex: instructionOnlyLine, token: [null, "keyword", null, "error"], sol: true }, { regex: shellsAsArrayRegex, token: [null, "keyword", null], sol: true, next: "array" }, { regex: exposeRegex, token: [null, "keyword", null], sol: true, next: "expose" }, // Highlight an instruction followed by arguments { regex: instructionWithArguments, token: [null, "keyword", null], sol: true, next: "arguments" }, { regex: /./, token: null } ], from: [ { regex: /\s*$/, token: null, next: "start" }, { // Line comment without instruction arguments is an error regex: /(\s*)(#.*)$/, token: [null, "error"], next: "start" }, { regex: /(\s*\S+\s+)(as)/i, token: [null, "keyword"], next: "start" }, // Fail safe return to start { token: null, next: "start" } ], single: [ { regex: /(?:[^\\']|\\.)/, token: "string" }, { regex: /'/, token: "string", pop: true } ], double: [ { regex: /(?:[^\\"]|\\.)/, token: "string" }, { regex: /"/, token: "string", pop: true } ], array: [ { regex: /\]/, token: null, next: "start" }, { regex: /"(?:[^\\"]|\\.)*"?/, token: "string" } ], expose: [ { regex: /\d+$/, token: "number", next: "start" }, { regex: /[^\d]+$/, token: null, next: "start" }, { regex: /\d+/, token: "number" }, { regex: /[^\d]+/, token: null }, // Fail safe return to start { token: null, next: "start" } ], arguments: [ { regex: /^\s*#.*$/, sol: true, token: "comment" }, { regex: /"(?:[^\\"]|\\.)*"?$/, token: "string", next: "start" }, { regex: /"/, token: "string", push: "double" }, { regex: /'(?:[^\\']|\\.)*'?$/, token: "string", next: "start" }, { regex: /'/, token: "string", push: "single" }, { regex: /[^#"']+[\\`]$/, token: null }, { regex: /[^#"']+$/, token: null, next: "start" }, { regex: /[^#"']+/, token: null }, // Fail safe return to start { token: null, next: "start" } ], meta: { lineComment: "#" } }); CodeMirror.defineMIME("text/x-dockerfile", "dockerfile"); }); ================================================ FILE: third_party/CodeMirror/mode/dockerfile/index.html ================================================ CodeMirror: Dockerfile mode

Dockerfile mode

Dockerfile syntax highlighting for CodeMirror. Depends on the simplemode addon.

MIME types defined: text/x-dockerfile

================================================ FILE: third_party/CodeMirror/mode/dockerfile/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-dockerfile"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("simple_nodejs_dockerfile", "[keyword FROM] node:carbon", "[comment # Create app directory]", "[keyword WORKDIR] /usr/src/app", "[comment # Install app dependencies]", "[comment # A wildcard is used to ensure both package.json AND package-lock.json are copied]", "[comment # where available (npm@5+)]", "[keyword COPY] package*.json ./", "[keyword RUN] npm install", "[keyword COPY] . .", "[keyword EXPOSE] [number 8080] [number 3000]", "[keyword ENV] NODE_ENV development", "[keyword CMD] [[ [string \"npm\"], [string \"start\"] ]]"); // Ideally the last space should not be highlighted. MT("instruction_without_args_1", "[keyword CMD] "); MT("instruction_without_args_2", "[comment # An instruction without args...]", "[keyword ARG] [error #...is an error]"); MT("multiline", "[keyword RUN] apt-get update && apt-get install -y \\", " mercurial \\", " subversion \\", " && apt-get clean \\", " && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*"); MT("from_comment", " [keyword FROM] debian:stretch # I tend to use stable as that is more stable", " [keyword FROM] debian:stretch [keyword AS] stable # I am even more stable", " [keyword FROM] [error # this is an error]"); MT("from_as", "[keyword FROM] golang:1.9.2-alpine3.6 [keyword AS] build", "[keyword COPY] --from=build /bin/project /bin/project", "[keyword ENTRYPOINT] [[ [string \"/bin/project\"] ]]", "[keyword CMD] [[ [string \"--help\"] ]]"); MT("arg", "[keyword ARG] VERSION=latest", "[keyword FROM] busybox:$VERSION", "[keyword ARG] VERSION", "[keyword RUN] echo $VERSION > image_version"); MT("label", "[keyword LABEL] com.example.label-with-value=[string \"foo\"]"); MT("label_multiline", "[keyword LABEL] description=[string \"This text illustrates ]\\", "[string that label-values can span multiple lines.\"]"); MT("maintainer", "[keyword MAINTAINER] Foo Bar [string \"foo@bar.com\"] ", "[keyword MAINTAINER] Bar Baz "); MT("env", "[keyword ENV] BUNDLE_PATH=[string \"$GEM_HOME\"] \\", " BUNDLE_APP_CONFIG=[string \"$GEM_HOME\"]"); MT("verify_keyword", "[keyword RUN] add-apt-repository ppa:chris-lea/node.js"); MT("scripts", "[comment # Set an entrypoint, to automatically install node modules]", "[keyword ENTRYPOINT] [[ [string \"/bin/bash\"], [string \"-c\"], [string \"if [[ ! -d node_modules ]]; then npm install; fi; exec \\\"${@:0}\\\";\"] ]]", "[keyword CMD] npm start", "[keyword RUN] npm run build && \\", "[comment # a comment between the shell commands]", " npm run test"); MT("strings_single", "[keyword FROM] buildpack-deps:stretch", "[keyword RUN] { \\", " echo [string 'install: --no-document']; \\", " echo [string 'update: --no-document']; \\", " } >> /usr/local/etc/gemrc"); MT("strings_single_multiline", "[keyword RUN] set -ex \\", " \\", " && buildDeps=[string ' ]\\", "[string bison ]\\", "[string dpkg-dev ]\\", "[string libgdbm-dev ]\\", "[string ruby ]\\", "[string '] \\", " && apt-get update"); MT("strings_single_multiline_2", "[keyword RUN] echo [string 'say \\' ]\\", "[string it works'] "); MT("strings_double", "[keyword RUN] apt-get install -y --no-install-recommends $buildDeps \\", " \\", " && wget -O ruby.tar.xz [string \"https://cache.ruby-lang.org/pub/ruby/${RUBY_MAJOR%-rc}/ruby-$RUBY_VERSION.tar.xz\"] \\", " && echo [string \"$RUBY_DOWNLOAD_SHA256 *ruby.tar.xz\"] | sha256sum -c - "); MT("strings_double_multiline", "[keyword RUN] echo [string \"say \\\" ]\\", "[string it works\"] "); MT("escape", "[comment # escape=`]", "[keyword FROM] microsoft/windowsservercore", "[keyword RUN] powershell.exe -Command `", " $ErrorActionPreference = [string 'Stop']; `", " wget https://www.python.org/ftp/python/3.5.1/python-3.5.1.exe -OutFile c:\python-3.5.1.exe ; `", " Start-Process c:\python-3.5.1.exe -ArgumentList [string '/quiet InstallAllUsers=1 PrependPath=1'] -Wait ; `", " Remove-Item c:\python-3.5.1.exe -Force)"); MT("escape_strings", "[comment # escape=`]", "[keyword FROM] python:3.6-windowsservercore [keyword AS] python", "[keyword RUN] $env:PATH = [string 'C:\\Python;C:\\Python\\Scripts;{0}'] -f $env:PATH ; `", // It should not consider \' as escaped. // " Set-ItemProperty -Path [string 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\'] -Name Path -Value $env:PATH ;"); " Set-ItemProperty -Path [string 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment\\' -Name Path -Value $env:PATH ;]"); })(); ================================================ FILE: third_party/CodeMirror/mode/dtd/dtd.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /* DTD mode Ported to CodeMirror by Peter Kroon Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues GitHub: @peterkroon */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("dtd", function(config) { var indentUnit = config.indentUnit, type; function ret(style, tp) {type = tp; return style;} function tokenBase(stream, state) { var ch = stream.next(); if (ch == "<" && stream.eat("!") ) { if (stream.eatWhile(/[\-]/)) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (stream.eatWhile(/[\w]/)) return ret("keyword", "doindent"); } else if (ch == "<" && stream.eat("?")) { //xml declaration state.tokenize = inBlock("meta", "?>"); return ret("meta", ch); } else if (ch == "#" && stream.eatWhile(/[\w]/)) return ret("atom", "tag"); else if (ch == "|") return ret("keyword", "seperator"); else if (ch.match(/[\(\)\[\]\-\.,\+\?>]/)) return ret(null, ch);//if(ch === ">") return ret(null, "endtag"); else else if (ch.match(/[\[\]]/)) return ret("rule", ch); else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (stream.eatWhile(/[a-zA-Z\?\+\d]/)) { var sc = stream.current(); if( sc.substr(sc.length-1,sc.length).match(/\?|\+/) !== null )stream.backUp(1); return ret("tag", "tag"); } else if (ch == "%" || ch == "*" ) return ret("number", "number"); else { stream.eatWhile(/[\w\\\-_%.{,]/); return ret(null, null); } } function tokenSGMLComment(stream, state) { var dashes = 0, ch; while ((ch = stream.next()) != null) { if (dashes >= 2 && ch == ">") { state.tokenize = tokenBase; break; } dashes = (ch == "-") ? dashes + 1 : 0; } return ret("comment", "comment"); } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = !escaped && ch == "\\"; } return ret("string", "tag"); }; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = tokenBase; break; } stream.next(); } return style; }; } return { startState: function(base) { return {tokenize: tokenBase, baseIndent: base || 0, stack: []}; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); var context = state.stack[state.stack.length-1]; if (stream.current() == "[" || type === "doindent" || type == "[") state.stack.push("rule"); else if (type === "endtag") state.stack[state.stack.length-1] = "endtag"; else if (stream.current() == "]" || type == "]" || (type == ">" && context == "rule")) state.stack.pop(); else if (type == "[") state.stack.push("["); return style; }, indent: function(state, textAfter) { var n = state.stack.length; if( textAfter.match(/\]\s+|\]/) )n=n-1; else if(textAfter.substr(textAfter.length-1, textAfter.length) === ">"){ if(textAfter.substr(0,1) === "<") {} else if( type == "doindent" && textAfter.length > 1 ) {} else if( type == "doindent")n--; else if( type == ">" && textAfter.length > 1) {} else if( type == "tag" && textAfter !== ">") {} else if( type == "tag" && state.stack[state.stack.length-1] == "rule")n--; else if( type == "tag")n++; else if( textAfter === ">" && state.stack[state.stack.length-1] == "rule" && type === ">")n--; else if( textAfter === ">" && state.stack[state.stack.length-1] == "rule") {} else if( textAfter.substr(0,1) !== "<" && textAfter.substr(0,1) === ">" )n=n-1; else if( textAfter === ">") {} else n=n-1; //over rule them all if(type == null || type == "]")n--; } return state.baseIndent + n * indentUnit; }, electricChars: "]>" }; }); CodeMirror.defineMIME("application/xml-dtd", "dtd"); }); ================================================ FILE: third_party/CodeMirror/mode/dtd/index.html ================================================ CodeMirror: DTD mode

DTD mode

MIME types defined: application/xml-dtd.

================================================ FILE: third_party/CodeMirror/mode/dylan/dylan.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function forEach(arr, f) { for (var i = 0; i < arr.length; i++) f(arr[i], i) } function some(arr, f) { for (var i = 0; i < arr.length; i++) if (f(arr[i], i)) return true return false } CodeMirror.defineMode("dylan", function(_config) { // Words var words = { // Words that introduce unnamed definitions like "define interface" unnamedDefinition: ["interface"], // Words that introduce simple named definitions like "define library" namedDefinition: ["module", "library", "macro", "C-struct", "C-union", "C-function", "C-callable-wrapper" ], // Words that introduce type definitions like "define class". // These are also parameterized like "define method" and are // appended to otherParameterizedDefinitionWords typeParameterizedDefinition: ["class", "C-subtype", "C-mapped-subtype"], // Words that introduce trickier definitions like "define method". // These require special definitions to be added to startExpressions otherParameterizedDefinition: ["method", "function", "C-variable", "C-address" ], // Words that introduce module constant definitions. // These must also be simple definitions and are // appended to otherSimpleDefinitionWords constantSimpleDefinition: ["constant"], // Words that introduce module variable definitions. // These must also be simple definitions and are // appended to otherSimpleDefinitionWords variableSimpleDefinition: ["variable"], // Other words that introduce simple definitions // (without implicit bodies). otherSimpleDefinition: ["generic", "domain", "C-pointer-type", "table" ], // Words that begin statements with implicit bodies. statement: ["if", "block", "begin", "method", "case", "for", "select", "when", "unless", "until", "while", "iterate", "profiling", "dynamic-bind" ], // Patterns that act as separators in compound statements. // This may include any general pattern that must be indented // specially. separator: ["finally", "exception", "cleanup", "else", "elseif", "afterwards" ], // Keywords that do not require special indentation handling, // but which should be highlighted other: ["above", "below", "by", "from", "handler", "in", "instance", "let", "local", "otherwise", "slot", "subclass", "then", "to", "keyed-by", "virtual" ], // Condition signaling function calls signalingCalls: ["signal", "error", "cerror", "break", "check-type", "abort" ] }; words["otherDefinition"] = words["unnamedDefinition"] .concat(words["namedDefinition"]) .concat(words["otherParameterizedDefinition"]); words["definition"] = words["typeParameterizedDefinition"] .concat(words["otherDefinition"]); words["parameterizedDefinition"] = words["typeParameterizedDefinition"] .concat(words["otherParameterizedDefinition"]); words["simpleDefinition"] = words["constantSimpleDefinition"] .concat(words["variableSimpleDefinition"]) .concat(words["otherSimpleDefinition"]); words["keyword"] = words["statement"] .concat(words["separator"]) .concat(words["other"]); // Patterns var symbolPattern = "[-_a-zA-Z?!*@<>$%]+"; var symbol = new RegExp("^" + symbolPattern); var patterns = { // Symbols with special syntax symbolKeyword: symbolPattern + ":", symbolClass: "<" + symbolPattern + ">", symbolGlobal: "\\*" + symbolPattern + "\\*", symbolConstant: "\\$" + symbolPattern }; var patternStyles = { symbolKeyword: "atom", symbolClass: "tag", symbolGlobal: "variable-2", symbolConstant: "variable-3" }; // Compile all patterns to regular expressions for (var patternName in patterns) if (patterns.hasOwnProperty(patternName)) patterns[patternName] = new RegExp("^" + patterns[patternName]); // Names beginning "with-" and "without-" are commonly // used as statement macro patterns["keyword"] = [/^with(?:out)?-[-_a-zA-Z?!*@<>$%]+/]; var styles = {}; styles["keyword"] = "keyword"; styles["definition"] = "def"; styles["simpleDefinition"] = "def"; styles["signalingCalls"] = "builtin"; // protected words lookup table var wordLookup = {}; var styleLookup = {}; forEach([ "keyword", "definition", "simpleDefinition", "signalingCalls" ], function(type) { forEach(words[type], function(word) { wordLookup[word] = type; styleLookup[word] = styles[type]; }); }); function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenBase(stream, state) { // String var ch = stream.peek(); if (ch == "'" || ch == '"') { stream.next(); return chain(stream, state, tokenString(ch, "string")); } // Comment else if (ch == "/") { stream.next(); if (stream.eat("*")) { return chain(stream, state, tokenComment); } else if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } stream.backUp(1); } // Decimal else if (/[+\-\d\.]/.test(ch)) { if (stream.match(/^[+-]?[0-9]*\.[0-9]*([esdx][+-]?[0-9]+)?/i) || stream.match(/^[+-]?[0-9]+([esdx][+-]?[0-9]+)/i) || stream.match(/^[+-]?\d+/)) { return "number"; } } // Hash else if (ch == "#") { stream.next(); // Symbol with string syntax ch = stream.peek(); if (ch == '"') { stream.next(); return chain(stream, state, tokenString('"', "string")); } // Binary number else if (ch == "b") { stream.next(); stream.eatWhile(/[01]/); return "number"; } // Hex number else if (ch == "x") { stream.next(); stream.eatWhile(/[\da-f]/i); return "number"; } // Octal number else if (ch == "o") { stream.next(); stream.eatWhile(/[0-7]/); return "number"; } // Token concatenation in macros else if (ch == '#') { stream.next(); return "punctuation"; } // Sequence literals else if ((ch == '[') || (ch == '(')) { stream.next(); return "bracket"; // Hash symbol } else if (stream.match(/f|t|all-keys|include|key|next|rest/i)) { return "atom"; } else { stream.eatWhile(/[-a-zA-Z]/); return "error"; } } else if (ch == "~") { stream.next(); ch = stream.peek(); if (ch == "=") { stream.next(); ch = stream.peek(); if (ch == "=") { stream.next(); return "operator"; } return "operator"; } return "operator"; } else if (ch == ":") { stream.next(); ch = stream.peek(); if (ch == "=") { stream.next(); return "operator"; } else if (ch == ":") { stream.next(); return "punctuation"; } } else if ("[](){}".indexOf(ch) != -1) { stream.next(); return "bracket"; } else if (".,".indexOf(ch) != -1) { stream.next(); return "punctuation"; } else if (stream.match("end")) { return "keyword"; } for (var name in patterns) { if (patterns.hasOwnProperty(name)) { var pattern = patterns[name]; if ((pattern instanceof Array && some(pattern, function(p) { return stream.match(p); })) || stream.match(pattern)) return patternStyles[name]; } } if (/[+\-*\/^=<>&|]/.test(ch)) { stream.next(); return "operator"; } if (stream.match("define")) { return "def"; } else { stream.eatWhile(/[\w\-]/); // Keyword if (wordLookup.hasOwnProperty(stream.current())) { return styleLookup[stream.current()]; } else if (stream.current().match(symbol)) { return "variable"; } else { stream.next(); return "variable-2"; } } } function tokenComment(stream, state) { var maybeEnd = false, maybeNested = false, nestedCount = 0, ch; while ((ch = stream.next())) { if (ch == "/" && maybeEnd) { if (nestedCount > 0) { nestedCount--; } else { state.tokenize = tokenBase; break; } } else if (ch == "*" && maybeNested) { nestedCount++; } maybeEnd = (ch == "*"); maybeNested = (ch == "/"); } return "comment"; } function tokenString(quote, style) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) { end = true; break; } escaped = !escaped && next == "\\"; } if (end || !escaped) { state.tokenize = tokenBase; } return style; }; } // Interface return { startState: function() { return { tokenize: tokenBase, currentIndent: 0 }; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); return style; }, blockCommentStart: "/*", blockCommentEnd: "*/" }; }); CodeMirror.defineMIME("text/x-dylan", "dylan"); }); ================================================ FILE: third_party/CodeMirror/mode/dylan/index.html ================================================ CodeMirror: Dylan mode

Dylan mode

MIME types defined: text/x-dylan.

================================================ FILE: third_party/CodeMirror/mode/dylan/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "dylan"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT('comments', '[comment // This is a line comment]', '[comment /* This is a block comment */]', '[comment /* This is a multi]', '[comment line comment]', '[comment */]', '[comment /* And this is a /*]', '[comment /* nested */ comment */]'); MT('unary_operators', '[operator -][variable a]', '[operator -] [variable a]', '[operator ~][variable a]', '[operator ~] [variable a]'); MT('binary_operators', '[variable a] [operator +] [variable b]', '[variable a] [operator -] [variable b]', '[variable a] [operator *] [variable b]', '[variable a] [operator /] [variable b]', '[variable a] [operator ^] [variable b]', '[variable a] [operator =] [variable b]', '[variable a] [operator ==] [variable b]', '[variable a] [operator ~=] [variable b]', '[variable a] [operator ~==] [variable b]', '[variable a] [operator <] [variable b]', '[variable a] [operator <=] [variable b]', '[variable a] [operator >] [variable b]', '[variable a] [operator >=] [variable b]', '[variable a] [operator &] [variable b]', '[variable a] [operator |] [variable b]', '[variable a] [operator :=] [variable b]'); MT('integers', '[number 1]', '[number 123]', '[number -123]', '[number +456]', '[number #b010]', '[number #o073]', '[number #xabcDEF123]'); MT('floats', '[number .3]', '[number -1.]', '[number -2.335]', '[number +3.78d1]', '[number 3.78s-1]', '[number -3.32e+5]'); MT('characters_and_strings', "[string 'a']", "[string '\\\\'']", '[string ""]', '[string "a"]', '[string "abc def"]', '[string "More escaped characters: \\\\\\\\ \\\\a \\\\b \\\\e \\\\f \\\\n \\\\r \\\\t \\\\0 ..."]'); MT('brackets', '[bracket #[[]]]', '[bracket #()]', '[bracket #(][number 1][bracket )]', '[bracket [[][number 1][punctuation ,] [number 3][bracket ]]]', '[bracket ()]', '[bracket {}]', '[keyword if] [bracket (][variable foo][bracket )]', '[bracket (][number 1][bracket )]', '[bracket [[][number 1][bracket ]]]'); MT('hash_words', '[punctuation ##]', '[atom #f]', '[atom #F]', '[atom #t]', '[atom #T]', '[atom #all-keys]', '[atom #include]', '[atom #key]', '[atom #next]', '[atom #rest]', '[string #"foo"]', '[error #invalid]'); })(); ================================================ FILE: third_party/CodeMirror/mode/ebnf/ebnf.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("ebnf", function (config) { var commentType = {slash: 0, parenthesis: 1}; var stateType = {comment: 0, _string: 1, characterClass: 2}; var bracesMode = null; if (config.bracesMode) bracesMode = CodeMirror.getMode(config, config.bracesMode); return { startState: function () { return { stringType: null, commentType: null, braced: 0, lhs: true, localState: null, stack: [], inDefinition: false }; }, token: function (stream, state) { if (!stream) return; //check for state changes if (state.stack.length === 0) { //strings if ((stream.peek() == '"') || (stream.peek() == "'")) { state.stringType = stream.peek(); stream.next(); // Skip quote state.stack.unshift(stateType._string); } else if (stream.match(/^\/\*/)) { //comments starting with /* state.stack.unshift(stateType.comment); state.commentType = commentType.slash; } else if (stream.match(/^\(\*/)) { //comments starting with (* state.stack.unshift(stateType.comment); state.commentType = commentType.parenthesis; } } //return state //stack has switch (state.stack[0]) { case stateType._string: while (state.stack[0] === stateType._string && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.stack.shift(); // Clear flag } else if (stream.peek() === "\\") { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return state.lhs ? "property string" : "string"; // Token style case stateType.comment: while (state.stack[0] === stateType.comment && !stream.eol()) { if (state.commentType === commentType.slash && stream.match(/\*\//)) { state.stack.shift(); // Clear flag state.commentType = null; } else if (state.commentType === commentType.parenthesis && stream.match(/\*\)/)) { state.stack.shift(); // Clear flag state.commentType = null; } else { stream.match(/^.[^\*]*/); } } return "comment"; case stateType.characterClass: while (state.stack[0] === stateType.characterClass && !stream.eol()) { if (!(stream.match(/^[^\]\\]+/) || stream.match(/^\\./))) { state.stack.shift(); } } return "operator"; } var peek = stream.peek(); if (bracesMode !== null && (state.braced || peek === "{")) { if (state.localState === null) state.localState = CodeMirror.startState(bracesMode); var token = bracesMode.token(stream, state.localState), text = stream.current(); if (!token) { for (var i = 0; i < text.length; i++) { if (text[i] === "{") { if (state.braced === 0) { token = "matchingbracket"; } state.braced++; } else if (text[i] === "}") { state.braced--; if (state.braced === 0) { token = "matchingbracket"; } } } } return token; } //no stack switch (peek) { case "[": stream.next(); state.stack.unshift(stateType.characterClass); return "bracket"; case ":": case "|": case ";": stream.next(); return "operator"; case "%": if (stream.match("%%")) { return "header"; } else if (stream.match(/[%][A-Za-z]+/)) { return "keyword"; } else if (stream.match(/[%][}]/)) { return "matchingbracket"; } break; case "/": if (stream.match(/[\/][A-Za-z]+/)) { return "keyword"; } case "\\": if (stream.match(/[\][a-z]+/)) { return "string-2"; } case ".": if (stream.match(".")) { return "atom"; } case "*": case "-": case "+": case "^": if (stream.match(peek)) { return "atom"; } case "$": if (stream.match("$$")) { return "builtin"; } else if (stream.match(/[$][0-9]+/)) { return "variable-3"; } case "<": if (stream.match(/<<[a-zA-Z_]+>>/)) { return "builtin"; } } if (stream.match(/^\/\//)) { stream.skipToEnd(); return "comment"; } else if (stream.match(/return/)) { return "operator"; } else if (stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/)) { if (stream.match(/(?=[\(.])/)) { return "variable"; } else if (stream.match(/(?=[\s\n]*[:=])/)) { return "def"; } return "variable-2"; } else if (["[", "]", "(", ")"].indexOf(stream.peek()) != -1) { stream.next(); return "bracket"; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }); CodeMirror.defineMIME("text/x-ebnf", "ebnf"); }); ================================================ FILE: third_party/CodeMirror/mode/ebnf/index.html ================================================ CodeMirror: EBNF Mode

EBNF Mode (bracesMode setting = "javascript")

The EBNF Mode

Created by Robert Plummer

================================================ FILE: third_party/CodeMirror/mode/ecl/ecl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("ecl", function(config) { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function metaHook(stream, state) { if (!state.startOfLine) return false; stream.skipToEnd(); return "meta"; } var indentUnit = config.indentUnit; 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"); var variable = words("apply assert build buildindex evaluate fail keydiff keypatch loadxml nothor notify output parallel sequential soapcall wait"); 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"); 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"); var builtin = words("checkpoint deprecated failcode failmessage failure global independent onwarning persist priority recovery stored success wait when"); var blockKeywords = words("catch class do else finally for if switch try while"); var atoms = words("true false null"); var hooks = {"#": metaHook}; var isOperatorChar = /[+\-*&%=<>!?|\/]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[\[\]{}\(\),;\:\.]/.test(ch)) { curPunc = ch; return null; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_]/); var cur = stream.current().toLowerCase(); if (keyword.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "keyword"; } else if (variable.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "variable"; } else if (variable_2.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "variable-2"; } else if (variable_3.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "variable-3"; } else if (builtin.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; return "builtin"; } else { //Data types are of from KEYWORD## var i = cur.length - 1; while(i >= 0 && (!isNaN(cur[i]) || cur[i] == '_')) --i; if (i > 0) { var cur2 = cur.substr(0, i + 1); if (variable_3.propertyIsEnumerable(cur2)) { if (blockKeywords.propertyIsEnumerable(cur2)) curPunc = "newstatement"; return "variable-3"; } } } if (atoms.propertyIsEnumerable(cur)) return "atom"; return null; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !escaped) state.tokenize = tokenBase; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { return state.context = new Context(state.indented, col, type, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; curPunc = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) pushContext(state, stream.column(), "statement"); state.startOfLine = false; return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null) return 0; var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; var closing = firstChar == ctx.type; if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit); else if (ctx.align) return ctx.column + (closing ? 0 : 1); else return ctx.indented + (closing ? 0 : indentUnit); }, electricChars: "{}" }; }); CodeMirror.defineMIME("text/x-ecl", "ecl"); }); ================================================ FILE: third_party/CodeMirror/mode/ecl/index.html ================================================ CodeMirror: ECL mode

ECL mode

Based on CodeMirror's clike mode. For more information see HPCC Systems web site.

MIME types defined: text/x-ecl.

================================================ FILE: third_party/CodeMirror/mode/eiffel/eiffel.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("eiffel", function() { function wordObj(words) { var o = {}; for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; return o; } var keywords = wordObj([ 'note', 'across', 'when', 'variant', 'until', 'unique', 'undefine', 'then', 'strip', 'select', 'retry', 'rescue', 'require', 'rename', 'reference', 'redefine', 'prefix', 'once', 'old', 'obsolete', 'loop', 'local', 'like', 'is', 'inspect', 'infix', 'include', 'if', 'frozen', 'from', 'external', 'export', 'ensure', 'end', 'elseif', 'else', 'do', 'creation', 'create', 'check', 'alias', 'agent', 'separate', 'invariant', 'inherit', 'indexing', 'feature', 'expanded', 'deferred', 'class', 'Void', 'True', 'Result', 'Precursor', 'False', 'Current', 'create', 'attached', 'detachable', 'as', 'and', 'implies', 'not', 'or' ]); var operators = wordObj([":=", "and then","and", "or","<<",">>"]); function chain(newtok, stream, state) { state.tokenize.push(newtok); return newtok(stream, state); } function tokenBase(stream, state) { if (stream.eatSpace()) return null; var ch = stream.next(); if (ch == '"'||ch == "'") { return chain(readQuoted(ch, "string"), stream, state); } else if (ch == "-"&&stream.eat("-")) { stream.skipToEnd(); return "comment"; } else if (ch == ":"&&stream.eat("=")) { return "operator"; } else if (/[0-9]/.test(ch)) { stream.eatWhile(/[xXbBCc0-9\.]/); stream.eat(/[\?\!]/); return "ident"; } else if (/[a-zA-Z_0-9]/.test(ch)) { stream.eatWhile(/[a-zA-Z_0-9]/); stream.eat(/[\?\!]/); return "ident"; } else if (/[=+\-\/*^%<>~]/.test(ch)) { stream.eatWhile(/[=+\-\/*^%<>~]/); return "operator"; } else { return null; } } function readQuoted(quote, style, unescaped) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && (unescaped || !escaped)) { state.tokenize.pop(); break; } escaped = !escaped && ch == "%"; } return style; }; } return { startState: function() { return {tokenize: [tokenBase]}; }, token: function(stream, state) { var style = state.tokenize[state.tokenize.length-1](stream, state); if (style == "ident") { var word = stream.current(); style = keywords.propertyIsEnumerable(stream.current()) ? "keyword" : operators.propertyIsEnumerable(stream.current()) ? "operator" : /^[A-Z][A-Z_0-9]*$/g.test(word) ? "tag" : /^0[bB][0-1]+$/g.test(word) ? "number" : /^0[cC][0-7]+$/g.test(word) ? "number" : /^0[xX][a-fA-F0-9]+$/g.test(word) ? "number" : /^([0-9]+\.[0-9]*)|([0-9]*\.[0-9]+)$/g.test(word) ? "number" : /^[0-9]+$/g.test(word) ? "number" : "variable"; } return style; }, lineComment: "--" }; }); CodeMirror.defineMIME("text/x-eiffel", "eiffel"); }); ================================================ FILE: third_party/CodeMirror/mode/eiffel/index.html ================================================ CodeMirror: Eiffel mode

Eiffel mode

MIME types defined: text/x-eiffel.

Created by YNH.

================================================ FILE: third_party/CodeMirror/mode/elm/elm.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("elm", function() { function switchState(source, setState, f) { setState(f); return f(source, setState); } // These should all be Unicode extended, as per the Haskell 2010 report var smallRE = /[a-z_]/; var largeRE = /[A-Z]/; var digitRE = /[0-9]/; var hexitRE = /[0-9A-Fa-f]/; var octitRE = /[0-7]/; var idRE = /[a-z_A-Z0-9\']/; var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:\u03BB\u2192]/; var specialRE = /[(),;[\]`{}]/; var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer function normal() { return function (source, setState) { if (source.eatWhile(whiteCharRE)) { return null; } var ch = source.next(); if (specialRE.test(ch)) { if (ch == '{' && source.eat('-')) { var t = "comment"; if (source.eat('#')) t = "meta"; return switchState(source, setState, ncomment(t, 1)); } return null; } if (ch == '\'') { if (source.eat('\\')) source.next(); // should handle other escapes here else source.next(); if (source.eat('\'')) return "string"; return "error"; } if (ch == '"') { return switchState(source, setState, stringLiteral); } if (largeRE.test(ch)) { source.eatWhile(idRE); if (source.eat('.')) return "qualifier"; return "variable-2"; } if (smallRE.test(ch)) { var isDef = source.pos === 1; source.eatWhile(idRE); return isDef ? "type" : "variable"; } if (digitRE.test(ch)) { if (ch == '0') { if (source.eat(/[xX]/)) { source.eatWhile(hexitRE); // should require at least 1 return "integer"; } if (source.eat(/[oO]/)) { source.eatWhile(octitRE); // should require at least 1 return "number"; } } source.eatWhile(digitRE); var t = "number"; if (source.eat('.')) { t = "number"; source.eatWhile(digitRE); // should require at least 1 } if (source.eat(/[eE]/)) { t = "number"; source.eat(/[-+]/); source.eatWhile(digitRE); // should require at least 1 } return t; } if (symbolRE.test(ch)) { if (ch == '-' && source.eat(/-/)) { source.eatWhile(/-/); if (!source.eat(symbolRE)) { source.skipToEnd(); return "comment"; } } source.eatWhile(symbolRE); return "builtin"; } return "error"; } } function ncomment(type, nest) { if (nest == 0) { return normal(); } return function(source, setState) { var currNest = nest; while (!source.eol()) { var ch = source.next(); if (ch == '{' && source.eat('-')) { ++currNest; } else if (ch == '-' && source.eat('}')) { --currNest; if (currNest == 0) { setState(normal()); return type; } } } setState(ncomment(type, currNest)); return type; } } function stringLiteral(source, setState) { while (!source.eol()) { var ch = source.next(); if (ch == '"') { setState(normal()); return "string"; } if (ch == '\\') { if (source.eol() || source.eat(whiteCharRE)) { setState(stringGap); return "string"; } if (!source.eat('&')) source.next(); // should handle other escapes here } } setState(normal()); return "error"; } function stringGap(source, setState) { if (source.eat('\\')) { return switchState(source, setState, stringLiteral); } source.next(); setState(normal()); return "error"; } var wellKnownWords = (function() { var wkw = {}; var keywords = [ "case", "of", "as", "if", "then", "else", "let", "in", "infix", "infixl", "infixr", "type", "alias", "input", "output", "foreign", "loopback", "module", "where", "import", "exposing", "_", "..", "|", ":", "=", "\\", "\"", "->", "<-" ]; for (var i = keywords.length; i--;) wkw[keywords[i]] = "keyword"; return wkw; })(); return { startState: function () { return { f: normal() }; }, copyState: function (s) { return { f: s.f }; }, token: function(stream, state) { var t = state.f(stream, function(s) { state.f = s; }); var w = stream.current(); return (wellKnownWords.hasOwnProperty(w)) ? wellKnownWords[w] : t; } }; }); CodeMirror.defineMIME("text/x-elm", "elm"); }); ================================================ FILE: third_party/CodeMirror/mode/elm/index.html ================================================ CodeMirror: Elm mode

Elm mode

MIME types defined: text/x-elm.

================================================ FILE: third_party/CodeMirror/mode/erlang/erlang.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /*jshint unused:true, eqnull:true, curly:true, bitwise:true */ /*jshint undef:true, latedef:true, trailing:true */ /*global CodeMirror:true */ // erlang mode. // tokenizer -> token types -> CodeMirror styles // tokenizer maintains a parse stack // indenter uses the parse stack // TODO indenter: // bit syntax // old guard/bif/conversion clashes (e.g. "float/1") // type/spec/opaque (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMIME("text/x-erlang", "erlang"); CodeMirror.defineMode("erlang", function(cmCfg) { "use strict"; ///////////////////////////////////////////////////////////////////////////// // constants var typeWords = [ "-type", "-spec", "-export_type", "-opaque"]; var keywordWords = [ "after","begin","catch","case","cond","end","fun","if", "let","of","query","receive","try","when"]; var separatorRE = /[\->,;]/; var separatorWords = [ "->",";",","]; var operatorAtomWords = [ "and","andalso","band","bnot","bor","bsl","bsr","bxor", "div","not","or","orelse","rem","xor"]; var operatorSymbolRE = /[\+\-\*\/<>=\|:!]/; var operatorSymbolWords = [ "=","+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-","!"]; var openParenRE = /[<\(\[\{]/; var openParenWords = [ "<<","(","[","{"]; var closeParenRE = /[>\)\]\}]/; var closeParenWords = [ "}","]",")",">>"]; var guardWords = [ "is_atom","is_binary","is_bitstring","is_boolean","is_float", "is_function","is_integer","is_list","is_number","is_pid", "is_port","is_record","is_reference","is_tuple", "atom","binary","bitstring","boolean","function","integer","list", "number","pid","port","record","reference","tuple"]; var bifWords = [ "abs","adler32","adler32_combine","alive","apply","atom_to_binary", "atom_to_list","binary_to_atom","binary_to_existing_atom", "binary_to_list","binary_to_term","bit_size","bitstring_to_list", "byte_size","check_process_code","contact_binary","crc32", "crc32_combine","date","decode_packet","delete_module", "disconnect_node","element","erase","exit","float","float_to_list", "garbage_collect","get","get_keys","group_leader","halt","hd", "integer_to_list","internal_bif","iolist_size","iolist_to_binary", "is_alive","is_atom","is_binary","is_bitstring","is_boolean", "is_float","is_function","is_integer","is_list","is_number","is_pid", "is_port","is_process_alive","is_record","is_reference","is_tuple", "length","link","list_to_atom","list_to_binary","list_to_bitstring", "list_to_existing_atom","list_to_float","list_to_integer", "list_to_pid","list_to_tuple","load_module","make_ref","module_loaded", "monitor_node","node","node_link","node_unlink","nodes","notalive", "now","open_port","pid_to_list","port_close","port_command", "port_connect","port_control","pre_loaded","process_flag", "process_info","processes","purge_module","put","register", "registered","round","self","setelement","size","spawn","spawn_link", "spawn_monitor","spawn_opt","split_binary","statistics", "term_to_binary","time","throw","tl","trunc","tuple_size", "tuple_to_list","unlink","unregister","whereis"]; // upper case: [A-Z] [Ø-Þ] [À-Ö] // lower case: [a-z] [ß-ö] [ø-ÿ] var anumRE = /[\w@Ø-ÞÀ-Öß-öø-ÿ]/; var escapesRE = /[0-7]{1,3}|[bdefnrstv\\"']|\^[a-zA-Z]|x[0-9a-zA-Z]{2}|x{[0-9a-zA-Z]+}/; ///////////////////////////////////////////////////////////////////////////// // tokenizer function tokenizer(stream,state) { // in multi-line string if (state.in_string) { state.in_string = (!doubleQuote(stream)); return rval(state,stream,"string"); } // in multi-line atom if (state.in_atom) { state.in_atom = (!singleQuote(stream)); return rval(state,stream,"atom"); } // whitespace if (stream.eatSpace()) { return rval(state,stream,"whitespace"); } // attributes and type specs if (!peekToken(state) && stream.match(/-\s*[a-zß-öø-ÿ][\wØ-ÞÀ-Öß-öø-ÿ]*/)) { if (is_member(stream.current(),typeWords)) { return rval(state,stream,"type"); }else{ return rval(state,stream,"attribute"); } } var ch = stream.next(); // comment if (ch == '%') { stream.skipToEnd(); return rval(state,stream,"comment"); } // colon if (ch == ":") { return rval(state,stream,"colon"); } // macro if (ch == '?') { stream.eatSpace(); stream.eatWhile(anumRE); return rval(state,stream,"macro"); } // record if (ch == "#") { stream.eatSpace(); stream.eatWhile(anumRE); return rval(state,stream,"record"); } // dollar escape if (ch == "$") { if (stream.next() == "\\" && !stream.match(escapesRE)) { return rval(state,stream,"error"); } return rval(state,stream,"number"); } // dot if (ch == ".") { return rval(state,stream,"dot"); } // quoted atom if (ch == '\'') { if (!(state.in_atom = (!singleQuote(stream)))) { if (stream.match(/\s*\/\s*[0-9]/,false)) { stream.match(/\s*\/\s*[0-9]/,true); return rval(state,stream,"fun"); // 'f'/0 style fun } if (stream.match(/\s*\(/,false) || stream.match(/\s*:/,false)) { return rval(state,stream,"function"); } } return rval(state,stream,"atom"); } // string if (ch == '"') { state.in_string = (!doubleQuote(stream)); return rval(state,stream,"string"); } // variable if (/[A-Z_Ø-ÞÀ-Ö]/.test(ch)) { stream.eatWhile(anumRE); return rval(state,stream,"variable"); } // atom/keyword/BIF/function if (/[a-z_ß-öø-ÿ]/.test(ch)) { stream.eatWhile(anumRE); if (stream.match(/\s*\/\s*[0-9]/,false)) { stream.match(/\s*\/\s*[0-9]/,true); return rval(state,stream,"fun"); // f/0 style fun } var w = stream.current(); if (is_member(w,keywordWords)) { return rval(state,stream,"keyword"); }else if (is_member(w,operatorAtomWords)) { return rval(state,stream,"operator"); }else if (stream.match(/\s*\(/,false)) { // 'put' and 'erlang:put' are bifs, 'foo:put' is not if (is_member(w,bifWords) && ((peekToken(state).token != ":") || (peekToken(state,2).token == "erlang"))) { return rval(state,stream,"builtin"); }else if (is_member(w,guardWords)) { return rval(state,stream,"guard"); }else{ return rval(state,stream,"function"); } }else if (lookahead(stream) == ":") { if (w == "erlang") { return rval(state,stream,"builtin"); } else { return rval(state,stream,"function"); } }else if (is_member(w,["true","false"])) { return rval(state,stream,"boolean"); }else{ return rval(state,stream,"atom"); } } // number var digitRE = /[0-9]/; var radixRE = /[0-9a-zA-Z]/; // 36#zZ style int if (digitRE.test(ch)) { stream.eatWhile(digitRE); if (stream.eat('#')) { // 36#aZ style integer if (!stream.eatWhile(radixRE)) { stream.backUp(1); //"36#" - syntax error } } else if (stream.eat('.')) { // float if (!stream.eatWhile(digitRE)) { stream.backUp(1); // "3." - probably end of function } else { if (stream.eat(/[eE]/)) { // float with exponent if (stream.eat(/[-+]/)) { if (!stream.eatWhile(digitRE)) { stream.backUp(2); // "2e-" - syntax error } } else { if (!stream.eatWhile(digitRE)) { stream.backUp(1); // "2e" - syntax error } } } } } return rval(state,stream,"number"); // normal integer } // open parens if (nongreedy(stream,openParenRE,openParenWords)) { return rval(state,stream,"open_paren"); } // close parens if (nongreedy(stream,closeParenRE,closeParenWords)) { return rval(state,stream,"close_paren"); } // separators if (greedy(stream,separatorRE,separatorWords)) { return rval(state,stream,"separator"); } // operators if (greedy(stream,operatorSymbolRE,operatorSymbolWords)) { return rval(state,stream,"operator"); } return rval(state,stream,null); } ///////////////////////////////////////////////////////////////////////////// // utilities function nongreedy(stream,re,words) { if (stream.current().length == 1 && re.test(stream.current())) { stream.backUp(1); while (re.test(stream.peek())) { stream.next(); if (is_member(stream.current(),words)) { return true; } } stream.backUp(stream.current().length-1); } return false; } function greedy(stream,re,words) { if (stream.current().length == 1 && re.test(stream.current())) { while (re.test(stream.peek())) { stream.next(); } while (0 < stream.current().length) { if (is_member(stream.current(),words)) { return true; }else{ stream.backUp(1); } } stream.next(); } return false; } function doubleQuote(stream) { return quote(stream, '"', '\\'); } function singleQuote(stream) { return quote(stream,'\'','\\'); } function quote(stream,quoteChar,escapeChar) { while (!stream.eol()) { var ch = stream.next(); if (ch == quoteChar) { return true; }else if (ch == escapeChar) { stream.next(); } } return false; } function lookahead(stream) { var m = stream.match(/([\n\s]+|%[^\n]*\n)*(.)/,false); return m ? m.pop() : ""; } function is_member(element,list) { return (-1 < list.indexOf(element)); } function rval(state,stream,type) { // parse stack pushToken(state,realToken(type,stream)); // map erlang token type to CodeMirror style class // erlang -> CodeMirror tag switch (type) { case "atom": return "atom"; case "attribute": return "attribute"; case "boolean": return "atom"; case "builtin": return "builtin"; case "close_paren": return null; case "colon": return null; case "comment": return "comment"; case "dot": return null; case "error": return "error"; case "fun": return "meta"; case "function": return "tag"; case "guard": return "property"; case "keyword": return "keyword"; case "macro": return "variable-2"; case "number": return "number"; case "open_paren": return null; case "operator": return "operator"; case "record": return "bracket"; case "separator": return null; case "string": return "string"; case "type": return "def"; case "variable": return "variable"; default: return null; } } function aToken(tok,col,ind,typ) { return {token: tok, column: col, indent: ind, type: typ}; } function realToken(type,stream) { return aToken(stream.current(), stream.column(), stream.indentation(), type); } function fakeToken(type) { return aToken(type,0,0,type); } function peekToken(state,depth) { var len = state.tokenStack.length; var dep = (depth ? depth : 1); if (len < dep) { return false; }else{ return state.tokenStack[len-dep]; } } function pushToken(state,token) { if (!(token.type == "comment" || token.type == "whitespace")) { state.tokenStack = maybe_drop_pre(state.tokenStack,token); state.tokenStack = maybe_drop_post(state.tokenStack); } } function maybe_drop_pre(s,token) { var last = s.length-1; if (0 < last && s[last].type === "record" && token.type === "dot") { s.pop(); }else if (0 < last && s[last].type === "group") { s.pop(); s.push(token); }else{ s.push(token); } return s; } function maybe_drop_post(s) { if (!s.length) return s var last = s.length-1; if (s[last].type === "dot") { return []; } if (last > 1 && s[last].type === "fun" && s[last-1].token === "fun") { return s.slice(0,last-1); } switch (s[last].token) { case "}": return d(s,{g:["{"]}); case "]": return d(s,{i:["["]}); case ")": return d(s,{i:["("]}); case ">>": return d(s,{i:["<<"]}); case "end": return d(s,{i:["begin","case","fun","if","receive","try"]}); case ",": return d(s,{e:["begin","try","when","->", ",","(","[","{","<<"]}); case "->": return d(s,{r:["when"], m:["try","if","case","receive"]}); case ";": return d(s,{E:["case","fun","if","receive","try","when"]}); case "catch":return d(s,{e:["try"]}); case "of": return d(s,{e:["case"]}); case "after":return d(s,{e:["receive","try"]}); default: return s; } } function d(stack,tt) { // stack is a stack of Token objects. // tt is an object; {type:tokens} // type is a char, tokens is a list of token strings. // The function returns (possibly truncated) stack. // It will descend the stack, looking for a Token such that Token.token // is a member of tokens. If it does not find that, it will normally (but // see "E" below) return stack. If it does find a match, it will remove // all the Tokens between the top and the matched Token. // If type is "m", that is all it does. // If type is "i", it will also remove the matched Token and the top Token. // If type is "g", like "i", but add a fake "group" token at the top. // If type is "r", it will remove the matched Token, but not the top Token. // If type is "e", it will keep the matched Token but not the top Token. // If type is "E", it behaves as for type "e", except if there is no match, // in which case it will return an empty stack. for (var type in tt) { var len = stack.length-1; var tokens = tt[type]; for (var i = len-1; -1 < i ; i--) { if (is_member(stack[i].token,tokens)) { var ss = stack.slice(0,i); switch (type) { case "m": return ss.concat(stack[i]).concat(stack[len]); case "r": return ss.concat(stack[len]); case "i": return ss; case "g": return ss.concat(fakeToken("group")); case "E": return ss.concat(stack[i]); case "e": return ss.concat(stack[i]); } } } } return (type == "E" ? [] : stack); } ///////////////////////////////////////////////////////////////////////////// // indenter function indenter(state,textAfter) { var t; var unit = cmCfg.indentUnit; var wordAfter = wordafter(textAfter); var currT = peekToken(state,1); var prevT = peekToken(state,2); if (state.in_string || state.in_atom) { return CodeMirror.Pass; }else if (!prevT) { return 0; }else if (currT.token == "when") { return currT.column+unit; }else if (wordAfter === "when" && prevT.type === "function") { return prevT.indent+unit; }else if (wordAfter === "(" && currT.token === "fun") { return currT.column+3; }else if (wordAfter === "catch" && (t = getToken(state,["try"]))) { return t.column; }else if (is_member(wordAfter,["end","after","of"])) { t = getToken(state,["begin","case","fun","if","receive","try"]); return t ? t.column : CodeMirror.Pass; }else if (is_member(wordAfter,closeParenWords)) { t = getToken(state,openParenWords); return t ? t.column : CodeMirror.Pass; }else if (is_member(currT.token,[",","|","||"]) || is_member(wordAfter,[",","|","||"])) { t = postcommaToken(state); return t ? t.column+t.token.length : unit; }else if (currT.token == "->") { if (is_member(prevT.token, ["receive","case","if","try"])) { return prevT.column+unit+unit; }else{ return prevT.column+unit; } }else if (is_member(currT.token,openParenWords)) { return currT.column+currT.token.length; }else{ t = defaultToken(state); return truthy(t) ? t.column+unit : 0; } } function wordafter(str) { var m = str.match(/,|[a-z]+|\}|\]|\)|>>|\|+|\(/); return truthy(m) && (m.index === 0) ? m[0] : ""; } function postcommaToken(state) { var objs = state.tokenStack.slice(0,-1); var i = getTokenIndex(objs,"type",["open_paren"]); return truthy(objs[i]) ? objs[i] : false; } function defaultToken(state) { var objs = state.tokenStack; var stop = getTokenIndex(objs,"type",["open_paren","separator","keyword"]); var oper = getTokenIndex(objs,"type",["operator"]); if (truthy(stop) && truthy(oper) && stop < oper) { return objs[stop+1]; } else if (truthy(stop)) { return objs[stop]; } else { return false; } } function getToken(state,tokens) { var objs = state.tokenStack; var i = getTokenIndex(objs,"token",tokens); return truthy(objs[i]) ? objs[i] : false; } function getTokenIndex(objs,propname,propvals) { for (var i = objs.length-1; -1 < i ; i--) { if (is_member(objs[i][propname],propvals)) { return i; } } return false; } function truthy(x) { return (x !== false) && (x != null); } ///////////////////////////////////////////////////////////////////////////// // this object defines the mode return { startState: function() { return {tokenStack: [], in_string: false, in_atom: false}; }, token: function(stream, state) { return tokenizer(stream, state); }, indent: function(state, textAfter) { return indenter(state,textAfter); }, lineComment: "%" }; }); }); ================================================ FILE: third_party/CodeMirror/mode/erlang/index.html ================================================ CodeMirror: Erlang mode

Erlang mode

MIME types defined: text/x-erlang.

================================================ FILE: third_party/CodeMirror/mode/factor/factor.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Factor syntax highlight - simple mode // // by Dimage Sapelkin (https://github.com/kerabromsmu) (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/simple")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../addon/mode/simple"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineSimpleMode("factor", { // The start state contains the rules that are intially used start: [ // comments {regex: /#?!.*/, token: "comment"}, // strings """, multiline --> state {regex: /"""/, token: "string", next: "string3"}, {regex: /(STRING:)(\s)/, token: ["keyword", null], next: "string2"}, {regex: /\S*?"/, token: "string", next: "string"}, // numbers: dec, hex, unicode, bin, fractional, complex {regex: /(?:0x[\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\-?\d+.?\d*)(?=\s)/, token: "number"}, //{regex: /[+-]?/} //fractional // definition: defining word, defined word, etc {regex: /((?:GENERIC)|\:?\:)(\s+)(\S+)(\s+)(\()/, token: ["keyword", null, "def", null, "bracket"], next: "stack"}, // method definition: defining word, type, defined word, etc {regex: /(M\:)(\s+)(\S+)(\s+)(\S+)/, token: ["keyword", null, "def", null, "tag"]}, // vocabulary using --> state {regex: /USING\:/, token: "keyword", next: "vocabulary"}, // vocabulary definition/use {regex: /(USE\:|IN\:)(\s+)(\S+)(?=\s|$)/, token: ["keyword", null, "tag"]}, // definition: a defining word, defined word {regex: /(\S+\:)(\s+)(\S+)(?=\s|$)/, token: ["keyword", null, "def"]}, // "keywords", incl. ; t f . [ ] { } defining words {regex: /(?:;|\\|t|f|if|loop|while|until|do|PRIVATE>| and the like {regex: /\S+[\)>\.\*\?]+(?=\s|$)/, token: "builtin"}, {regex: /[\)><]+\S+(?=\s|$)/, token: "builtin"}, // operators {regex: /(?:[\+\-\=\/\*<>])(?=\s|$)/, token: "keyword"}, // any id (?) {regex: /\S+/, token: "variable"}, {regex: /\s+|./, token: null} ], vocabulary: [ {regex: /;/, token: "keyword", next: "start"}, {regex: /\S+/, token: "tag"}, {regex: /\s+|./, token: null} ], string: [ {regex: /(?:[^\\]|\\.)*?"/, token: "string", next: "start"}, {regex: /.*/, token: "string"} ], string2: [ {regex: /^;/, token: "keyword", next: "start"}, {regex: /.*/, token: "string"} ], string3: [ {regex: /(?:[^\\]|\\.)*?"""/, token: "string", next: "start"}, {regex: /.*/, token: "string"} ], stack: [ {regex: /\)/, token: "bracket", next: "start"}, {regex: /--/, token: "bracket"}, {regex: /\S+/, token: "meta"}, {regex: /\s+|./, token: null} ], // The meta property contains global information about the mode. It // can contain properties like lineComment, which are supported by // all modes, and also directives like dontIndentStates, which are // specific to simple modes. meta: { dontIndentStates: ["start", "vocabulary", "string", "string3", "stack"], lineComment: [ "!", "#!" ] } }); CodeMirror.defineMIME("text/x-factor", "factor"); }); ================================================ FILE: third_party/CodeMirror/mode/factor/index.html ================================================ CodeMirror: Factor mode

Factor mode

Simple mode that handles Factor Syntax (Factor on WikiPedia).

MIME types defined: text/x-factor.

================================================ FILE: third_party/CodeMirror/mode/fcl/fcl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("fcl", function(config) { var indentUnit = config.indentUnit; var keywords = { "term": true, "method": true, "accu": true, "rule": true, "then": true, "is": true, "and": true, "or": true, "if": true, "default": true }; var start_blocks = { "var_input": true, "var_output": true, "fuzzify": true, "defuzzify": true, "function_block": true, "ruleblock": true }; var end_blocks = { "end_ruleblock": true, "end_defuzzify": true, "end_function_block": true, "end_fuzzify": true, "end_var": true }; var atoms = { "true": true, "false": true, "nan": true, "real": true, "min": true, "max": true, "cog": true, "cogs": true }; var isOperatorChar = /[+\-*&^%:=<>!|\/]/; function tokenBase(stream, state) { var ch = stream.next(); if (/[\d\.]/.test(ch)) { if (ch == ".") { stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); } else if (ch == "0") { stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); } else { stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); } return "number"; } if (ch == "/" || ch == "(") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_\xa1-\uffff]/); var cur = stream.current().toLowerCase(); if (keywords.propertyIsEnumerable(cur) || start_blocks.propertyIsEnumerable(cur) || end_blocks.propertyIsEnumerable(cur)) { return "keyword"; } if (atoms.propertyIsEnumerable(cur)) return "atom"; return "variable"; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if ((ch == "/" || ch == ")") && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { return state.context = new Context(state.indented, col, type, null, state.context); } function popContext(state) { if (!state.context.prev) return; var t = state.context.type; if (t == "end_block") state.indented = state.context.indented; return state.context = state.context.prev; } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; var cur = stream.current().toLowerCase(); if (start_blocks.propertyIsEnumerable(cur)) pushContext(state, stream.column(), "end_block"); else if (end_blocks.propertyIsEnumerable(cur)) popContext(state); state.startOfLine = false; return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null) return 0; var ctx = state.context; var closing = end_blocks.propertyIsEnumerable(textAfter); if (ctx.align) return ctx.column + (closing ? 0 : 1); else return ctx.indented + (closing ? 0 : indentUnit); }, electricChars: "ryk", fold: "brace", blockCommentStart: "(*", blockCommentEnd: "*)", lineComment: "//" }; }); CodeMirror.defineMIME("text/x-fcl", "fcl"); }); ================================================ FILE: third_party/CodeMirror/mode/fcl/index.html ================================================ CodeMirror: FCL mode

FCL mode

MIME type: text/x-fcl

================================================ FILE: third_party/CodeMirror/mode/forth/forth.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Author: Aliaksei Chapyzhenka (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function toWordList(words) { var ret = []; words.split(' ').forEach(function(e){ ret.push({name: e}); }); return ret; } var coreWordList = toWordList( 'INVERT AND OR XOR\ 2* 2/ LSHIFT RSHIFT\ 0= = 0< < > U< MIN MAX\ 2DROP 2DUP 2OVER 2SWAP ?DUP DEPTH DROP DUP OVER ROT SWAP\ >R R> R@\ + - 1+ 1- ABS NEGATE\ S>D * M* UM*\ FM/MOD SM/REM UM/MOD */ */MOD / /MOD MOD\ HERE , @ ! CELL+ CELLS C, C@ C! CHARS 2@ 2!\ ALIGN ALIGNED +! ALLOT\ CHAR [CHAR] [ ] BL\ FIND EXECUTE IMMEDIATE COUNT LITERAL STATE\ ; DOES> >BODY\ EVALUATE\ SOURCE >IN\ <# # #S #> HOLD SIGN BASE >NUMBER HEX DECIMAL\ FILL MOVE\ . CR EMIT SPACE SPACES TYPE U. .R U.R\ ACCEPT\ TRUE FALSE\ <> U> 0<> 0>\ NIP TUCK ROLL PICK\ 2>R 2R@ 2R>\ WITHIN UNUSED MARKER\ I J\ TO\ COMPILE, [COMPILE]\ SAVE-INPUT RESTORE-INPUT\ PAD ERASE\ 2LITERAL DNEGATE\ D- D+ D0< D0= D2* D2/ D< D= DMAX DMIN D>S DABS\ M+ M*/ D. D.R 2ROT DU<\ CATCH THROW\ FREE RESIZE ALLOCATE\ CS-PICK CS-ROLL\ GET-CURRENT SET-CURRENT FORTH-WORDLIST GET-ORDER SET-ORDER\ PREVIOUS SEARCH-WORDLIST WORDLIST FIND ALSO ONLY FORTH DEFINITIONS ORDER\ -TRAILING /STRING SEARCH COMPARE CMOVE CMOVE> BLANK SLITERAL'); 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'); CodeMirror.defineMode('forth', function() { function searchWordList (wordList, word) { var i; for (i = wordList.length - 1; i >= 0; i--) { if (wordList[i].name === word.toUpperCase()) { return wordList[i]; } } return undefined; } return { startState: function() { return { state: '', base: 10, coreWordList: coreWordList, immediateWordList: immediateWordList, wordList: [] }; }, token: function (stream, stt) { var mat; if (stream.eatSpace()) { return null; } if (stt.state === '') { // interpretation if (stream.match(/^(\]|:NONAME)(\s|$)/i)) { stt.state = ' compilation'; return 'builtin compilation'; } mat = stream.match(/^(\:)\s+(\S+)(\s|$)+/); if (mat) { stt.wordList.push({name: mat[2].toUpperCase()}); stt.state = ' compilation'; return 'def' + stt.state; } mat = stream.match(/^(VARIABLE|2VARIABLE|CONSTANT|2CONSTANT|CREATE|POSTPONE|VALUE|WORD)\s+(\S+)(\s|$)+/i); if (mat) { stt.wordList.push({name: mat[2].toUpperCase()}); return 'def' + stt.state; } mat = stream.match(/^(\'|\[\'\])\s+(\S+)(\s|$)+/); if (mat) { return 'builtin' + stt.state; } } else { // compilation // ; [ if (stream.match(/^(\;|\[)(\s)/)) { stt.state = ''; stream.backUp(1); return 'builtin compilation'; } if (stream.match(/^(\;|\[)($)/)) { stt.state = ''; return 'builtin compilation'; } if (stream.match(/^(POSTPONE)\s+\S+(\s|$)+/)) { return 'builtin'; } } // dynamic wordlist mat = stream.match(/^(\S+)(\s+|$)/); if (mat) { if (searchWordList(stt.wordList, mat[1]) !== undefined) { return 'variable' + stt.state; } // comments if (mat[1] === '\\') { stream.skipToEnd(); return 'comment' + stt.state; } // core words if (searchWordList(stt.coreWordList, mat[1]) !== undefined) { return 'builtin' + stt.state; } if (searchWordList(stt.immediateWordList, mat[1]) !== undefined) { return 'keyword' + stt.state; } if (mat[1] === '(') { stream.eatWhile(function (s) { return s !== ')'; }); stream.eat(')'); return 'comment' + stt.state; } // // strings if (mat[1] === '.(') { stream.eatWhile(function (s) { return s !== ')'; }); stream.eat(')'); return 'string' + stt.state; } if (mat[1] === 'S"' || mat[1] === '."' || mat[1] === 'C"') { stream.eatWhile(function (s) { return s !== '"'; }); stream.eat('"'); return 'string' + stt.state; } // numbers if (mat[1] - 0xfffffffff) { return 'number' + stt.state; } // if (mat[1].match(/^[-+]?[0-9]+\.[0-9]*/)) { // return 'number' + stt.state; // } return 'atom' + stt.state; } } }; }); CodeMirror.defineMIME("text/x-forth", "forth"); }); ================================================ FILE: third_party/CodeMirror/mode/forth/index.html ================================================ CodeMirror: Forth mode

Forth mode

Simple mode that handle Forth-Syntax (Forth on WikiPedia).

MIME types defined: text/x-forth.

================================================ FILE: third_party/CodeMirror/mode/fortran/fortran.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("fortran", function() { function words(array) { var keys = {}; for (var i = 0; i < array.length; ++i) { keys[array[i]] = true; } return keys; } var keywords = words([ "abstract", "accept", "allocatable", "allocate", "array", "assign", "asynchronous", "backspace", "bind", "block", "byte", "call", "case", "class", "close", "common", "contains", "continue", "cycle", "data", "deallocate", "decode", "deferred", "dimension", "do", "elemental", "else", "encode", "end", "endif", "entry", "enumerator", "equivalence", "exit", "external", "extrinsic", "final", "forall", "format", "function", "generic", "go", "goto", "if", "implicit", "import", "include", "inquire", "intent", "interface", "intrinsic", "module", "namelist", "non_intrinsic", "non_overridable", "none", "nopass", "nullify", "open", "optional", "options", "parameter", "pass", "pause", "pointer", "print", "private", "program", "protected", "public", "pure", "read", "recursive", "result", "return", "rewind", "save", "select", "sequence", "stop", "subroutine", "target", "then", "to", "type", "use", "value", "volatile", "where", "while", "write"]); var builtins = words(["abort", "abs", "access", "achar", "acos", "adjustl", "adjustr", "aimag", "aint", "alarm", "all", "allocated", "alog", "amax", "amin", "amod", "and", "anint", "any", "asin", "associated", "atan", "besj", "besjn", "besy", "besyn", "bit_size", "btest", "cabs", "ccos", "ceiling", "cexp", "char", "chdir", "chmod", "clog", "cmplx", "command_argument_count", "complex", "conjg", "cos", "cosh", "count", "cpu_time", "cshift", "csin", "csqrt", "ctime", "c_funloc", "c_loc", "c_associated", "c_null_ptr", "c_null_funptr", "c_f_pointer", "c_null_char", "c_alert", "c_backspace", "c_form_feed", "c_new_line", "c_carriage_return", "c_horizontal_tab", "c_vertical_tab", "dabs", "dacos", "dasin", "datan", "date_and_time", "dbesj", "dbesj", "dbesjn", "dbesy", "dbesy", "dbesyn", "dble", "dcos", "dcosh", "ddim", "derf", "derfc", "dexp", "digits", "dim", "dint", "dlog", "dlog", "dmax", "dmin", "dmod", "dnint", "dot_product", "dprod", "dsign", "dsinh", "dsin", "dsqrt", "dtanh", "dtan", "dtime", "eoshift", "epsilon", "erf", "erfc", "etime", "exit", "exp", "exponent", "extends_type_of", "fdate", "fget", "fgetc", "float", "floor", "flush", "fnum", "fputc", "fput", "fraction", "fseek", "fstat", "ftell", "gerror", "getarg", "get_command", "get_command_argument", "get_environment_variable", "getcwd", "getenv", "getgid", "getlog", "getpid", "getuid", "gmtime", "hostnm", "huge", "iabs", "iachar", "iand", "iargc", "ibclr", "ibits", "ibset", "ichar", "idate", "idim", "idint", "idnint", "ieor", "ierrno", "ifix", "imag", "imagpart", "index", "int", "ior", "irand", "isatty", "ishft", "ishftc", "isign", "iso_c_binding", "is_iostat_end", "is_iostat_eor", "itime", "kill", "kind", "lbound", "len", "len_trim", "lge", "lgt", "link", "lle", "llt", "lnblnk", "loc", "log", "logical", "long", "lshift", "lstat", "ltime", "matmul", "max", "maxexponent", "maxloc", "maxval", "mclock", "merge", "move_alloc", "min", "minexponent", "minloc", "minval", "mod", "modulo", "mvbits", "nearest", "new_line", "nint", "not", "or", "pack", "perror", "precision", "present", "product", "radix", "rand", "random_number", "random_seed", "range", "real", "realpart", "rename", "repeat", "reshape", "rrspacing", "rshift", "same_type_as", "scale", "scan", "second", "selected_int_kind", "selected_real_kind", "set_exponent", "shape", "short", "sign", "signal", "sinh", "sin", "sleep", "sngl", "spacing", "spread", "sqrt", "srand", "stat", "sum", "symlnk", "system", "system_clock", "tan", "tanh", "time", "tiny", "transfer", "transpose", "trim", "ttynam", "ubound", "umask", "unlink", "unpack", "verify", "xor", "zabs", "zcos", "zexp", "zlog", "zsin", "zsqrt"]); var dataTypes = words(["c_bool", "c_char", "c_double", "c_double_complex", "c_float", "c_float_complex", "c_funptr", "c_int", "c_int16_t", "c_int32_t", "c_int64_t", "c_int8_t", "c_int_fast16_t", "c_int_fast32_t", "c_int_fast64_t", "c_int_fast8_t", "c_int_least16_t", "c_int_least32_t", "c_int_least64_t", "c_int_least8_t", "c_intmax_t", "c_intptr_t", "c_long", "c_long_double", "c_long_double_complex", "c_long_long", "c_ptr", "c_short", "c_signed_char", "c_size_t", "character", "complex", "double", "integer", "logical", "real"]); var isOperatorChar = /[+\-*&=<>\/\:]/; var litOperator = new RegExp("(\.and\.|\.or\.|\.eq\.|\.lt\.|\.le\.|\.gt\.|\.ge\.|\.ne\.|\.not\.|\.eqv\.|\.neqv\.)", "i"); function tokenBase(stream, state) { if (stream.match(litOperator)){ return 'operator'; } var ch = stream.next(); if (ch == "!") { stream.skipToEnd(); return "comment"; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[\[\]\(\),]/.test(ch)) { return null; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_]/); var word = stream.current().toLowerCase(); if (keywords.hasOwnProperty(word)){ return 'keyword'; } if (builtins.hasOwnProperty(word) || dataTypes.hasOwnProperty(word)) { return 'builtin'; } return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) { end = true; break; } escaped = !escaped && next == "\\"; } if (end || !escaped) state.tokenize = null; return "string"; }; } // Interface return { startState: function() { return {tokenize: null}; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; return style; } }; }); CodeMirror.defineMIME("text/x-fortran", "fortran"); }); ================================================ FILE: third_party/CodeMirror/mode/fortran/index.html ================================================ CodeMirror: Fortran mode

Fortran mode

MIME types defined: text/x-fortran.

================================================ FILE: third_party/CodeMirror/mode/gas/gas.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("gas", function(_config, parserConfig) { 'use strict'; // If an architecture is specified, its initialization function may // populate this array with custom parsing functions which will be // tried in the event that the standard functions do not find a match. var custom = []; // The symbol used to start a line comment changes based on the target // architecture. // If no architecture is pased in "parserConfig" then only multiline // comments will have syntax support. var lineCommentStartSymbol = ""; // These directives are architecture independent. // Machine specific directives should go in their respective // architecture initialization function. // Reference: // http://sourceware.org/binutils/docs/as/Pseudo-Ops.html#Pseudo-Ops var directives = { ".abort" : "builtin", ".align" : "builtin", ".altmacro" : "builtin", ".ascii" : "builtin", ".asciz" : "builtin", ".balign" : "builtin", ".balignw" : "builtin", ".balignl" : "builtin", ".bundle_align_mode" : "builtin", ".bundle_lock" : "builtin", ".bundle_unlock" : "builtin", ".byte" : "builtin", ".cfi_startproc" : "builtin", ".comm" : "builtin", ".data" : "builtin", ".def" : "builtin", ".desc" : "builtin", ".dim" : "builtin", ".double" : "builtin", ".eject" : "builtin", ".else" : "builtin", ".elseif" : "builtin", ".end" : "builtin", ".endef" : "builtin", ".endfunc" : "builtin", ".endif" : "builtin", ".equ" : "builtin", ".equiv" : "builtin", ".eqv" : "builtin", ".err" : "builtin", ".error" : "builtin", ".exitm" : "builtin", ".extern" : "builtin", ".fail" : "builtin", ".file" : "builtin", ".fill" : "builtin", ".float" : "builtin", ".func" : "builtin", ".global" : "builtin", ".gnu_attribute" : "builtin", ".hidden" : "builtin", ".hword" : "builtin", ".ident" : "builtin", ".if" : "builtin", ".incbin" : "builtin", ".include" : "builtin", ".int" : "builtin", ".internal" : "builtin", ".irp" : "builtin", ".irpc" : "builtin", ".lcomm" : "builtin", ".lflags" : "builtin", ".line" : "builtin", ".linkonce" : "builtin", ".list" : "builtin", ".ln" : "builtin", ".loc" : "builtin", ".loc_mark_labels" : "builtin", ".local" : "builtin", ".long" : "builtin", ".macro" : "builtin", ".mri" : "builtin", ".noaltmacro" : "builtin", ".nolist" : "builtin", ".octa" : "builtin", ".offset" : "builtin", ".org" : "builtin", ".p2align" : "builtin", ".popsection" : "builtin", ".previous" : "builtin", ".print" : "builtin", ".protected" : "builtin", ".psize" : "builtin", ".purgem" : "builtin", ".pushsection" : "builtin", ".quad" : "builtin", ".reloc" : "builtin", ".rept" : "builtin", ".sbttl" : "builtin", ".scl" : "builtin", ".section" : "builtin", ".set" : "builtin", ".short" : "builtin", ".single" : "builtin", ".size" : "builtin", ".skip" : "builtin", ".sleb128" : "builtin", ".space" : "builtin", ".stab" : "builtin", ".string" : "builtin", ".struct" : "builtin", ".subsection" : "builtin", ".symver" : "builtin", ".tag" : "builtin", ".text" : "builtin", ".title" : "builtin", ".type" : "builtin", ".uleb128" : "builtin", ".val" : "builtin", ".version" : "builtin", ".vtable_entry" : "builtin", ".vtable_inherit" : "builtin", ".warning" : "builtin", ".weak" : "builtin", ".weakref" : "builtin", ".word" : "builtin" }; var registers = {}; function x86(_parserConfig) { lineCommentStartSymbol = "#"; registers.ax = "variable"; registers.eax = "variable-2"; registers.rax = "variable-3"; registers.bx = "variable"; registers.ebx = "variable-2"; registers.rbx = "variable-3"; registers.cx = "variable"; registers.ecx = "variable-2"; registers.rcx = "variable-3"; registers.dx = "variable"; registers.edx = "variable-2"; registers.rdx = "variable-3"; registers.si = "variable"; registers.esi = "variable-2"; registers.rsi = "variable-3"; registers.di = "variable"; registers.edi = "variable-2"; registers.rdi = "variable-3"; registers.sp = "variable"; registers.esp = "variable-2"; registers.rsp = "variable-3"; registers.bp = "variable"; registers.ebp = "variable-2"; registers.rbp = "variable-3"; registers.ip = "variable"; registers.eip = "variable-2"; registers.rip = "variable-3"; registers.cs = "keyword"; registers.ds = "keyword"; registers.ss = "keyword"; registers.es = "keyword"; registers.fs = "keyword"; registers.gs = "keyword"; } function armv6(_parserConfig) { // Reference: // http://infocenter.arm.com/help/topic/com.arm.doc.qrc0001l/QRC0001_UAL.pdf // http://infocenter.arm.com/help/topic/com.arm.doc.ddi0301h/DDI0301H_arm1176jzfs_r0p7_trm.pdf lineCommentStartSymbol = "@"; directives.syntax = "builtin"; registers.r0 = "variable"; registers.r1 = "variable"; registers.r2 = "variable"; registers.r3 = "variable"; registers.r4 = "variable"; registers.r5 = "variable"; registers.r6 = "variable"; registers.r7 = "variable"; registers.r8 = "variable"; registers.r9 = "variable"; registers.r10 = "variable"; registers.r11 = "variable"; registers.r12 = "variable"; registers.sp = "variable-2"; registers.lr = "variable-2"; registers.pc = "variable-2"; registers.r13 = registers.sp; registers.r14 = registers.lr; registers.r15 = registers.pc; custom.push(function(ch, stream) { if (ch === '#') { stream.eatWhile(/\w/); return "number"; } }); } var arch = (parserConfig.architecture || "x86").toLowerCase(); if (arch === "x86") { x86(parserConfig); } else if (arch === "arm" || arch === "armv6") { armv6(parserConfig); } function nextUntilUnescaped(stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next === end && !escaped) { return false; } escaped = !escaped && next === "\\"; } return escaped; } function clikeComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (ch === "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch === "*"); } return "comment"; } return { startState: function() { return { tokenize: null }; }, token: function(stream, state) { if (state.tokenize) { return state.tokenize(stream, state); } if (stream.eatSpace()) { return null; } var style, cur, ch = stream.next(); if (ch === "/") { if (stream.eat("*")) { state.tokenize = clikeComment; return clikeComment(stream, state); } } if (ch === lineCommentStartSymbol) { stream.skipToEnd(); return "comment"; } if (ch === '"') { nextUntilUnescaped(stream, '"'); return "string"; } if (ch === '.') { stream.eatWhile(/\w/); cur = stream.current().toLowerCase(); style = directives[cur]; return style || null; } if (ch === '=') { stream.eatWhile(/\w/); return "tag"; } if (ch === '{') { return "braket"; } if (ch === '}') { return "braket"; } if (/\d/.test(ch)) { if (ch === "0" && stream.eat("x")) { stream.eatWhile(/[0-9a-fA-F]/); return "number"; } stream.eatWhile(/\d/); return "number"; } if (/\w/.test(ch)) { stream.eatWhile(/\w/); if (stream.eat(":")) { return 'tag'; } cur = stream.current().toLowerCase(); style = registers[cur]; return style || null; } for (var i = 0; i < custom.length; i++) { style = custom[i](ch, stream, state); if (style) { return style; } } }, lineComment: lineCommentStartSymbol, blockCommentStart: "/*", blockCommentEnd: "*/" }; }); }); ================================================ FILE: third_party/CodeMirror/mode/gas/index.html ================================================ CodeMirror: Gas mode

Gas mode

Handles AT&T assembler syntax (more specifically this handles the GNU Assembler (gas) syntax.) It takes a single optional configuration parameter: architecture, which can be one of "ARM", "ARMv6" or "x86". Including the parameter adds syntax for the registers and special directives for the supplied architecture.

MIME types defined: text/x-gas

================================================ FILE: third_party/CodeMirror/mode/gfm/gfm.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../markdown/markdown"), require("../../addon/mode/overlay")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../markdown/markdown", "../../addon/mode/overlay"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var 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 CodeMirror.defineMode("gfm", function(config, modeConfig) { var codeDepth = 0; function blankLine(state) { state.code = false; return null; } var gfmOverlay = { startState: function() { return { code: false, codeBlock: false, ateSpace: false }; }, copyState: function(s) { return { code: s.code, codeBlock: s.codeBlock, ateSpace: s.ateSpace }; }, token: function(stream, state) { state.combineTokens = null; // Hack to prevent formatting override inside code blocks (block and inline) if (state.codeBlock) { if (stream.match(/^```+/)) { state.codeBlock = false; return null; } stream.skipToEnd(); return null; } if (stream.sol()) { state.code = false; } if (stream.sol() && stream.match(/^```+/)) { stream.skipToEnd(); state.codeBlock = true; return null; } // If this block is changed, it may need to be updated in Markdown mode if (stream.peek() === '`') { stream.next(); var before = stream.pos; stream.eatWhile('`'); var difference = 1 + stream.pos - before; if (!state.code) { codeDepth = difference; state.code = true; } else { if (difference === codeDepth) { // Must be exact state.code = false; } } return null; } else if (state.code) { stream.next(); return null; } // Check if space. If so, links can be formatted later on if (stream.eatSpace()) { state.ateSpace = true; return null; } if (stream.sol() || state.ateSpace) { state.ateSpace = false; if (modeConfig.gitHubSpice !== false) { if(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?=.{0,6}\d)(?:[a-f0-9]{7,40}\b)/)) { // User/Project@SHA // User@SHA // SHA state.combineTokens = true; return "link"; } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) { // User/Project#Num // User#Num // #Num state.combineTokens = true; return "link"; } } } if (stream.match(urlRE) && stream.string.slice(stream.start - 2, stream.start) != "](" && (stream.start == 0 || /\W/.test(stream.string.charAt(stream.start - 1)))) { // URLs // Taken from http://daringfireball.net/2010/07/improved_regex_for_matching_urls // And then (issue #1160) simplified to make it not crash the Chrome Regexp engine // And then limited url schemes to the CommonMark list, so foo:bar isn't matched as a URL state.combineTokens = true; return "link"; } stream.next(); return null; }, blankLine: blankLine }; var markdownConfig = { taskLists: true, strikethrough: true, emoji: true }; for (var attr in modeConfig) { markdownConfig[attr] = modeConfig[attr]; } markdownConfig.name = "markdown"; return CodeMirror.overlayMode(CodeMirror.getMode(config, markdownConfig), gfmOverlay); }, "markdown"); CodeMirror.defineMIME("text/x-gfm", "gfm"); }); ================================================ FILE: third_party/CodeMirror/mode/gfm/index.html ================================================ CodeMirror: GFM mode

GFM mode

Optionally depends on other modes for properly highlighted code blocks.

Gfm mode supports these options (apart those from base Markdown mode):

  • gitHubSpice: boolean
    Hashes, issues... (default: true).
  • taskLists: boolean
    - [ ] syntax (default: true).
  • strikethrough: boolean
    ~~foo~~ syntax (default: true).
  • emoji: boolean
    :emoji: syntax (default: true).

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/gfm/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var config = {tabSize: 4, indentUnit: 2} var mode = CodeMirror.getMode(config, "gfm"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } var modeHighlightFormatting = CodeMirror.getMode(config, {name: "gfm", highlightFormatting: true}); function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); } FT("codeBackticks", "[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]"); FT("doubleBackticks", "[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]"); FT("taskList", "[variable-2&formatting&formatting-list&formatting-list-ul - ][meta&formatting&formatting-task [ ]]][variable-2 foo]", "[variable-2&formatting&formatting-list&formatting-list-ul - ][property&formatting&formatting-task [x]]][variable-2 foo]"); FT("formatting_strikethrough", "[strikethrough&formatting&formatting-strikethrough ~~][strikethrough foo][strikethrough&formatting&formatting-strikethrough ~~]"); FT("formatting_strikethrough", "foo [strikethrough&formatting&formatting-strikethrough ~~][strikethrough bar][strikethrough&formatting&formatting-strikethrough ~~]"); FT("formatting_emoji", "foo [builtin&formatting&formatting-emoji :smile:] foo"); MT("emInWordAsterisk", "foo[em *bar*]hello"); MT("emInWordUnderscore", "foo_bar_hello"); MT("emStrongUnderscore", "[em&strong ___foo___] bar"); MT("taskListAsterisk", "[variable-2 * ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] "[variable-2 * ][link&variable-2 [[ ]]][variable-2 bar]", // Invalid; must have space after ] "[variable-2 * ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ] "[variable-2 * ][meta [ ]]][variable-2 ][link&variable-2 [[world]]]", // Valid; tests reference style links " [variable-3 * ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("taskListPlus", "[variable-2 + ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] "[variable-2 + ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ] "[variable-2 + ][meta [ ]]][variable-2 ][link&variable-2 [[world]]]", // Valid; tests reference style links " [variable-3 + ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("taskListDash", "[variable-2 - ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] "[variable-2 - ][link&variable-2 [[x]]][variable-2 hello]", // Invalid; must have space after ] "[variable-2 - ][meta [ ]]][variable-2 world]", // Valid; tests reference style links " [variable-3 - ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("taskListNumber", "[variable-2 1. ][link&variable-2 [[]]][variable-2 foo]", // Invalid; must have space or x between [] "[variable-2 2. ][link&variable-2 [[ ]]][variable-2 bar]", // Invalid; must have space after ] "[variable-2 3. ][meta [ ]]][variable-2 world]", // Valid; tests reference style links " [variable-3 1. ][property [x]]][variable-3 foo]"); // Valid; can be nested MT("SHA", "foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar"); MT("SHAEmphasis", "[em *foo ][em&link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]"); MT("shortSHA", "foo [link be6a8cc] bar"); MT("tooShortSHA", "foo be6a8c bar"); MT("longSHA", "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd22 bar"); MT("badSHA", "foo be6a8cc1c1ecfe9489fb51e4869af15a13fc2cg2 bar"); MT("userSHA", "foo [link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] hello"); MT("userSHAEmphasis", "[em *foo ][em&link bar@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]"); MT("userProjectSHA", "foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world"); MT("userProjectSHAEmphasis", "[em *foo ][em&link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2][em *]"); MT("wordSHA", "ask for feedbac") MT("num", "foo [link #1] bar"); MT("numEmphasis", "[em *foo ][em&link #1][em *]"); MT("badNum", "foo #1bar hello"); MT("userNum", "foo [link bar#1] hello"); MT("userNumEmphasis", "[em *foo ][em&link bar#1][em *]"); MT("userProjectNum", "foo [link bar/hello#1] world"); MT("userProjectNumEmphasis", "[em *foo ][em&link bar/hello#1][em *]"); MT("vanillaLink", "foo [link http://www.example.com/] bar"); MT("vanillaLinkNoScheme", "foo [link www.example.com] bar"); MT("vanillaLinkHttps", "foo [link https://www.example.com/] bar"); MT("vanillaLinkDataSchema", "foo [link data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==] bar"); MT("vanillaLinkPunctuation", "foo [link http://www.example.com/]. bar"); MT("vanillaLinkExtension", "foo [link http://www.example.com/index.html] bar"); MT("vanillaLinkEmphasis", "foo [em *][em&link http://www.example.com/index.html][em *] bar"); MT("notALink", "foo asfd:asdf bar"); MT("notALink", "[comment ``foo `bar` http://www.example.com/``] hello"); MT("notALink", "[comment `foo]", "[comment&link http://www.example.com/]", "[comment `] foo", "", "[link http://www.example.com/]"); MT("strikethrough", "[strikethrough ~~foo~~]"); MT("strikethroughWithStartingSpace", "~~ foo~~"); MT("strikethroughUnclosedStrayTildes", "[strikethrough ~~foo~~~]"); MT("strikethroughUnclosedStrayTildes", "[strikethrough ~~foo ~~]"); MT("strikethroughUnclosedStrayTildes", "[strikethrough ~~foo ~~ bar]"); MT("strikethroughUnclosedStrayTildes", "[strikethrough ~~foo ~~ bar~~]hello"); MT("strikethroughOneLetter", "[strikethrough ~~a~~]"); MT("strikethroughWrapped", "[strikethrough ~~foo]", "[strikethrough foo~~]"); MT("strikethroughParagraph", "[strikethrough ~~foo]", "", "foo[strikethrough ~~bar]"); MT("strikethroughEm", "[strikethrough ~~foo][em&strikethrough *bar*][strikethrough ~~]"); MT("strikethroughEm", "[em *][em&strikethrough ~~foo~~][em *]"); MT("strikethroughStrong", "[strikethrough ~~][strong&strikethrough **foo**][strikethrough ~~]"); MT("strikethroughStrong", "[strong **][strong&strikethrough ~~foo~~][strong **]"); MT("emoji", "text [builtin :blush:] text [builtin :v:] text [builtin :+1:] text", ":text text: [builtin :smiley_cat:]"); })(); ================================================ FILE: third_party/CodeMirror/mode/gherkin/gherkin.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /* Gherkin mode - http://www.cukes.info/ Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues */ // Following Objs from Brackets implementation: https://github.com/tregusti/brackets-gherkin/blob/master/main.js //var Quotes = { // SINGLE: 1, // DOUBLE: 2 //}; //var regex = { // keywords: /(Feature| {2}(Scenario|In order to|As|I)| {4}(Given|When|Then|And))/ //}; (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("gherkin", function () { return { startState: function () { return { lineNumber: 0, tableHeaderLine: false, allowFeature: true, allowBackground: false, allowScenario: false, allowSteps: false, allowPlaceholders: false, allowMultilineArgument: false, inMultilineString: false, inMultilineTable: false, inKeywordLine: false }; }, token: function (stream, state) { if (stream.sol()) { state.lineNumber++; state.inKeywordLine = false; if (state.inMultilineTable) { state.tableHeaderLine = false; if (!stream.match(/\s*\|/, false)) { state.allowMultilineArgument = false; state.inMultilineTable = false; } } } stream.eatSpace(); if (state.allowMultilineArgument) { // STRING if (state.inMultilineString) { if (stream.match('"""')) { state.inMultilineString = false; state.allowMultilineArgument = false; } else { stream.match(/.*/); } return "string"; } // TABLE if (state.inMultilineTable) { if (stream.match(/\|\s*/)) { return "bracket"; } else { stream.match(/[^\|]*/); return state.tableHeaderLine ? "header" : "string"; } } // DETECT START if (stream.match('"""')) { // String state.inMultilineString = true; return "string"; } else if (stream.match("|")) { // Table state.inMultilineTable = true; state.tableHeaderLine = true; return "bracket"; } } // LINE COMMENT if (stream.match(/#.*/)) { return "comment"; // TAG } else if (!state.inKeywordLine && stream.match(/@\S+/)) { return "tag"; // FEATURE } 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):/)) { state.allowScenario = true; state.allowBackground = true; state.allowPlaceholders = false; state.allowSteps = false; state.allowMultilineArgument = false; state.inKeywordLine = true; return "keyword"; // BACKGROUND } 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):/)) { state.allowPlaceholders = false; state.allowSteps = true; state.allowBackground = false; state.allowMultilineArgument = false; state.inKeywordLine = true; return "keyword"; // SCENARIO OUTLINE } 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):/)) { state.allowPlaceholders = true; state.allowSteps = true; state.allowMultilineArgument = false; state.inKeywordLine = true; return "keyword"; // EXAMPLES } 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):/)) { state.allowPlaceholders = false; state.allowSteps = true; state.allowBackground = false; state.allowMultilineArgument = true; return "keyword"; // SCENARIO } 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):/)) { state.allowPlaceholders = false; state.allowSteps = true; state.allowBackground = false; state.allowMultilineArgument = false; state.inKeywordLine = true; return "keyword"; // STEPS } 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 |\* )/)) { state.inStep = true; state.allowPlaceholders = true; state.allowMultilineArgument = true; state.inKeywordLine = true; return "keyword"; // INLINE STRING } else if (stream.match(/"[^"]*"?/)) { return "string"; // PLACEHOLDER } else if (state.allowPlaceholders && stream.match(/<[^>]*>?/)) { return "variable"; // Fall through } else { stream.next(); stream.eatWhile(/[^@"<#]/); return null; } } }; }); CodeMirror.defineMIME("text/x-feature", "gherkin"); }); ================================================ FILE: third_party/CodeMirror/mode/gherkin/index.html ================================================ CodeMirror: Gherkin mode

Gherkin mode

MIME types defined: text/x-feature.

================================================ FILE: third_party/CodeMirror/mode/go/go.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("go", function(config) { var indentUnit = config.indentUnit; var keywords = { "break":true, "case":true, "chan":true, "const":true, "continue":true, "default":true, "defer":true, "else":true, "fallthrough":true, "for":true, "func":true, "go":true, "goto":true, "if":true, "import":true, "interface":true, "map":true, "package":true, "range":true, "return":true, "select":true, "struct":true, "switch":true, "type":true, "var":true, "bool":true, "byte":true, "complex64":true, "complex128":true, "float32":true, "float64":true, "int8":true, "int16":true, "int32":true, "int64":true, "string":true, "uint8":true, "uint16":true, "uint32":true, "uint64":true, "int":true, "uint":true, "uintptr":true, "error": true, "rune":true }; var atoms = { "true":true, "false":true, "iota":true, "nil":true, "append":true, "cap":true, "close":true, "complex":true, "copy":true, "delete":true, "imag":true, "len":true, "make":true, "new":true, "panic":true, "print":true, "println":true, "real":true, "recover":true }; var isOperatorChar = /[+\-*&^%:=<>!|\/]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'" || ch == "`") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[\d\.]/.test(ch)) { if (ch == ".") { stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); } else if (ch == "0") { stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); } else { stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); } return "number"; } if (/[\[\]{}\(\),;\:\.]/.test(ch)) { curPunc = ch; return null; } if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_\xa1-\uffff]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) { if (cur == "case" || cur == "default") curPunc = "case"; return "keyword"; } if (atoms.propertyIsEnumerable(cur)) return "atom"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && quote != "`" && next == "\\"; } if (end || !(escaped || quote == "`")) state.tokenize = tokenBase; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { return state.context = new Context(state.indented, col, type, null, state.context); } function popContext(state) { if (!state.context.prev) return; var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } // Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; if (ctx.type == "case") ctx.type = "}"; } if (stream.eatSpace()) return null; curPunc = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "case") ctx.type = "case"; else if (curPunc == "}" && ctx.type == "}") popContext(state); else if (curPunc == ctx.type) popContext(state); state.startOfLine = false; return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass; var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); if (ctx.type == "case" && /^(?:case|default)\b/.test(textAfter)) { state.context.type = "}"; return ctx.indented; } var closing = firstChar == ctx.type; if (ctx.align) return ctx.column + (closing ? 0 : 1); else return ctx.indented + (closing ? 0 : indentUnit); }, electricChars: "{}):", closeBrackets: "()[]{}''\"\"``", fold: "brace", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); CodeMirror.defineMIME("text/x-go", "go"); }); ================================================ FILE: third_party/CodeMirror/mode/go/index.html ================================================ CodeMirror: Go mode

Go mode

MIME type: text/x-go

================================================ FILE: third_party/CodeMirror/mode/groovy/groovy.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("groovy", function(config) { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = words( "abstract as assert boolean break byte case catch char class const continue def default " + "do double else enum extends final finally float for goto if implements import in " + "instanceof int interface long native new package private protected public return " + "short static strictfp super switch synchronized threadsafe throw throws trait transient " + "try void volatile while"); var blockKeywords = words("catch class def do else enum finally for if interface switch trait try while"); var standaloneKeywords = words("return break continue"); var atoms = words("null true false this"); var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { return startString(ch, stream, state); } if (/[\[\]{}\(\),;\:\.]/.test(ch)) { curPunc = ch; return null; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); if (stream.eat(/eE/)) { stream.eat(/\+\-/); stream.eatWhile(/\d/); } return "number"; } if (ch == "/") { if (stream.eat("*")) { state.tokenize.push(tokenComment); return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } if (expectExpression(state.lastToken, false)) { return startString(ch, stream, state); } } if (ch == "-" && stream.eat(">")) { curPunc = "->"; return null; } if (/[+\-*&%=<>!?|\/~]/.test(ch)) { stream.eatWhile(/[+\-*&%=<>|~]/); return "operator"; } stream.eatWhile(/[\w\$_]/); if (ch == "@") { stream.eatWhile(/[\w\$_\.]/); return "meta"; } if (state.lastToken == ".") return "property"; if (stream.eat(":")) { curPunc = "proplabel"; return "property"; } var cur = stream.current(); if (atoms.propertyIsEnumerable(cur)) { return "atom"; } if (keywords.propertyIsEnumerable(cur)) { if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; else if (standaloneKeywords.propertyIsEnumerable(cur)) curPunc = "standalone"; return "keyword"; } return "variable"; } tokenBase.isBase = true; function startString(quote, stream, state) { var tripleQuoted = false; if (quote != "/" && stream.eat(quote)) { if (stream.eat(quote)) tripleQuoted = true; else return "string"; } function t(stream, state) { var escaped = false, next, end = !tripleQuoted; while ((next = stream.next()) != null) { if (next == quote && !escaped) { if (!tripleQuoted) { break; } if (stream.match(quote + quote)) { end = true; break; } } if (quote == '"' && next == "$" && !escaped && stream.eat("{")) { state.tokenize.push(tokenBaseUntilBrace()); return "string"; } escaped = !escaped && next == "\\"; } if (end) state.tokenize.pop(); return "string"; } state.tokenize.push(t); return t(stream, state); } function tokenBaseUntilBrace() { var depth = 1; function t(stream, state) { if (stream.peek() == "}") { depth--; if (depth == 0) { state.tokenize.pop(); return state.tokenize[state.tokenize.length-1](stream, state); } } else if (stream.peek() == "{") { depth++; } return tokenBase(stream, state); } t.isBase = true; return t; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize.pop(); break; } maybeEnd = (ch == "*"); } return "comment"; } function expectExpression(last, newline) { return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) || last == "newstatement" || last == "keyword" || last == "proplabel" || (last == "standalone" && !newline); } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { return state.context = new Context(state.indented, col, type, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } // Interface return { startState: function(basecolumn) { return { tokenize: [tokenBase], context: new Context((basecolumn || 0) - config.indentUnit, 0, "top", false), indented: 0, startOfLine: true, lastToken: null }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; // Automatic semicolon insertion if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) { popContext(state); ctx = state.context; } } if (stream.eatSpace()) return null; curPunc = null; var style = state.tokenize[state.tokenize.length-1](stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); // Handle indentation for {x -> \n ... } else if (curPunc == "->" && ctx.type == "statement" && ctx.prev.type == "}") { popContext(state); state.context.align = false; } else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) pushContext(state, stream.column(), "statement"); state.startOfLine = false; state.lastToken = curPunc || style; return style; }, indent: function(state, textAfter) { if (!state.tokenize[state.tokenize.length-1].isBase) return CodeMirror.Pass; var firstChar = textAfter && textAfter.charAt(0), ctx = state.context; if (ctx.type == "statement" && !expectExpression(state.lastToken, true)) ctx = ctx.prev; var closing = firstChar == ctx.type; if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : config.indentUnit); else if (ctx.align) return ctx.column + (closing ? 0 : 1); else return ctx.indented + (closing ? 0 : config.indentUnit); }, electricChars: "{}", closeBrackets: {triples: "'\""}, fold: "brace" }; }); CodeMirror.defineMIME("text/x-groovy", "groovy"); }); ================================================ FILE: third_party/CodeMirror/mode/groovy/index.html ================================================ CodeMirror: Groovy mode

Groovy mode

MIME types defined: text/x-groovy

================================================ FILE: third_party/CodeMirror/mode/haml/haml.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../ruby/ruby")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../ruby/ruby"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; // full haml mode. This handled embedded ruby and html fragments too CodeMirror.defineMode("haml", function(config) { var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"}); var rubyMode = CodeMirror.getMode(config, "ruby"); function rubyInQuote(endQuote) { return function(stream, state) { var ch = stream.peek(); if (ch == endQuote && state.rubyState.tokenize.length == 1) { // step out of ruby context as it seems to complete processing all the braces stream.next(); state.tokenize = html; return "closeAttributeTag"; } else { return ruby(stream, state); } }; } function ruby(stream, state) { if (stream.match("-#")) { stream.skipToEnd(); return "comment"; } return rubyMode.token(stream, state.rubyState); } function html(stream, state) { var ch = stream.peek(); // handle haml declarations. All declarations that cant be handled here // will be passed to html mode if (state.previousToken.style == "comment" ) { if (state.indented > state.previousToken.indented) { stream.skipToEnd(); return "commentLine"; } } if (state.startOfLine) { if (ch == "!" && stream.match("!!")) { stream.skipToEnd(); return "tag"; } else if (stream.match(/^%[\w:#\.]+=/)) { state.tokenize = ruby; return "hamlTag"; } else if (stream.match(/^%[\w:]+/)) { return "hamlTag"; } else if (ch == "/" ) { stream.skipToEnd(); return "comment"; } } if (state.startOfLine || state.previousToken.style == "hamlTag") { if ( ch == "#" || ch == ".") { stream.match(/[\w-#\.]*/); return "hamlAttribute"; } } // donot handle --> as valid ruby, make it HTML close comment instead if (state.startOfLine && !stream.match("-->", false) && (ch == "=" || ch == "-" )) { state.tokenize = ruby; return state.tokenize(stream, state); } if (state.previousToken.style == "hamlTag" || state.previousToken.style == "closeAttributeTag" || state.previousToken.style == "hamlAttribute") { if (ch == "(") { state.tokenize = rubyInQuote(")"); return state.tokenize(stream, state); } else if (ch == "{") { if (!stream.match(/^\{%.*/)) { state.tokenize = rubyInQuote("}"); return state.tokenize(stream, state); } } } return htmlMode.token(stream, state.htmlState); } return { // default to html mode startState: function() { var htmlState = CodeMirror.startState(htmlMode); var rubyState = CodeMirror.startState(rubyMode); return { htmlState: htmlState, rubyState: rubyState, indented: 0, previousToken: { style: null, indented: 0}, tokenize: html }; }, copyState: function(state) { return { htmlState : CodeMirror.copyState(htmlMode, state.htmlState), rubyState: CodeMirror.copyState(rubyMode, state.rubyState), indented: state.indented, previousToken: state.previousToken, tokenize: state.tokenize }; }, token: function(stream, state) { if (stream.sol()) { state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); state.startOfLine = false; // dont record comment line as we only want to measure comment line with // the opening comment block if (style && style != "commentLine") { state.previousToken = { style: style, indented: state.indented }; } // if current state is ruby and the previous token is not `,` reset the // tokenize to html if (stream.eol() && state.tokenize == ruby) { stream.backUp(1); var ch = stream.peek(); stream.next(); if (ch && ch != ",") { state.tokenize = html; } } // reprocess some of the specific style tag when finish setting previousToken if (style == "hamlTag") { style = "tag"; } else if (style == "commentLine") { style = "comment"; } else if (style == "hamlAttribute") { style = "attribute"; } else if (style == "closeAttributeTag") { style = null; } return style; } }; }, "htmlmixed", "ruby"); CodeMirror.defineMIME("text/x-haml", "haml"); }); ================================================ FILE: third_party/CodeMirror/mode/haml/index.html ================================================ CodeMirror: HAML mode

HAML mode

MIME types defined: text/x-haml.

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/haml/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "haml"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Requires at least one media query MT("elementName", "[tag %h1] Hey There"); MT("oneElementPerLine", "[tag %h1] Hey There %h2"); MT("idSelector", "[tag %h1][attribute #test] Hey There"); MT("classSelector", "[tag %h1][attribute .hello] Hey There"); MT("docType", "[tag !!! XML]"); MT("comment", "[comment / Hello WORLD]"); MT("notComment", "[tag %h1] This is not a / comment "); MT("attributes", "[tag %a]([variable title][operator =][string \"test\"]){[atom :title] [operator =>] [string \"test\"]}"); MT("htmlCode", "[tag&bracket <][tag h1][tag&bracket >]Title[tag&bracket ]"); MT("rubyBlock", "[operator =][variable-2 @item]"); MT("selectorRubyBlock", "[tag %a.selector=] [variable-2 @item]"); MT("nestedRubyBlock", "[tag %a]", " [operator =][variable puts] [string \"test\"]"); MT("multilinePlaintext", "[tag %p]", " Hello,", " World"); MT("multilineRuby", "[tag %p]", " [comment -# this is a comment]", " [comment and this is a comment too]", " Date/Time", " [operator -] [variable now] [operator =] [tag DateTime][operator .][property now]", " [tag %strong=] [variable now]", " [operator -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][property parse]([string \"December 31, 2006\"])", " [operator =][string \"Happy\"]", " [operator =][string \"Belated\"]", " [operator =][string \"Birthday\"]"); MT("multilineComment", "[comment /]", " [comment Multiline]", " [comment Comment]"); MT("hamlComment", "[comment -# this is a comment]"); MT("multilineHamlComment", "[comment -# this is a comment]", " [comment and this is a comment too]"); MT("multilineHTMLComment", "[comment ]"); MT("hamlAfterRubyTag", "[attribute .block]", " [tag %strong=] [variable now]", " [attribute .test]", " [operator =][variable now]", " [attribute .right]"); MT("stretchedRuby", "[operator =] [variable puts] [string \"Hello\"],", " [string \"World\"]"); MT("interpolationInHashAttribute", //"[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test"); "[tag %div]{[atom :id] [operator =>] [string \"#{][variable test][string }_#{][variable ting][string }\"]} test"); MT("interpolationInHTMLAttribute", "[tag %div]([variable title][operator =][string \"#{][variable test][string }_#{][variable ting]()[string }\"]) Test"); })(); ================================================ FILE: third_party/CodeMirror/mode/handlebars/handlebars.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/simple"), require("../../addon/mode/multiplex")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../addon/mode/simple", "../../addon/mode/multiplex"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineSimpleMode("handlebars-tags", { start: [ { regex: /\{\{!--/, push: "dash_comment", token: "comment" }, { regex: /\{\{!/, push: "comment", token: "comment" }, { regex: /\{\{/, push: "handlebars", token: "tag" } ], handlebars: [ { regex: /\}\}/, pop: true, token: "tag" }, // Double and single quotes { regex: /"(?:[^\\"]|\\.)*"?/, token: "string" }, { regex: /'(?:[^\\']|\\.)*'?/, token: "string" }, // Handlebars keywords { regex: />|[#\/]([A-Za-z_]\w*)/, token: "keyword" }, { regex: /(?:else|this)\b/, token: "keyword" }, // Numeral { regex: /\d+/i, token: "number" }, // Atoms like = and . { regex: /=|~|@|true|false/, token: "atom" }, // Paths { regex: /(?:\.\.\/)*(?:[A-Za-z_][\w\.]*)+/, token: "variable-2" } ], dash_comment: [ { regex: /--\}\}/, pop: true, token: "comment" }, // Commented code { regex: /./, token: "comment"} ], comment: [ { regex: /\}\}/, pop: true, token: "comment" }, { regex: /./, token: "comment" } ], meta: { blockCommentStart: "{{--", blockCommentEnd: "--}}" } }); CodeMirror.defineMode("handlebars", function(config, parserConfig) { var handlebars = CodeMirror.getMode(config, "handlebars-tags"); if (!parserConfig || !parserConfig.base) return handlebars; return CodeMirror.multiplexingMode( CodeMirror.getMode(config, parserConfig.base), {open: "{{", close: "}}", mode: handlebars, parseDelimiters: true} ); }); CodeMirror.defineMIME("text/x-handlebars-template", "handlebars"); }); ================================================ FILE: third_party/CodeMirror/mode/handlebars/index.html ================================================ CodeMirror: Handlebars mode

Handlebars

Handlebars syntax highlighting for CodeMirror.

MIME types defined: text/x-handlebars-template

Supported options: base to set the mode to wrap. For example, use

mode: {name: "handlebars", base: "text/html"}

to highlight an HTML template.

================================================ FILE: third_party/CodeMirror/mode/haskell/haskell.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("haskell", function(_config, modeConfig) { function switchState(source, setState, f) { setState(f); return f(source, setState); } // These should all be Unicode extended, as per the Haskell 2010 report var smallRE = /[a-z_]/; var largeRE = /[A-Z]/; var digitRE = /\d/; var hexitRE = /[0-9A-Fa-f]/; var octitRE = /[0-7]/; var idRE = /[a-z_A-Z0-9'\xa1-\uffff]/; var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:]/; var specialRE = /[(),;[\]`{}]/; var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer function normal(source, setState) { if (source.eatWhile(whiteCharRE)) { return null; } var ch = source.next(); if (specialRE.test(ch)) { if (ch == '{' && source.eat('-')) { var t = "comment"; if (source.eat('#')) { t = "meta"; } return switchState(source, setState, ncomment(t, 1)); } return null; } if (ch == '\'') { if (source.eat('\\')) { source.next(); // should handle other escapes here } else { source.next(); } if (source.eat('\'')) { return "string"; } return "string error"; } if (ch == '"') { return switchState(source, setState, stringLiteral); } if (largeRE.test(ch)) { source.eatWhile(idRE); if (source.eat('.')) { return "qualifier"; } return "variable-2"; } if (smallRE.test(ch)) { source.eatWhile(idRE); return "variable"; } if (digitRE.test(ch)) { if (ch == '0') { if (source.eat(/[xX]/)) { source.eatWhile(hexitRE); // should require at least 1 return "integer"; } if (source.eat(/[oO]/)) { source.eatWhile(octitRE); // should require at least 1 return "number"; } } source.eatWhile(digitRE); var t = "number"; if (source.match(/^\.\d+/)) { t = "number"; } if (source.eat(/[eE]/)) { t = "number"; source.eat(/[-+]/); source.eatWhile(digitRE); // should require at least 1 } return t; } if (ch == "." && source.eat(".")) return "keyword"; if (symbolRE.test(ch)) { if (ch == '-' && source.eat(/-/)) { source.eatWhile(/-/); if (!source.eat(symbolRE)) { source.skipToEnd(); return "comment"; } } var t = "variable"; if (ch == ':') { t = "variable-2"; } source.eatWhile(symbolRE); return t; } return "error"; } function ncomment(type, nest) { if (nest == 0) { return normal; } return function(source, setState) { var currNest = nest; while (!source.eol()) { var ch = source.next(); if (ch == '{' && source.eat('-')) { ++currNest; } else if (ch == '-' && source.eat('}')) { --currNest; if (currNest == 0) { setState(normal); return type; } } } setState(ncomment(type, currNest)); return type; }; } function stringLiteral(source, setState) { while (!source.eol()) { var ch = source.next(); if (ch == '"') { setState(normal); return "string"; } if (ch == '\\') { if (source.eol() || source.eat(whiteCharRE)) { setState(stringGap); return "string"; } if (source.eat('&')) { } else { source.next(); // should handle other escapes here } } } setState(normal); return "string error"; } function stringGap(source, setState) { if (source.eat('\\')) { return switchState(source, setState, stringLiteral); } source.next(); setState(normal); return "error"; } var wellKnownWords = (function() { var wkw = {}; function setType(t) { return function () { for (var i = 0; i < arguments.length; i++) wkw[arguments[i]] = t; }; } setType("keyword")( "case", "class", "data", "default", "deriving", "do", "else", "foreign", "if", "import", "in", "infix", "infixl", "infixr", "instance", "let", "module", "newtype", "of", "then", "type", "where", "_"); setType("keyword")( "\.\.", ":", "::", "=", "\\", "<-", "->", "@", "~", "=>"); setType("builtin")( "!!", "$!", "$", "&&", "+", "++", "-", ".", "/", "/=", "<", "<*", "<=", "<$>", "<*>", "=<<", "==", ">", ">=", ">>", ">>=", "^", "^^", "||", "*", "*>", "**"); setType("builtin")( "Applicative", "Bool", "Bounded", "Char", "Double", "EQ", "Either", "Enum", "Eq", "False", "FilePath", "Float", "Floating", "Fractional", "Functor", "GT", "IO", "IOError", "Int", "Integer", "Integral", "Just", "LT", "Left", "Maybe", "Monad", "Nothing", "Num", "Ord", "Ordering", "Rational", "Read", "ReadS", "Real", "RealFloat", "RealFrac", "Right", "Show", "ShowS", "String", "True"); setType("builtin")( "abs", "acos", "acosh", "all", "and", "any", "appendFile", "asTypeOf", "asin", "asinh", "atan", "atan2", "atanh", "break", "catch", "ceiling", "compare", "concat", "concatMap", "const", "cos", "cosh", "curry", "cycle", "decodeFloat", "div", "divMod", "drop", "dropWhile", "either", "elem", "encodeFloat", "enumFrom", "enumFromThen", "enumFromThenTo", "enumFromTo", "error", "even", "exp", "exponent", "fail", "filter", "flip", "floatDigits", "floatRadix", "floatRange", "floor", "fmap", "foldl", "foldl1", "foldr", "foldr1", "fromEnum", "fromInteger", "fromIntegral", "fromRational", "fst", "gcd", "getChar", "getContents", "getLine", "head", "id", "init", "interact", "ioError", "isDenormalized", "isIEEE", "isInfinite", "isNaN", "isNegativeZero", "iterate", "last", "lcm", "length", "lex", "lines", "log", "logBase", "lookup", "map", "mapM", "mapM_", "max", "maxBound", "maximum", "maybe", "min", "minBound", "minimum", "mod", "negate", "not", "notElem", "null", "odd", "or", "otherwise", "pi", "pred", "print", "product", "properFraction", "pure", "putChar", "putStr", "putStrLn", "quot", "quotRem", "read", "readFile", "readIO", "readList", "readLn", "readParen", "reads", "readsPrec", "realToFrac", "recip", "rem", "repeat", "replicate", "return", "reverse", "round", "scaleFloat", "scanl", "scanl1", "scanr", "scanr1", "seq", "sequence", "sequence_", "show", "showChar", "showList", "showParen", "showString", "shows", "showsPrec", "significand", "signum", "sin", "sinh", "snd", "span", "splitAt", "sqrt", "subtract", "succ", "sum", "tail", "take", "takeWhile", "tan", "tanh", "toEnum", "toInteger", "toRational", "truncate", "uncurry", "undefined", "unlines", "until", "unwords", "unzip", "unzip3", "userError", "words", "writeFile", "zip", "zip3", "zipWith", "zipWith3"); var override = modeConfig.overrideKeywords; if (override) for (var word in override) if (override.hasOwnProperty(word)) wkw[word] = override[word]; return wkw; })(); return { startState: function () { return { f: normal }; }, copyState: function (s) { return { f: s.f }; }, token: function(stream, state) { var t = state.f(stream, function(s) { state.f = s; }); var w = stream.current(); return wellKnownWords.hasOwnProperty(w) ? wellKnownWords[w] : t; }, blockCommentStart: "{-", blockCommentEnd: "-}", lineComment: "--" }; }); CodeMirror.defineMIME("text/x-haskell", "haskell"); }); ================================================ FILE: third_party/CodeMirror/mode/haskell/index.html ================================================ CodeMirror: Haskell mode

Haskell mode

MIME types defined: text/x-haskell.

================================================ FILE: third_party/CodeMirror/mode/haskell-literate/haskell-literate.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function (mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../haskell/haskell")) else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../haskell/haskell"], mod) else // Plain browser env mod(CodeMirror) })(function (CodeMirror) { "use strict" CodeMirror.defineMode("haskell-literate", function (config, parserConfig) { var baseMode = CodeMirror.getMode(config, (parserConfig && parserConfig.base) || "haskell") return { startState: function () { return { inCode: false, baseState: CodeMirror.startState(baseMode) } }, token: function (stream, state) { if (stream.sol()) { if (state.inCode = stream.eat(">")) return "meta" } if (state.inCode) { return baseMode.token(stream, state.baseState) } else { stream.skipToEnd() return "comment" } }, innerMode: function (state) { return state.inCode ? {state: state.baseState, mode: baseMode} : null } } }, "haskell") CodeMirror.defineMIME("text/x-literate-haskell", "haskell-literate") }); ================================================ FILE: third_party/CodeMirror/mode/haskell-literate/index.html ================================================ CodeMirror: Haskell-literate mode

Haskell literate mode

MIME types defined: text/x-literate-haskell.

Parser configuration parameters recognized: base to set the base mode (defaults to "haskell").

================================================ FILE: third_party/CodeMirror/mode/haxe/haxe.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("haxe", function(config, parserConfig) { var indentUnit = config.indentUnit; // Tokenizer function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"}; var type = kw("typedef"); var keywords = { "if": A, "while": A, "else": B, "do": B, "try": B, "return": C, "break": C, "continue": C, "new": C, "throw": C, "var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"), "public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"), "function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "never": kw("property_access"), "trace":kw("trace"), "class": type, "abstract":type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type, "true": atom, "false": atom, "null": atom }; var isOperatorChar = /[+\-*&%=<>!?|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function toUnescaped(stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next == end && !escaped) return true; escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function haxeTokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { return chain(stream, state, haxeTokenString(ch)); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); } else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) { stream.match(/^\d*(?:\.\d*(?!\.))?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); } else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) { toUnescaped(stream, "/"); stream.eatWhile(/[gimsu]/); return ret("regexp", "string-2"); } else if (ch == "/") { if (stream.eat("*")) { return chain(stream, state, haxeTokenComment); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else { stream.eatWhile(isOperatorChar); return ret("operator", null, stream.current()); } } else if (ch == "#") { stream.skipToEnd(); return ret("conditional", "meta"); } else if (ch == "@") { stream.eat(/:/); stream.eatWhile(/[\w_]/); return ret ("metadata", "meta"); } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return ret("operator", null, stream.current()); } else { var word; if(/[A-Z]/.test(ch)) { stream.eatWhile(/[\w_<>]/); word = stream.current(); return ret("type", "variable-3", word); } else { stream.eatWhile(/[\w_]/); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return (known && state.kwAllowed) ? ret(known.type, known.style, word) : ret("variable", "variable", word); } } } function haxeTokenString(quote) { return function(stream, state) { if (toUnescaped(stream, quote)) state.tokenize = haxeTokenBase; return ret("string", "string"); }; } function haxeTokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = haxeTokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true}; function HaxeLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; } function parseHaxe(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; if (type == "variable" && imported(state, content)) return "variable-3"; return style; } } } function imported(state, typename) { if (/[a-z]/.test(typename.charAt(0))) return false; var len = state.importedtypes.length; for (var i = 0; i= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function inList(name, list) { for (var v = list; v; v = v.next) if (v.name == name) return true; return false; } function register(varname) { var state = cx.state; if (state.context) { cx.marked = "def"; if (inList(varname, state.localVars)) return; state.localVars = {name: varname, next: state.localVars}; } else if (state.globalVars) { if (inList(varname, state.globalVars)) return; state.globalVars = {name: varname, next: state.globalVars}; } } // Combinators var defaultVars = {name: "this", next: null}; function pushcontext() { if (!cx.state.context) cx.state.localVars = defaultVars; cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; } function popcontext() { cx.state.localVars = cx.state.context.vars; cx.state.context = cx.state.context.prev; } popcontext.lex = true; function pushlex(type, info) { var result = function() { var state = cx.state; state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { function f(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); else return cont(f); } return f; } function statement(type) { if (type == "@") return cont(metadef); if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext); if (type == ";") return cont(); if (type == "attribute") return cont(maybeattribute); if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"), poplex, statement, poplex); if (type == "variable") return cont(pushlex("stat"), maybelabel); if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); if (type == "import") return cont(importdef, expect(";")); if (type == "typedef") return cont(typedef); return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator); if (type == "type" ) return cont(maybeoperator); if (type == "function") return cont(functiondef); if (type == "keyword c") return cont(maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator); if (type == "operator") return cont(expression); if (type == "[") return cont(pushlex("]"), commasep(maybeexpression, "]"), poplex, maybeoperator); if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeoperator(type, value) { if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator); if (type == "operator" || type == ":") return cont(expression); if (type == ";") return; if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator); if (type == ".") return cont(property, maybeoperator); if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator); } function maybeattribute(type) { if (type == "attribute") return cont(maybeattribute); if (type == "function") return cont(functiondef); if (type == "var") return cont(vardef1); } function metadef(type) { if(type == ":") return cont(metadef); if(type == "variable") return cont(metadef); if(type == "(") return cont(pushlex(")"), commasep(metaargs, ")"), poplex, statement); } function metaargs(type) { if(type == "variable") return cont(); } function importdef (type, value) { if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); } else if(type == "variable" || type == "property" || type == "." || value == "*") return cont(importdef); } function typedef (type, value) { if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); } else if (type == "type" && /[A-Z]/.test(value.charAt(0))) { return cont(); } } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperator, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type) { if (type == "variable") cx.marked = "property"; if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression); } function commasep(what, end) { function proceed(type) { if (type == ",") return cont(what, proceed); if (type == end) return cont(); return cont(expect(end)); } return function(type) { if (type == end) return cont(); else return pass(what, proceed); }; } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function vardef1(type, value) { if (type == "variable"){register(value); return cont(typeuse, vardef2);} return cont(); } function vardef2(type, value) { if (value == "=") return cont(expression, vardef2); if (type == ",") return cont(vardef1); } function forspec1(type, value) { if (type == "variable") { register(value); return cont(forin, expression) } else { return pass() } } function forin(_type, value) { if (value == "in") return cont(); } function functiondef(type, value) { //function names starting with upper-case letters are recognised as types, so cludging them together here. if (type == "variable" || type == "type") {register(value); return cont(functiondef);} if (value == "new") return cont(functiondef); if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext); } function typeuse(type) { if(type == ":") return cont(typestring); } function typestring(type) { if(type == "type") return cont(); if(type == "variable") return cont(); if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex); } function typeprop(type) { if(type == "variable") return cont(typeuse); } function funarg(type, value) { if (type == "variable") {register(value); return cont(typeuse);} } // Interface return { startState: function(basecolumn) { var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"]; var state = { tokenize: haxeTokenBase, reAllowed: true, kwAllowed: true, cc: [], lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, importedtypes: defaulttypes, context: parserConfig.localVars && {vars: parserConfig.localVars}, indented: 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/)); state.kwAllowed = type != '.'; return parseHaxe(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize != haxeTokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + 4; else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "stat" || type == "form") return lexical.indented + indentUnit; else if (lexical.info == "switch" && !closing) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricChars: "{}", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); CodeMirror.defineMIME("text/x-haxe", "haxe"); CodeMirror.defineMode("hxml", function () { return { startState: function () { return { define: false, inString: false }; }, token: function (stream, state) { var ch = stream.peek(); var sol = stream.sol(); ///* comments */ if (ch == "#") { stream.skipToEnd(); return "comment"; } if (sol && ch == "-") { var style = "variable-2"; stream.eat(/-/); if (stream.peek() == "-") { stream.eat(/-/); style = "keyword a"; } if (stream.peek() == "D") { stream.eat(/[D]/); style = "keyword c"; state.define = true; } stream.eatWhile(/[A-Z]/i); return style; } var ch = stream.peek(); if (state.inString == false && ch == "'") { state.inString = true; stream.next(); } if (state.inString == true) { if (stream.skipTo("'")) { } else { stream.skipToEnd(); } if (stream.peek() == "'") { stream.next(); state.inString = false; } return "string"; } stream.next(); return null; }, lineComment: "#" }; }); CodeMirror.defineMIME("text/x-hxml", "hxml"); }); ================================================ FILE: third_party/CodeMirror/mode/haxe/index.html ================================================ CodeMirror: Haxe mode

Haxe mode

Hxml mode:

MIME types defined: text/x-haxe, text/x-hxml.

================================================ FILE: third_party/CodeMirror/mode/htmlembedded/htmlembedded.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../../addon/mode/multiplex")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../../addon/mode/multiplex"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("htmlembedded", function(config, parserConfig) { var closeComment = parserConfig.closeComment || "--%>" return CodeMirror.multiplexingMode(CodeMirror.getMode(config, "htmlmixed"), { open: parserConfig.openComment || "<%--", close: closeComment, delimStyle: "comment", mode: {token: function(stream) { stream.skipTo(closeComment) || stream.skipToEnd() return "comment" }} }, { open: parserConfig.open || parserConfig.scriptStartRegex || "<%", close: parserConfig.close || parserConfig.scriptEndRegex || "%>", mode: CodeMirror.getMode(config, parserConfig.scriptingModeSpec) }); }, "htmlmixed"); CodeMirror.defineMIME("application/x-ejs", {name: "htmlembedded", scriptingModeSpec:"javascript"}); CodeMirror.defineMIME("application/x-aspx", {name: "htmlembedded", scriptingModeSpec:"text/x-csharp"}); CodeMirror.defineMIME("application/x-jsp", {name: "htmlembedded", scriptingModeSpec:"text/x-java"}); CodeMirror.defineMIME("application/x-erb", {name: "htmlembedded", scriptingModeSpec:"ruby"}); }); ================================================ FILE: third_party/CodeMirror/mode/htmlembedded/index.html ================================================ CodeMirror: Html Embedded Scripts mode

Html Embedded Scripts mode

Mode for html embedded scripts like JSP and ASP.NET. Depends on multiplex and HtmlMixed which in turn depends on JavaScript, CSS and XML.
Other dependencies include those of the scripting language chosen.

MIME types defined: application/x-aspx (ASP.NET), application/x-ejs (Embedded Javascript), application/x-jsp (JavaServer Pages) and application/x-erb

================================================ FILE: third_party/CodeMirror/mode/htmlmixed/htmlmixed.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript"), require("../css/css")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var defaultTags = { script: [ ["lang", /(javascript|babel)/i, "javascript"], ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"], ["type", /./, "text/plain"], [null, null, "javascript"] ], style: [ ["lang", /^css$/i, "css"], ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"], ["type", /./, "text/plain"], [null, null, "css"] ] }; function maybeBackup(stream, pat, style) { var cur = stream.current(), close = cur.search(pat); if (close > -1) { stream.backUp(cur.length - close); } else if (cur.match(/<\/?$/)) { stream.backUp(cur.length); if (!stream.match(pat, false)) stream.match(cur); } return style; } var attrRegexpCache = {}; function getAttrRegexp(attr) { var regexp = attrRegexpCache[attr]; if (regexp) return regexp; return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"); } function getAttrValue(text, attr) { var match = text.match(getAttrRegexp(attr)) return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : "" } function getTagRegexp(tagName, anchored) { return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i"); } function addTags(from, to) { for (var tag in from) { var dest = to[tag] || (to[tag] = []); var source = from[tag]; for (var i = source.length - 1; i >= 0; i--) dest.unshift(source[i]) } } function findMatchingMode(tagInfo, tagText) { for (var i = 0; i < tagInfo.length; i++) { var spec = tagInfo[i]; if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2]; } } CodeMirror.defineMode("htmlmixed", function (config, parserConfig) { var htmlMode = CodeMirror.getMode(config, { name: "xml", htmlMode: true, multilineTagIndentFactor: parserConfig.multilineTagIndentFactor, multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag }); var tags = {}; var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes; addTags(defaultTags, tags); if (configTags) addTags(configTags, tags); if (configScript) for (var i = configScript.length - 1; i >= 0; i--) tags.script.unshift(["type", configScript[i].matches, configScript[i].mode]) function html(stream, state) { var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName if (tag && !/[<>\s\/]/.test(stream.current()) && (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) && tags.hasOwnProperty(tagName)) { state.inTag = tagName + " " } else if (state.inTag && tag && />$/.test(stream.current())) { var inTag = /^([\S]+) (.*)/.exec(state.inTag) state.inTag = null var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2]) var mode = CodeMirror.getMode(config, modeSpec) var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false); state.token = function (stream, state) { if (stream.match(endTagA, false)) { state.token = html; state.localState = state.localMode = null; return null; } return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState)); }; state.localMode = mode; state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", "")); } else if (state.inTag) { state.inTag += stream.current() if (stream.eol()) state.inTag += " " } return style; }; return { startState: function () { var state = CodeMirror.startState(htmlMode); return {token: html, inTag: null, localMode: null, localState: null, htmlState: state}; }, copyState: function (state) { var local; if (state.localState) { local = CodeMirror.copyState(state.localMode, state.localState); } return {token: state.token, inTag: state.inTag, localMode: state.localMode, localState: local, htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; }, token: function (stream, state) { return state.token(stream, state); }, indent: function (state, textAfter, line) { if (!state.localMode || /^\s*<\//.test(textAfter)) return htmlMode.indent(state.htmlState, textAfter, line); else if (state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line); else return CodeMirror.Pass; }, innerMode: function (state) { return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; } }; }, "xml", "javascript", "css"); CodeMirror.defineMIME("text/html", "htmlmixed"); }); ================================================ FILE: third_party/CodeMirror/mode/htmlmixed/index.html ================================================ CodeMirror: HTML mixed mode

HTML mixed mode

The HTML mixed mode depends on the XML, JavaScript, and CSS modes.

It takes an optional mode configuration option, tags, which can be used to add custom behavior for specific tags. When given, it should be an object mapping tag names (for example script) to arrays or three-element arrays. Those inner arrays indicate [attributeName, valueRegexp, modeSpec] specifications. For example, you could use ["type", /^foo$/, "foo"] to map the attribute type="foo" to the foo mode. When the first two fields are null ([null, null, "mode"]), the given mode is used for any such tag that doesn't match any of the previously given attributes. For example:

var myModeSpec = {
  name: "htmlmixed",
  tags: {
    style: [["type", /^text\/(x-)?scss$/, "text/x-scss"],
            [null, null, "css"]],
    custom: [[null, null, "customMode"]]
  }
}

MIME types defined: text/html (redefined, only takes effect if you load this parser after the XML parser).

================================================ FILE: third_party/CodeMirror/mode/http/http.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("http", function() { function failFirstLine(stream, state) { stream.skipToEnd(); state.cur = header; return "error"; } function start(stream, state) { if (stream.match(/^HTTP\/\d\.\d/)) { state.cur = responseStatusCode; return "keyword"; } else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) { state.cur = requestPath; return "keyword"; } else { return failFirstLine(stream, state); } } function responseStatusCode(stream, state) { var code = stream.match(/^\d+/); if (!code) return failFirstLine(stream, state); state.cur = responseStatusText; var status = Number(code[0]); if (status >= 100 && status < 200) { return "positive informational"; } else if (status >= 200 && status < 300) { return "positive success"; } else if (status >= 300 && status < 400) { return "positive redirect"; } else if (status >= 400 && status < 500) { return "negative client-error"; } else if (status >= 500 && status < 600) { return "negative server-error"; } else { return "error"; } } function responseStatusText(stream, state) { stream.skipToEnd(); state.cur = header; return null; } function requestPath(stream, state) { stream.eatWhile(/\S/); state.cur = requestProtocol; return "string-2"; } function requestProtocol(stream, state) { if (stream.match(/^HTTP\/\d\.\d$/)) { state.cur = header; return "keyword"; } else { return failFirstLine(stream, state); } } function header(stream) { if (stream.sol() && !stream.eat(/[ \t]/)) { if (stream.match(/^.*?:/)) { return "atom"; } else { stream.skipToEnd(); return "error"; } } else { stream.skipToEnd(); return "string"; } } function body(stream) { stream.skipToEnd(); return null; } return { token: function(stream, state) { var cur = state.cur; if (cur != header && cur != body && stream.eatSpace()) return null; return cur(stream, state); }, blankLine: function(state) { state.cur = body; }, startState: function() { return {cur: start}; } }; }); CodeMirror.defineMIME("message/http", "http"); }); ================================================ FILE: third_party/CodeMirror/mode/http/index.html ================================================ CodeMirror: HTTP mode

HTTP mode

MIME types defined: message/http.

================================================ FILE: third_party/CodeMirror/mode/idl/idl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function wordRegexp(words) { return new RegExp('^((' + words.join(')|(') + '))\\b', 'i'); }; var builtinArray = [ 'a_correlate', 'abs', 'acos', 'adapt_hist_equal', 'alog', 'alog2', 'alog10', 'amoeba', 'annotate', 'app_user_dir', 'app_user_dir_query', 'arg_present', 'array_equal', 'array_indices', 'arrow', 'ascii_template', 'asin', 'assoc', 'atan', 'axis', 'axis', 'bandpass_filter', 'bandreject_filter', 'barplot', 'bar_plot', 'beseli', 'beselj', 'beselk', 'besely', 'beta', 'biginteger', 'bilinear', 'bin_date', 'binary_template', 'bindgen', 'binomial', 'bit_ffs', 'bit_population', 'blas_axpy', 'blk_con', 'boolarr', 'boolean', 'boxplot', 'box_cursor', 'breakpoint', 'broyden', 'bubbleplot', 'butterworth', 'bytarr', 'byte', 'byteorder', 'bytscl', 'c_correlate', 'calendar', 'caldat', 'call_external', 'call_function', 'call_method', 'call_procedure', 'canny', 'catch', 'cd', 'cdf', 'ceil', 'chebyshev', 'check_math', 'chisqr_cvf', 'chisqr_pdf', 'choldc', 'cholsol', 'cindgen', 'cir_3pnt', 'clipboard', 'close', 'clust_wts', 'cluster', 'cluster_tree', 'cmyk_convert', 'code_coverage', 'color_convert', 'color_exchange', 'color_quan', 'color_range_map', 'colorbar', 'colorize_sample', 'colormap_applicable', 'colormap_gradient', 'colormap_rotation', 'colortable', 'comfit', 'command_line_args', 'common', 'compile_opt', 'complex', 'complexarr', 'complexround', 'compute_mesh_normals', 'cond', 'congrid', 'conj', 'constrained_min', 'contour', 'contour', 'convert_coord', 'convol', 'convol_fft', 'coord2to3', 'copy_lun', 'correlate', 'cos', 'cosh', 'cpu', 'cramer', 'createboxplotdata', 'create_cursor', 'create_struct', 'create_view', 'crossp', 'crvlength', 'ct_luminance', 'cti_test', 'cursor', 'curvefit', 'cv_coord', 'cvttobm', 'cw_animate', 'cw_animate_getp', 'cw_animate_load', 'cw_animate_run', 'cw_arcball', 'cw_bgroup', 'cw_clr_index', 'cw_colorsel', 'cw_defroi', 'cw_field', 'cw_filesel', 'cw_form', 'cw_fslider', 'cw_light_editor', 'cw_light_editor_get', 'cw_light_editor_set', 'cw_orient', 'cw_palette_editor', 'cw_palette_editor_get', 'cw_palette_editor_set', 'cw_pdmenu', 'cw_rgbslider', 'cw_tmpl', 'cw_zoom', 'db_exists', 'dblarr', 'dcindgen', 'dcomplex', 'dcomplexarr', 'define_key', 'define_msgblk', 'define_msgblk_from_file', 'defroi', 'defsysv', 'delvar', 'dendro_plot', 'dendrogram', 'deriv', 'derivsig', 'determ', 'device', 'dfpmin', 'diag_matrix', 'dialog_dbconnect', 'dialog_message', 'dialog_pickfile', 'dialog_printersetup', 'dialog_printjob', 'dialog_read_image', 'dialog_write_image', 'dictionary', 'digital_filter', 'dilate', 'dindgen', 'dissolve', 'dist', 'distance_measure', 'dlm_load', 'dlm_register', 'doc_library', 'double', 'draw_roi', 'edge_dog', 'efont', 'eigenql', 'eigenvec', 'ellipse', 'elmhes', 'emboss', 'empty', 'enable_sysrtn', 'eof', 'eos', 'erase', 'erf', 'erfc', 'erfcx', 'erode', 'errorplot', 'errplot', 'estimator_filter', 'execute', 'exit', 'exp', 'expand', 'expand_path', 'expint', 'extrac', 'extract_slice', 'f_cvf', 'f_pdf', 'factorial', 'fft', 'file_basename', 'file_chmod', 'file_copy', 'file_delete', 'file_dirname', 'file_expand_path', 'file_gunzip', 'file_gzip', 'file_info', 'file_lines', 'file_link', 'file_mkdir', 'file_move', 'file_poll_input', 'file_readlink', 'file_same', 'file_search', 'file_tar', 'file_test', 'file_untar', 'file_unzip', 'file_which', 'file_zip', 'filepath', 'findgen', 'finite', 'fix', 'flick', 'float', 'floor', 'flow3', 'fltarr', 'flush', 'format_axis_values', 'forward_function', 'free_lun', 'fstat', 'fulstr', 'funct', 'function', 'fv_test', 'fx_root', 'fz_roots', 'gamma', 'gamma_ct', 'gauss_cvf', 'gauss_pdf', 'gauss_smooth', 'gauss2dfit', 'gaussfit', 'gaussian_function', 'gaussint', 'get_drive_list', 'get_dxf_objects', 'get_kbrd', 'get_login_info', 'get_lun', 'get_screen_size', 'getenv', 'getwindows', 'greg2jul', 'grib', 'grid_input', 'grid_tps', 'grid3', 'griddata', 'gs_iter', 'h_eq_ct', 'h_eq_int', 'hanning', 'hash', 'hdf', 'hdf5', 'heap_free', 'heap_gc', 'heap_nosave', 'heap_refcount', 'heap_save', 'help', 'hilbert', 'hist_2d', 'hist_equal', 'histogram', 'hls', 'hough', 'hqr', 'hsv', 'i18n_multibytetoutf8', 'i18n_multibytetowidechar', 'i18n_utf8tomultibyte', 'i18n_widechartomultibyte', 'ibeta', 'icontour', 'iconvertcoord', 'idelete', 'identity', 'idl_base64', 'idl_container', 'idl_validname', 'idlexbr_assistant', 'idlitsys_createtool', 'idlunit', 'iellipse', 'igamma', 'igetcurrent', 'igetdata', 'igetid', 'igetproperty', 'iimage', 'image', 'image_cont', 'image_statistics', 'image_threshold', 'imaginary', 'imap', 'indgen', 'int_2d', 'int_3d', 'int_tabulated', 'intarr', 'interpol', 'interpolate', 'interval_volume', 'invert', 'ioctl', 'iopen', 'ir_filter', 'iplot', 'ipolygon', 'ipolyline', 'iputdata', 'iregister', 'ireset', 'iresolve', 'irotate', 'isa', 'isave', 'iscale', 'isetcurrent', 'isetproperty', 'ishft', 'isocontour', 'isosurface', 'isurface', 'itext', 'itranslate', 'ivector', 'ivolume', 'izoom', 'journal', 'json_parse', 'json_serialize', 'jul2greg', 'julday', 'keyword_set', 'krig2d', 'kurtosis', 'kw_test', 'l64indgen', 'la_choldc', 'la_cholmprove', 'la_cholsol', 'la_determ', 'la_eigenproblem', 'la_eigenql', 'la_eigenvec', 'la_elmhes', 'la_gm_linear_model', 'la_hqr', 'la_invert', 'la_least_square_equality', 'la_least_squares', 'la_linear_equation', 'la_ludc', 'la_lumprove', 'la_lusol', 'la_svd', 'la_tridc', 'la_trimprove', 'la_triql', 'la_trired', 'la_trisol', 'label_date', 'label_region', 'ladfit', 'laguerre', 'lambda', 'lambdap', 'lambertw', 'laplacian', 'least_squares_filter', 'leefilt', 'legend', 'legendre', 'linbcg', 'lindgen', 'linfit', 'linkimage', 'list', 'll_arc_distance', 'lmfit', 'lmgr', 'lngamma', 'lnp_test', 'loadct', 'locale_get', 'logical_and', 'logical_or', 'logical_true', 'lon64arr', 'lonarr', 'long', 'long64', 'lsode', 'lu_complex', 'ludc', 'lumprove', 'lusol', 'm_correlate', 'machar', 'make_array', 'make_dll', 'make_rt', 'map', 'mapcontinents', 'mapgrid', 'map_2points', 'map_continents', 'map_grid', 'map_image', 'map_patch', 'map_proj_forward', 'map_proj_image', 'map_proj_info', 'map_proj_init', 'map_proj_inverse', 'map_set', 'matrix_multiply', 'matrix_power', 'max', 'md_test', 'mean', 'meanabsdev', 'mean_filter', 'median', 'memory', 'mesh_clip', 'mesh_decimate', 'mesh_issolid', 'mesh_merge', 'mesh_numtriangles', 'mesh_obj', 'mesh_smooth', 'mesh_surfacearea', 'mesh_validate', 'mesh_volume', 'message', 'min', 'min_curve_surf', 'mk_html_help', 'modifyct', 'moment', 'morph_close', 'morph_distance', 'morph_gradient', 'morph_hitormiss', 'morph_open', 'morph_thin', 'morph_tophat', 'multi', 'n_elements', 'n_params', 'n_tags', 'ncdf', 'newton', 'noise_hurl', 'noise_pick', 'noise_scatter', 'noise_slur', 'norm', 'obj_class', 'obj_destroy', 'obj_hasmethod', 'obj_isa', 'obj_new', 'obj_valid', 'objarr', 'on_error', 'on_ioerror', 'online_help', 'openr', 'openu', 'openw', 'oplot', 'oploterr', 'orderedhash', 'p_correlate', 'parse_url', 'particle_trace', 'path_cache', 'path_sep', 'pcomp', 'plot', 'plot3d', 'plot', 'plot_3dbox', 'plot_field', 'ploterr', 'plots', 'polar_contour', 'polar_surface', 'polyfill', 'polyshade', 'pnt_line', 'point_lun', 'polarplot', 'poly', 'poly_2d', 'poly_area', 'poly_fit', 'polyfillv', 'polygon', 'polyline', 'polywarp', 'popd', 'powell', 'pref_commit', 'pref_get', 'pref_set', 'prewitt', 'primes', 'print', 'printf', 'printd', 'pro', 'product', 'profile', 'profiler', 'profiles', 'project_vol', 'ps_show_fonts', 'psafm', 'pseudo', 'ptr_free', 'ptr_new', 'ptr_valid', 'ptrarr', 'pushd', 'qgrid3', 'qhull', 'qromb', 'qromo', 'qsimp', 'query_*', 'query_ascii', 'query_bmp', 'query_csv', 'query_dicom', 'query_gif', 'query_image', 'query_jpeg', 'query_jpeg2000', 'query_mrsid', 'query_pict', 'query_png', 'query_ppm', 'query_srf', 'query_tiff', 'query_video', 'query_wav', 'r_correlate', 'r_test', 'radon', 'randomn', 'randomu', 'ranks', 'rdpix', 'read', 'readf', 'read_ascii', 'read_binary', 'read_bmp', 'read_csv', 'read_dicom', 'read_gif', 'read_image', 'read_interfile', 'read_jpeg', 'read_jpeg2000', 'read_mrsid', 'read_pict', 'read_png', 'read_ppm', 'read_spr', 'read_srf', 'read_sylk', 'read_tiff', 'read_video', 'read_wav', 'read_wave', 'read_x11_bitmap', 'read_xwd', 'reads', 'readu', 'real_part', 'rebin', 'recall_commands', 'recon3', 'reduce_colors', 'reform', 'region_grow', 'register_cursor', 'regress', 'replicate', 'replicate_inplace', 'resolve_all', 'resolve_routine', 'restore', 'retall', 'return', 'reverse', 'rk4', 'roberts', 'rot', 'rotate', 'round', 'routine_filepath', 'routine_info', 'rs_test', 's_test', 'save', 'savgol', 'scale3', 'scale3d', 'scatterplot', 'scatterplot3d', 'scope_level', 'scope_traceback', 'scope_varfetch', 'scope_varname', 'search2d', 'search3d', 'sem_create', 'sem_delete', 'sem_lock', 'sem_release', 'set_plot', 'set_shading', 'setenv', 'sfit', 'shade_surf', 'shade_surf_irr', 'shade_volume', 'shift', 'shift_diff', 'shmdebug', 'shmmap', 'shmunmap', 'shmvar', 'show3', 'showfont', 'signum', 'simplex', 'sin', 'sindgen', 'sinh', 'size', 'skewness', 'skip_lun', 'slicer3', 'slide_image', 'smooth', 'sobel', 'socket', 'sort', 'spawn', 'sph_4pnt', 'sph_scat', 'spher_harm', 'spl_init', 'spl_interp', 'spline', 'spline_p', 'sprsab', 'sprsax', 'sprsin', 'sprstp', 'sqrt', 'standardize', 'stddev', 'stop', 'strarr', 'strcmp', 'strcompress', 'streamline', 'streamline', 'stregex', 'stretch', 'string', 'strjoin', 'strlen', 'strlowcase', 'strmatch', 'strmessage', 'strmid', 'strpos', 'strput', 'strsplit', 'strtrim', 'struct_assign', 'struct_hide', 'strupcase', 'surface', 'surface', 'surfr', 'svdc', 'svdfit', 'svsol', 'swap_endian', 'swap_endian_inplace', 'symbol', 'systime', 't_cvf', 't_pdf', 't3d', 'tag_names', 'tan', 'tanh', 'tek_color', 'temporary', 'terminal_size', 'tetra_clip', 'tetra_surface', 'tetra_volume', 'text', 'thin', 'thread', 'threed', 'tic', 'time_test2', 'timegen', 'timer', 'timestamp', 'timestamptovalues', 'tm_test', 'toc', 'total', 'trace', 'transpose', 'tri_surf', 'triangulate', 'trigrid', 'triql', 'trired', 'trisol', 'truncate_lun', 'ts_coef', 'ts_diff', 'ts_fcast', 'ts_smooth', 'tv', 'tvcrs', 'tvlct', 'tvrd', 'tvscl', 'typename', 'uindgen', 'uint', 'uintarr', 'ul64indgen', 'ulindgen', 'ulon64arr', 'ulonarr', 'ulong', 'ulong64', 'uniq', 'unsharp_mask', 'usersym', 'value_locate', 'variance', 'vector', 'vector_field', 'vel', 'velovect', 'vert_t3d', 'voigt', 'volume', 'voronoi', 'voxel_proj', 'wait', 'warp_tri', 'watershed', 'wdelete', 'wf_draw', 'where', 'widget_base', 'widget_button', 'widget_combobox', 'widget_control', 'widget_displaycontextmenu', 'widget_draw', 'widget_droplist', 'widget_event', 'widget_info', 'widget_label', 'widget_list', 'widget_propertysheet', 'widget_slider', 'widget_tab', 'widget_table', 'widget_text', 'widget_tree', 'widget_tree_move', 'widget_window', 'wiener_filter', 'window', 'window', 'write_bmp', 'write_csv', 'write_gif', 'write_image', 'write_jpeg', 'write_jpeg2000', 'write_nrif', 'write_pict', 'write_png', 'write_ppm', 'write_spr', 'write_srf', 'write_sylk', 'write_tiff', 'write_video', 'write_wav', 'write_wave', 'writeu', 'wset', 'wshow', 'wtn', 'wv_applet', 'wv_cwt', 'wv_cw_wavelet', 'wv_denoise', 'wv_dwt', 'wv_fn_coiflet', 'wv_fn_daubechies', 'wv_fn_gaussian', 'wv_fn_haar', 'wv_fn_morlet', 'wv_fn_paul', 'wv_fn_symlet', 'wv_import_data', 'wv_import_wavelet', 'wv_plot3d_wps', 'wv_plot_multires', 'wv_pwt', 'wv_tool_denoise', 'xbm_edit', 'xdisplayfile', 'xdxf', 'xfont', 'xinteranimate', 'xloadct', 'xmanager', 'xmng_tmpl', 'xmtool', 'xobjview', 'xobjview_rotate', 'xobjview_write_image', 'xpalette', 'xpcolor', 'xplot3d', 'xregistered', 'xroi', 'xsq_test', 'xsurface', 'xvaredit', 'xvolume', 'xvolume_rotate', 'xvolume_write_image', 'xyouts', 'zlib_compress', 'zlib_uncompress', 'zoom', 'zoom_24' ]; var builtins = wordRegexp(builtinArray); var keywordArray = [ 'begin', 'end', 'endcase', 'endfor', 'endwhile', 'endif', 'endrep', 'endforeach', 'break', 'case', 'continue', 'for', 'foreach', 'goto', 'if', 'then', 'else', 'repeat', 'until', 'switch', 'while', 'do', 'pro', 'function' ]; var keywords = wordRegexp(keywordArray); CodeMirror.registerHelper("hintWords", "idl", builtinArray.concat(keywordArray)); var identifiers = new RegExp('^[_a-z\xa1-\uffff][_a-z0-9\xa1-\uffff]*', 'i'); var singleOperators = /[+\-*&=<>\/@#~$]/; var boolOperators = new RegExp('(and|or|eq|lt|le|gt|ge|ne|not)', 'i'); function tokenBase(stream) { // whitespaces if (stream.eatSpace()) return null; // Handle one line Comments if (stream.match(';')) { stream.skipToEnd(); return 'comment'; } // Handle Number Literals if (stream.match(/^[0-9\.+-]/, false)) { if (stream.match(/^[+-]?0x[0-9a-fA-F]+/)) return 'number'; if (stream.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?/)) return 'number'; if (stream.match(/^[+-]?\d+([EeDd][+-]?\d+)?/)) return 'number'; } // Handle Strings if (stream.match(/^"([^"]|(""))*"/)) { return 'string'; } if (stream.match(/^'([^']|(''))*'/)) { return 'string'; } // Handle words if (stream.match(keywords)) { return 'keyword'; } if (stream.match(builtins)) { return 'builtin'; } if (stream.match(identifiers)) { return 'variable'; } if (stream.match(singleOperators) || stream.match(boolOperators)) { return 'operator'; } // Handle non-detected items stream.next(); return null; }; CodeMirror.defineMode('idl', function() { return { token: function(stream) { return tokenBase(stream); } }; }); CodeMirror.defineMIME('text/x-idl', 'idl'); }); ================================================ FILE: third_party/CodeMirror/mode/idl/index.html ================================================ CodeMirror: IDL mode

IDL mode

MIME types defined: text/x-idl.

================================================ FILE: third_party/CodeMirror/mode/index.html ================================================ CodeMirror: Language Modes

Language modes

This is a list of every mode in the distribution. Each mode lives in a subdirectory of the mode/ directory, and typically defines a single JavaScript file that implements the mode. Loading such file will make the language available to CodeMirror, through the mode option.

================================================ FILE: third_party/CodeMirror/mode/javascript/index.html ================================================ CodeMirror: JavaScript mode

JavaScript mode

JavaScript mode supports several configuration options:

  • json which will set the mode to expect JSON data rather than a JavaScript program.
  • jsonld which will set the mode to expect JSON-LD linked data rather than a JavaScript program (demo).
  • typescript which will activate additional syntax highlighting and some other things for TypeScript code (demo).
  • statementIndent which (given a number) will determine the amount of indentation to use for statements continued on a new line.
  • wordCharacters, a regexp that indicates which characters should be considered part of an identifier. Defaults to /[\w$]/, which does not handle non-ASCII identifiers. Can be set to something more elaborate to improve Unicode support.

MIME types defined: text/javascript, application/json, application/ld+json, text/typescript, application/typescript.

================================================ FILE: third_party/CodeMirror/mode/javascript/javascript.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; return { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, "this": kw("this"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, "await": C }; }(); var isOperatorChar = /[+\-*&%=<>!?|~^@]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.match(/^(?:x[\da-f]+|o[0-7]+|b[01]+)n?/i)) { return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^\d*(?:n|(?:\.\d*)?(?:[eE][+\-]?\d+)?)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (expressionAllowed(stream, state, 1)) { readRegexp(stream); stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); return ret("regexp", "string-2"); } else { stream.eat("="); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { if (ch != ">" || !state.lexical || state.lexical.type != ">") { if (stream.eat("=")) { if (ch == "!" || ch == "=") stream.eat("=") } else if (/[<>*+\-]/.test(ch)) { stream.eat(ch) if (ch == ">") stream.eat(ch) } } return ret("operator", "operator", stream.current()); } else if (wordRE.test(ch)) { stream.eatWhile(wordRE); var word = stream.current() if (state.lastType != ".") { if (keywords.propertyIsEnumerable(word)) { var kw = keywords[word] return ret(kw.type, kw.style, word) } if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) return ret("async", "keyword", word) } return ret("variable", "variable", word) } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; if (isTS) { // Try to skip TypeScript return type declarations after the arguments var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) if (m) arrow = m.index } var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) { if (ch == "(") sawSomething = true; break; } } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (wordRE.test(ch)) { sawSomething = true; } else if (/["'\/]/.test(ch)) { return; } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; } } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function inList(name, list) { for (var v = list; v; v = v.next) if (v.name == name) return true return false; } function register(varname) { var state = cx.state; cx.marked = "def"; if (state.context) { if (state.lexical.info == "var" && state.context && state.context.block) { // FIXME function decls are also not block scoped var newContext = registerVarScoped(varname, state.context) if (newContext != null) { state.context = newContext return } } else if (!inList(varname, state.localVars)) { state.localVars = new Var(varname, state.localVars) return } } // Fall through means this is global if (parserConfig.globalVars && !inList(varname, state.globalVars)) state.globalVars = new Var(varname, state.globalVars) } function registerVarScoped(varname, context) { if (!context) { return null } else if (context.block) { var inner = registerVarScoped(varname, context.prev) if (!inner) return null if (inner == context.prev) return context return new Context(inner, context.vars, true) } else if (inList(varname, context.vars)) { return context } else { return new Context(context.prev, new Var(varname, context.vars), false) } } function isModifier(name) { return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" } // Combinators function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } function Var(name, next) { this.name = name; this.next = next } var defaultVars = new Var("this", new Var("arguments", null)) function pushcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, false) cx.state.localVars = defaultVars } function pushblockcontext() { cx.state.context = new Context(cx.state.context, cx.state.localVars, true) cx.state.localVars = null } function popcontext() { cx.state.localVars = cx.state.context.vars cx.state.context = cx.state.context.prev } popcontext.lex = true function pushlex(type, info) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) indent = outer.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { function exp(type) { if (type == wanted) return cont(); else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); else return cont(exp); }; return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); if (type == "debugger") return cont(expect(";")); if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); if (type == ";") return cont(); if (type == "if") { if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); } if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword" return cont(pushlex("form", type == "class" ? type : value), className, poplex) } if (type == "variable") { if (isTS && value == "declare") { cx.marked = "keyword" return cont(statement) } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { cx.marked = "keyword" if (value == "enum") return cont(enumdef); else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) } else if (isTS && value == "namespace") { cx.marked = "keyword" return cont(pushlex("form"), expression, statement, poplex) } else if (isTS && value == "abstract") { cx.marked = "keyword" return cont(statement) } else { return cont(pushlex("stat"), maybelabel); } } if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, block, poplex, poplex, popcontext); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); if (type == "export") return cont(pushlex("stat"), afterExport, poplex); if (type == "import") return cont(pushlex("stat"), afterImport, poplex); if (type == "async") return cont(statement) if (value == "@") return cont(expression, statement) return pass(pushlex("stat"), expression, expect(";"), poplex); } function maybeCatchBinding(type) { if (type == "(") return cont(funarg, expect(")")) } function expression(type, value) { return expressionInner(type, value, false); } function expressionNoComma(type, value) { return expressionInner(type, value, true); } function parenExpr(type) { if (type != "(") return pass() return cont(pushlex(")"), expression, expect(")"), poplex) } function expressionInner(type, value, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); if (type == "quasi") return pass(quasi, maybeop); if (type == "new") return cont(maybeTarget(noComma)); if (type == "import") return cont(expression); return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeoperatorComma(type, value) { if (type == ",") return cont(expression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false)) return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } if (type == "regexp") { cx.state.lastType = cx.marked = "operator" cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) return cont(expr) } } function quasi(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); return pass(type == "{" ? statement : expressionNoComma); } function maybeTarget(noComma) { return function(type) { if (type == ".") return cont(noComma ? targetNoComma : target); else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) else return pass(noComma ? expressionNoComma : expression); }; } function target(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } } function targetNoComma(_, value) { if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "async") { cx.marked = "property"; return cont(objprop); } else if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) cx.state.fatArrowAt = cx.stream.pos + m[0].length return cont(afterprop); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (cx.style + " property"); return cont(afterprop); } else if (type == "jsonld-keyword") { return cont(afterprop); } else if (isTS && isModifier(value)) { cx.marked = "keyword" return cont(objprop) } else if (type == "[") { return cont(expression, maybetype, expect("]"), afterprop); } else if (type == "spread") { return cont(expressionNoComma, afterprop); } else if (value == "*") { cx.marked = "keyword"; return cont(objprop); } else if (type == ":") { return pass(afterprop) } } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end, sep) { function proceed(type, value) { if (sep ? sep.indexOf(type) > -1 : type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(function(type, value) { if (type == end || value == end) return pass() return pass(what) }, proceed); } if (type == end || value == end) return cont(); if (sep && sep.indexOf(";") > -1) return pass(what) return cont(expect(end)); } return function(type, value) { if (type == end || value == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type, value) { if (isTS) { if (type == ":" || value == "in") return cont(typeexpr); if (value == "?") return cont(maybetype); } } function mayberettype(type) { if (isTS && type == ":") { if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) else return cont(typeexpr) } } function isKW(_, value) { if (value == "is") { cx.marked = "keyword" return cont() } } function typeexpr(type, value) { if (value == "keyof" || value == "typeof" || value == "infer") { cx.marked = "keyword" return cont(value == "typeof" ? expressionNoComma : typeexpr) } if (type == "variable" || value == "void") { cx.marked = "type" return cont(afterType) } if (type == "string" || type == "number" || type == "atom") return cont(afterType); if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) } function maybeReturnType(type) { if (type == "=>") return cont(typeexpr) } function typeprop(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property" return cont(typeprop) } else if (value == "?" || type == "number" || type == "string") { return cont(typeprop) } else if (type == ":") { return cont(typeexpr) } else if (type == "[") { return cont(expect("variable"), maybetype, expect("]"), typeprop) } else if (type == "(") { return pass(functiondecl, typeprop) } } function typearg(type, value) { if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) if (type == ":") return cont(typeexpr) if (type == "spread") return cont(typearg) return pass(typeexpr) } function afterType(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) if (value == "|" || type == "." || value == "&") return cont(typeexpr) if (type == "[") return cont(typeexpr, expect("]"), afterType) if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } if (value == "?") return cont(typeexpr, expect(":"), typeexpr) } function maybeTypeArgs(_, value) { if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) } function typeparam() { return pass(typeexpr, maybeTypeDefault) } function maybeTypeDefault(_, value) { if (value == "=") return cont(typeexpr) } function vardef(_, value) { if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } if (type == "variable") { register(value); return cont(); } if (type == "spread") return cont(pattern); if (type == "[") return contCommasep(eltpattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; if (type == "spread") return cont(pattern); if (type == "}") return pass(); if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); return cont(expect(":"), pattern, maybeAssign); } function eltpattern() { return pass(pattern, maybeAssign) } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type, value) { if (value == "await") return cont(forspec); if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); } function forspec1(type) { if (type == "var") return cont(vardef, expect(";"), forspec2); if (type == ";") return cont(forspec2); if (type == "variable") return cont(formaybeinof); return pass(expression, expect(";"), forspec2); } function formaybeinof(_type, value) { if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return cont(maybeoperatorComma, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return pass(expression, expect(";"), forspec3); } function forspec3(type) { if (type != ")") cont(expression); } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) } function functiondecl(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} if (type == "variable") {register(value); return cont(functiondecl);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) } function typename(type, value) { if (type == "keyword" || type == "variable") { cx.marked = "type" return cont(typename) } else if (value == "<") { return cont(pushlex(">"), commasep(typeparam, ">"), poplex) } } function funarg(type, value) { if (value == "@") cont(expression, funarg) if (type == "spread") return cont(funarg); if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } return pass(pattern, maybetype, maybeAssign); } function classExpression(type, value) { // Class expressions may have an optional name. if (type == "variable") return className(type, value); return classNameAfter(type, value); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) if (value == "extends" || value == "implements" || (isTS && type == ",")) { if (value == "implements") cx.marked = "keyword"; return cont(isTS ? typeexpr : expression, classNameAfter); } if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "async" || (type == "variable" && (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { cx.marked = "keyword"; return cont(classBody); } if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; return cont(isTS ? classfield : functiondef, classBody); } if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody); if (type == "[") return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody) if (value == "*") { cx.marked = "keyword"; return cont(classBody); } if (isTS && type == "(") return pass(functiondecl, classBody) if (type == ";" || type == ",") return cont(classBody); if (type == "}") return cont(); if (value == "@") return cont(expression, classBody) } function classfield(type, value) { if (value == "?") return cont(classfield) if (type == ":") return cont(typeexpr, maybeAssign) if (value == "=") return cont(expressionNoComma) var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" return pass(isInterface ? functiondecl : functiondef) } function afterExport(type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); return pass(statement); } function exportField(type, value) { if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } if (type == "variable") return pass(expressionNoComma, exportField); } function afterImport(type) { if (type == "string") return cont(); if (type == "(") return pass(expression); return pass(importSpec, maybeMoreImports, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); if (value == "*") cx.marked = "keyword"; return cont(maybeAs); } function maybeMoreImports(type) { if (type == ",") return cont(importSpec, maybeMoreImports) } function maybeAs(_type, value) { if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(commasep(expressionNoComma, "]")); } function enumdef() { return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) } function enummember() { return pass(pattern, maybeAssign); } function isContinuedStatement(state, textAfter) { return state.lastType == "operator" || state.lastType == "," || isOperatorChar.test(textAfter.charAt(0)) || /[,.]/.test(textAfter.charAt(0)); } function expressionAllowed(stream, state, backUp) { return state.tokenize == tokenBase && /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && new Context(null, null, false), indented: basecolumn || 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top // Kludge to prevent 'maybelse' from blocking lexical scope pops if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } while ((lexical.type == "stat" || lexical.type == "form") && (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && (top == maybeoperatorComma || top == maybeoperatorNoComma) && !/^[,\.=+\-*:?[\(]/.test(textAfter)))) lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", blockCommentContinue: jsonMode ? null : " * ", lineComment: jsonMode ? null : "//", fold: "brace", closeBrackets: "()[]{}''\"\"``", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode, expressionAllowed: expressionAllowed, skipExpression: function(state) { var top = state.cc[state.cc.length - 1] if (top == expression || top == expressionNoComma) state.cc.pop() } }; }); CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/x-javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); }); ================================================ FILE: third_party/CodeMirror/mode/javascript/json-ld.html ================================================ CodeMirror: JSON-LD mode

JSON-LD mode

This is a specialization of the JavaScript mode.

================================================ FILE: third_party/CodeMirror/mode/javascript/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "javascript"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("locals", "[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]; }"); MT("comma-and-binop", "[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }"); MT("destructuring", "([keyword function]([def a], [[[def b], [def c] ]]) {", " [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);", " [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];", "})();"); MT("destructure_trailing_comma", "[keyword let] {[def a], [def b],} [operator =] [variable foo];", "[keyword let] [def c];"); // Parser still in good state? MT("class_body", "[keyword class] [def Foo] {", " [property constructor]() {}", " [property sayName]() {", " [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];", " }", "}"); MT("class", "[keyword class] [def Point] [keyword extends] [variable SuperThing] {", " [keyword get] [property prop]() { [keyword return] [number 24]; }", " [property constructor]([def x], [def y]) {", " [keyword super]([string 'something']);", " [keyword this].[property x] [operator =] [variable-2 x];", " }", "}"); MT("anonymous_class_expression", "[keyword const] [def Adder] [operator =] [keyword class] [keyword extends] [variable Arithmetic] {", " [property add]([def a], [def b]) {}", "};"); MT("named_class_expression", "[keyword const] [def Subber] [operator =] [keyword class] [def Subtract] {", " [property sub]([def a], [def b]) {}", "};"); MT("class_async_method", "[keyword class] [def Foo] {", " [property sayName1]() {}", " [keyword async] [property sayName2]() {}", "}"); MT("import", "[keyword function] [def foo]() {", " [keyword import] [def $] [keyword from] [string 'jquery'];", " [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];", "}"); MT("import_trailing_comma", "[keyword import] {[def foo], [def bar],} [keyword from] [string 'baz']") MT("import_dynamic", "[keyword import]([string 'baz']).[property then]") MT("import_dynamic", "[keyword const] [def t] [operator =] [keyword import]([string 'baz']).[property then]") MT("const", "[keyword function] [def f]() {", " [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];", "}"); MT("for/of", "[keyword for]([keyword let] [def of] [keyword of] [variable something]) {}"); MT("for await", "[keyword for] [keyword await]([keyword let] [def of] [keyword of] [variable something]) {}"); MT("generator", "[keyword function*] [def repeat]([def n]) {", " [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])", " [keyword yield] [variable-2 i];", "}"); MT("let_scoping", "[keyword function] [def scoped]([def n]) {", " { [keyword var] [def i]; } [variable-2 i];", " { [keyword let] [def j]; [variable-2 j]; } [variable j];", " [keyword if] ([atom true]) { [keyword const] [def k]; [variable-2 k]; } [variable k];", "}"); MT("switch_scoping", "[keyword switch] ([variable x]) {", " [keyword default]:", " [keyword let] [def j];", " [keyword return] [variable-2 j]", "}", "[variable j];") MT("leaving_scope", "[keyword function] [def a]() {", " {", " [keyword const] [def x] [operator =] [number 1]", " [keyword if] ([atom true]) {", " [keyword let] [def y] [operator =] [number 2]", " [keyword var] [def z] [operator =] [number 3]", " [variable console].[property log]([variable-2 x], [variable-2 y], [variable-2 z])", " }", " [variable console].[property log]([variable-2 x], [variable y], [variable-2 z])", " }", " [variable console].[property log]([variable x], [variable y], [variable-2 z])", "}") MT("quotedStringAddition", "[keyword let] [def f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];"); MT("quotedFatArrow", "[keyword let] [def f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];"); MT("fatArrow", "[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);", "[variable a];", // No longer in scope "[keyword let] [def f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];", "[variable c];"); MT("spread", "[keyword function] [def f]([def a], [meta ...][def b]) {", " [variable something]([variable-2 a], [meta ...][variable-2 b]);", "}"); MT("quasi", "[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("quasi_no_function", "[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]"); MT("indent_statement", "[keyword var] [def x] [operator =] [number 10]", "[variable x] [operator +=] [variable y] [operator +]", " [atom Infinity]", "[keyword debugger];"); MT("indent_if", "[keyword if] ([number 1])", " [keyword break];", "[keyword else] [keyword if] ([number 2])", " [keyword continue];", "[keyword else]", " [number 10];", "[keyword if] ([number 1]) {", " [keyword break];", "} [keyword else] [keyword if] ([number 2]) {", " [keyword continue];", "} [keyword else] {", " [number 10];", "}"); MT("indent_for", "[keyword for] ([keyword var] [def i] [operator =] [number 0];", " [variable i] [operator <] [number 100];", " [variable i][operator ++])", " [variable doSomething]([variable i]);", "[keyword debugger];"); MT("indent_c_style", "[keyword function] [def foo]()", "{", " [keyword debugger];", "}"); MT("indent_else", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [keyword if] ([variable bar])", " [number 1];", " [keyword else]", " [number 2];", " [keyword else]", " [number 3];"); MT("indent_funarg", "[variable foo]([number 10000],", " [keyword function]([def a]) {", " [keyword debugger];", "};"); MT("indent_below_if", "[keyword for] (;;)", " [keyword if] ([variable foo])", " [number 1];", "[number 2];"); MT("indent_semicolonless_if", "[keyword function] [def foo]() {", " [keyword if] ([variable x])", " [variable foo]()", "}") MT("indent_semicolonless_if_with_statement", "[keyword function] [def foo]() {", " [keyword if] ([variable x])", " [variable foo]()", " [variable bar]()", "}") MT("multilinestring", "[keyword var] [def x] [operator =] [string 'foo\\]", "[string bar'];"); MT("scary_regexp", "[string-2 /foo[[/]]bar/];"); MT("indent_strange_array", "[keyword var] [def x] [operator =] [[", " [number 1],,", " [number 2],", "]];", "[number 10];"); MT("param_default", "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {", " [keyword return] [variable-2 x];", "}"); MT( "param_destructuring", "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {", " [keyword return] [variable-2 x];", "}"); MT("new_target", "[keyword function] [def F]([def target]) {", " [keyword if] ([variable-2 target] [operator &&] [keyword new].[keyword target].[property name]) {", " [keyword return] [keyword new]", " .[keyword target];", " }", "}"); MT("async", "[keyword async] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }"); MT("async_assignment", "[keyword const] [def foo] [operator =] [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; };"); MT("async_object", "[keyword let] [def obj] [operator =] { [property async]: [atom false] };"); // async be highlighet as keyword and foo as def, but it requires potentially expensive look-ahead. See #4173 MT("async_object_function", "[keyword let] [def obj] [operator =] { [property async] [property foo]([def args]) { [keyword return] [atom true]; } };"); MT("async_object_properties", "[keyword let] [def obj] [operator =] {", " [property prop1]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },", " [property prop2]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },", " [property prop3]: [keyword async] [keyword function] [def prop3]([def args]) { [keyword return] [atom true]; },", "};"); MT("async_arrow", "[keyword const] [def foo] [operator =] [keyword async] ([def args]) [operator =>] { [keyword return] [atom true]; };"); MT("async_jquery", "[variable $].[property ajax]({", " [property url]: [variable url],", " [property async]: [atom true],", " [property method]: [string 'GET']", "});"); MT("async_variable", "[keyword const] [def async] [operator =] {[property a]: [number 1]};", "[keyword const] [def foo] [operator =] [string-2 `bar ${][variable async].[property a][string-2 }`];") MT("bigint", "[number 1n] [operator +] [number 0x1afn] [operator +] [number 0o064n] [operator +] [number 0b100n];") MT("async_comment", "[keyword async] [comment /**/] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }"); MT("indent_switch", "[keyword switch] ([variable x]) {", " [keyword default]:", " [keyword return] [number 2]", "}") MT("regexp_corner_case", "[operator +]{} [operator /] [atom undefined];", "[[[meta ...][string-2 /\\//] ]];", "[keyword void] [string-2 /\\//];", "[keyword do] [string-2 /\\//]; [keyword while] ([number 0]);", "[keyword if] ([number 0]) {} [keyword else] [string-2 /\\//];", "[string-2 `${][variable async][operator ++][string-2 }//`];", "[string-2 `${]{} [operator /] [string-2 /\\//}`];") MT("return_eol", "[keyword return]", "{} [string-2 /5/]") var ts_mode = CodeMirror.getMode({indentUnit: 2}, "application/typescript") function TS(name) { test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1)) } TS("typescript_extend_type", "[keyword class] [def Foo] [keyword extends] [type Some][operator <][type Type][operator >] {}") TS("typescript_arrow_type", "[keyword let] [def x]: ([variable arg]: [type Type]) [operator =>] [type ReturnType]") TS("typescript_class", "[keyword class] [def Foo] {", " [keyword public] [keyword static] [property main]() {}", " [keyword private] [property _foo]: [type string];", "}") TS("typescript_literal_types", "[keyword import] [keyword *] [keyword as] [def Sequelize] [keyword from] [string 'sequelize'];", "[keyword interface] [def MyAttributes] {", " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];", " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];", "}", "[keyword interface] [def MyInstance] [keyword extends] [type Sequelize].[type Instance] [operator <] [type MyAttributes] [operator >] {", " [property rawAttributes]: [type MyAttributes];", " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];", " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];", "}") TS("typescript_extend_operators", "[keyword export] [keyword interface] [def UserModel] [keyword extends]", " [type Sequelize].[type Model] [operator <] [type UserInstance], [type UserAttributes] [operator >] {", " [property findById]: (", " [variable userId]: [type number]", " ) [operator =>] [type Promise] [operator <] [type Array] [operator <] { [property id], [property name] } [operator >>];", " [property updateById]: (", " [variable userId]: [type number],", " [variable isActive]: [type boolean]", " ) [operator =>] [type Promise] [operator <] [type AccountHolderNotificationPreferenceInstance] [operator >];", " }") TS("typescript_interface_with_const", "[keyword const] [def hello]: {", " [property prop1][operator ?]: [type string];", " [property prop2][operator ?]: [type string];", "} [operator =] {};") TS("typescript_double_extend", "[keyword export] [keyword interface] [def UserAttributes] {", " [property id][operator ?]: [type number];", " [property createdAt][operator ?]: [type Date];", "}", "[keyword export] [keyword interface] [def UserInstance] [keyword extends] [type Sequelize].[type Instance][operator <][type UserAttributes][operator >], [type UserAttributes] {", " [property id]: [type number];", " [property createdAt]: [type Date];", "}"); TS("typescript_index_signature", "[keyword interface] [def A] {", " [[ [variable prop]: [type string] ]]: [type any];", " [property prop1]: [type any];", "}"); TS("typescript_generic_class", "[keyword class] [def Foo][operator <][type T][operator >] {", " [property bar]() {}", " [property foo](): [type Foo] {}", "}") TS("typescript_type_when_keyword", "[keyword export] [keyword type] [type AB] [operator =] [type A] [operator |] [type B];", "[keyword type] [type Flags] [operator =] {", " [property p1]: [type string];", " [property p2]: [type boolean];", "};") TS("typescript_type_when_not_keyword", "[keyword class] [def HasType] {", " [property type]: [type string];", " [property constructor]([def type]: [type string]) {", " [keyword this].[property type] [operator =] [variable-2 type];", " }", " [property setType]({ [def type] }: { [property type]: [type string]; }) {", " [keyword this].[property type] [operator =] [variable-2 type];", " }", "}") TS("typescript_function_generics", "[keyword function] [def a]() {}", "[keyword function] [def b][operator <][type IA] [keyword extends] [type object], [type IB] [keyword extends] [type object][operator >]() {}", "[keyword function] [def c]() {}") TS("typescript_complex_return_type", "[keyword function] [def A]() {", " [keyword return] [keyword this].[property property];", "}", "[keyword function] [def B](): [type Promise][operator <]{ [[ [variable key]: [type string] ]]: [type any] } [operator |] [atom null][operator >] {", " [keyword return] [keyword this].[property property];", "}") TS("typescript_complex_type_casting", "[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]; } };") TS("typescript_keyof", "[keyword function] [def x][operator <][type T] [keyword extends] [keyword keyof] [type X][operator >]([def a]: [type T]) {", " [keyword return]") TS("typescript_new_typeargs", "[keyword let] [def x] [operator =] [keyword new] [variable Map][operator <][type string], [type Date][operator >]([string-2 `foo${][variable bar][string-2 }`])") TS("modifiers", "[keyword class] [def Foo] {", " [keyword public] [keyword abstract] [property bar]() {}", " [property constructor]([keyword readonly] [keyword private] [def x]) {}", "}") TS("arrow prop", "({[property a]: [def p] [operator =>] [variable-2 p]})") TS("generic in function call", "[keyword this].[property a][operator <][type Type][operator >]([variable foo]);", "[keyword this].[property a][operator <][variable Type][operator >][variable foo];") TS("type guard", "[keyword class] [def Appler] {", " [keyword static] [property assertApple]([def fruit]: [type Fruit]): [variable-2 fruit] [keyword is] [type Apple] {", " [keyword if] ([operator !]([variable-2 fruit] [keyword instanceof] [variable Apple]))", " [keyword throw] [keyword new] [variable Error]();", " }", "}") TS("type as variable", "[variable type] [operator =] [variable x] [keyword as] [type Bar];"); TS("enum body", "[keyword export] [keyword const] [keyword enum] [def CodeInspectionResultType] {", " [def ERROR] [operator =] [string 'problem_type_error'],", " [def WARNING] [operator =] [string 'problem_type_warning'],", " [def META],", "}") TS("parenthesized type", "[keyword class] [def Foo] {", " [property x] [operator =] [keyword new] [variable A][operator <][type B], [type string][operator |](() [operator =>] [type void])[operator >]();", " [keyword private] [property bar]();", "}") TS("abstract class", "[keyword export] [keyword abstract] [keyword class] [def Foo] {}") TS("interface without semicolons", "[keyword interface] [def Foo] {", " [property greet]([def x]: [type int]): [type blah]", " [property bar]: [type void]", "}") var jsonld_mode = CodeMirror.getMode( {indentUnit: 2}, {name: "javascript", jsonld: true} ); function LD(name) { test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1)); } LD("json_ld_keywords", '{', ' [meta "@context"]: {', ' [meta "@base"]: [string "http://example.com"],', ' [meta "@vocab"]: [string "http://xmlns.com/foaf/0.1/"],', ' [property "likesFlavor"]: {', ' [meta "@container"]: [meta "@list"]', ' [meta "@reverse"]: [string "@beFavoriteOf"]', ' },', ' [property "nick"]: { [meta "@container"]: [meta "@set"] },', ' [property "nick"]: { [meta "@container"]: [meta "@index"] }', ' },', ' [meta "@graph"]: [[ {', ' [meta "@id"]: [string "http://dbpedia.org/resource/John_Lennon"],', ' [property "name"]: [string "John Lennon"],', ' [property "modified"]: {', ' [meta "@value"]: [string "2010-05-29T14:17:39+02:00"],', ' [meta "@type"]: [string "http://www.w3.org/2001/XMLSchema#dateTime"]', ' }', ' } ]]', '}'); LD("json_ld_fake", '{', ' [property "@fake"]: [string "@fake"],', ' [property "@contextual"]: [string "@identifier"],', ' [property "user@domain.com"]: [string "@graphical"],', ' [property "@ID"]: [string "@@ID"]', '}'); })(); ================================================ FILE: third_party/CodeMirror/mode/javascript/typescript.html ================================================ CodeMirror: TypeScript mode

TypeScript mode

This is a specialization of the JavaScript mode.

================================================ FILE: third_party/CodeMirror/mode/jinja2/index.html ================================================ CodeMirror: Jinja2 mode

Jinja2 mode

================================================ FILE: third_party/CodeMirror/mode/jinja2/jinja2.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("jinja2", function() { var keywords = ["and", "as", "block", "endblock", "by", "cycle", "debug", "else", "elif", "extends", "filter", "endfilter", "firstof", "for", "endfor", "if", "endif", "ifchanged", "endifchanged", "ifequal", "endifequal", "ifnotequal", "endifnotequal", "in", "include", "load", "not", "now", "or", "parsed", "regroup", "reversed", "spaceless", "endspaceless", "ssi", "templatetag", "openblock", "closeblock", "openvariable", "closevariable", "openbrace", "closebrace", "opencomment", "closecomment", "widthratio", "url", "with", "endwith", "get_current_language", "trans", "endtrans", "noop", "blocktrans", "endblocktrans", "get_available_languages", "get_current_language_bidi", "plural"], operator = /^[+\-*&%=<>!?|~^]/, sign = /^[:\[\(\{]/, atom = ["true", "false"], number = /^(\d[+\-\*\/])?\d+(\.\d+)?/; keywords = new RegExp("((" + keywords.join(")|(") + "))\\b"); atom = new RegExp("((" + atom.join(")|(") + "))\\b"); function tokenBase (stream, state) { var ch = stream.peek(); //Comment if (state.incomment) { if(!stream.skipTo("#}")) { stream.skipToEnd(); } else { stream.eatWhile(/\#|}/); state.incomment = false; } return "comment"; //Tag } else if (state.intag) { //After operator if(state.operator) { state.operator = false; if(stream.match(atom)) { return "atom"; } if(stream.match(number)) { return "number"; } } //After sign if(state.sign) { state.sign = false; if(stream.match(atom)) { return "atom"; } if(stream.match(number)) { return "number"; } } if(state.instring) { if(ch == state.instring) { state.instring = false; } stream.next(); return "string"; } else if(ch == "'" || ch == '"') { state.instring = ch; stream.next(); return "string"; } else if(stream.match(state.intag + "}") || stream.eat("-") && stream.match(state.intag + "}")) { state.intag = false; return "tag"; } else if(stream.match(operator)) { state.operator = true; return "operator"; } else if(stream.match(sign)) { state.sign = true; } else { if(stream.eat(" ") || stream.sol()) { if(stream.match(keywords)) { return "keyword"; } if(stream.match(atom)) { return "atom"; } if(stream.match(number)) { return "number"; } if(stream.sol()) { stream.next(); } } else { stream.next(); } } return "variable"; } else if (stream.eat("{")) { if (stream.eat("#")) { state.incomment = true; if(!stream.skipTo("#}")) { stream.skipToEnd(); } else { stream.eatWhile(/\#|}/); state.incomment = false; } return "comment"; //Open tag } else if (ch = stream.eat(/\{|%/)) { //Cache close tag state.intag = ch; if(ch == "{") { state.intag = "}"; } stream.eat("-"); return "tag"; } } stream.next(); }; return { startState: function () { return {tokenize: tokenBase}; }, token: function (stream, state) { return state.tokenize(stream, state); }, blockCommentStart: "{#", blockCommentEnd: "#}" }; }); CodeMirror.defineMIME("text/jinja2", "jinja2"); }); ================================================ FILE: third_party/CodeMirror/mode/jsx/index.html ================================================ CodeMirror: JSX mode

JSX mode

JSX Mode for React's JavaScript syntax extension.

MIME types defined: text/jsx, text/typescript-jsx.

================================================ FILE: third_party/CodeMirror/mode/jsx/jsx.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../javascript/javascript")) else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript"], mod) else // Plain browser env mod(CodeMirror) })(function(CodeMirror) { "use strict" // Depth means the amount of open braces in JS context, in XML // context 0 means not in tag, 1 means in tag, and 2 means in tag // and js block comment. function Context(state, mode, depth, prev) { this.state = state; this.mode = mode; this.depth = depth; this.prev = prev } function copyContext(context) { return new Context(CodeMirror.copyState(context.mode, context.state), context.mode, context.depth, context.prev && copyContext(context.prev)) } CodeMirror.defineMode("jsx", function(config, modeConfig) { var xmlMode = CodeMirror.getMode(config, {name: "xml", allowMissing: true, multilineTagIndentPastTag: false, allowMissingTagName: true}) var jsMode = CodeMirror.getMode(config, modeConfig && modeConfig.base || "javascript") function flatXMLIndent(state) { var tagName = state.tagName state.tagName = null var result = xmlMode.indent(state, "", "") state.tagName = tagName return result } function token(stream, state) { if (state.context.mode == xmlMode) return xmlToken(stream, state, state.context) else return jsToken(stream, state, state.context) } function xmlToken(stream, state, cx) { if (cx.depth == 2) { // Inside a JS /* */ comment if (stream.match(/^.*?\*\//)) cx.depth = 1 else stream.skipToEnd() return "comment" } if (stream.peek() == "{") { xmlMode.skipAttribute(cx.state) var indent = flatXMLIndent(cx.state), xmlContext = cx.state.context // If JS starts on same line as tag if (xmlContext && stream.match(/^[^>]*>\s*$/, false)) { while (xmlContext.prev && !xmlContext.startOfLine) xmlContext = xmlContext.prev // If tag starts the line, use XML indentation level if (xmlContext.startOfLine) indent -= config.indentUnit // Else use JS indentation level else if (cx.prev.state.lexical) indent = cx.prev.state.lexical.indented // Else if inside of tag } else if (cx.depth == 1) { indent += config.indentUnit } state.context = new Context(CodeMirror.startState(jsMode, indent), jsMode, 0, state.context) return null } if (cx.depth == 1) { // Inside of tag if (stream.peek() == "<") { // Tag inside of tag xmlMode.skipAttribute(cx.state) state.context = new Context(CodeMirror.startState(xmlMode, flatXMLIndent(cx.state)), xmlMode, 0, state.context) return null } else if (stream.match("//")) { stream.skipToEnd() return "comment" } else if (stream.match("/*")) { cx.depth = 2 return token(stream, state) } } var style = xmlMode.token(stream, cx.state), cur = stream.current(), stop if (/\btag\b/.test(style)) { if (/>$/.test(cur)) { if (cx.state.context) cx.depth = 0 else state.context = state.context.prev } else if (/^ -1) { stream.backUp(cur.length - stop) } return style } function jsToken(stream, state, cx) { if (stream.peek() == "<" && jsMode.expressionAllowed(stream, cx.state)) { jsMode.skipExpression(cx.state) state.context = new Context(CodeMirror.startState(xmlMode, jsMode.indent(cx.state, "", "")), xmlMode, 0, state.context) return null } var style = jsMode.token(stream, cx.state) if (!style && cx.depth != null) { var cur = stream.current() if (cur == "{") { cx.depth++ } else if (cur == "}") { if (--cx.depth == 0) state.context = state.context.prev } } return style } return { startState: function() { return {context: new Context(CodeMirror.startState(jsMode), jsMode)} }, copyState: function(state) { return {context: copyContext(state.context)} }, token: token, indent: function(state, textAfter, fullLine) { return state.context.mode.indent(state.context.state, textAfter, fullLine) }, innerMode: function(state) { return state.context } } }, "xml", "javascript") CodeMirror.defineMIME("text/jsx", "jsx") CodeMirror.defineMIME("text/typescript-jsx", {name: "jsx", base: {name: "javascript", typescript: true}}) }); ================================================ FILE: third_party/CodeMirror/mode/jsx/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "jsx") function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)) } MT("selfclose", "[keyword var] [def x] [operator =] [bracket&tag <] [tag foo] [bracket&tag />] [operator +] [number 1];") MT("openclose", "([bracket&tag <][tag foo][bracket&tag >]hello [atom &][bracket&tag ][operator ++])") MT("openclosefragment", "([bracket&tag <><][tag foo][bracket&tag >]hello [atom &][bracket&tag ][operator ++])") MT("attr", "([bracket&tag <][tag foo] [attribute abc]=[string 'value'][bracket&tag >]hello [atom &][bracket&tag ][operator ++])") MT("braced_attr", "([bracket&tag <][tag foo] [attribute abc]={[number 10]}[bracket&tag >]hello [atom &][bracket&tag ][operator ++])") MT("braced_text", "([bracket&tag <][tag foo][bracket&tag >]hello {[number 10]} [atom &][bracket&tag ][operator ++])") MT("nested_tag", "([bracket&tag <][tag foo][bracket&tag ><][tag bar][bracket&tag >][operator ++])") MT("nested_jsx", "[keyword return] (", " [bracket&tag <][tag foo][bracket&tag >]", " say {[number 1] [operator +] [bracket&tag <][tag bar] [attribute attr]={[number 10]}[bracket&tag />]}!", " [bracket&tag ][operator ++]", ")") MT("preserve_js_context", "[variable x] [operator =] [string-2 `quasi${][bracket&tag <][tag foo][bracket&tag />][string-2 }quoted`]") MT("string_interpolation", "[variable x] [operator =] [string-2 `quasi${] [number 10] [string-2 }`]") MT("line_comment", "([bracket&tag <][tag foo] [comment // hello]", " [bracket&tag >][operator ++])") MT("line_comment_not_in_tag", "([bracket&tag <][tag foo][bracket&tag >] // hello", " [bracket&tag ][operator ++])") MT("block_comment", "([bracket&tag <][tag foo] [comment /* hello]", "[comment line 2]", "[comment line 3 */] [bracket&tag >][operator ++])") MT("block_comment_not_in_tag", "([bracket&tag <][tag foo][bracket&tag >]/* hello", " line 2", " line 3 */ [bracket&tag ][operator ++])") MT("missing_attr", "([bracket&tag <][tag foo] [attribute selected][bracket&tag />][operator ++])") MT("indent_js", "([bracket&tag <][tag foo][bracket&tag >]", " [bracket&tag <][tag bar] [attribute baz]={[keyword function]() {", " [keyword return] [number 10]", " }}[bracket&tag />]", " [bracket&tag ])") MT("spread", "([bracket&tag <][tag foo] [attribute bar]={[meta ...][variable baz] [operator /][number 2]}[bracket&tag />])") MT("tag_attribute", "([bracket&tag <][tag foo] [attribute bar]=[bracket&tag <][tag foo][bracket&tag />/>][operator ++])") var ts_mode = CodeMirror.getMode({indentUnit: 2}, "text/typescript-jsx") function TS(name) { test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1)) } TS("tsx_react_integration", "[keyword interface] [def Props] {", " [property foo]: [type string];", "}", "[keyword class] [def MyComponent] [keyword extends] [type React].[type Component] [operator <] [type Props], [type any] [operator >] {", " [property render]() {", " [keyword return] [bracket&tag <][tag span][bracket&tag >]{[keyword this].[property props].[property foo]}[bracket&tag ]", " }", "}", "[bracket&tag <][tag MyComponent] [attribute foo]=[string \"bar\"] [bracket&tag />]; [comment //ok]", "[bracket&tag <][tag MyComponent] [attribute foo]={[number 0]} [bracket&tag />]; [comment //error]") })() ================================================ FILE: third_party/CodeMirror/mode/julia/index.html ================================================ CodeMirror: Julia mode

Julia mode

MIME types defined: text/x-julia.

================================================ FILE: third_party/CodeMirror/mode/julia/julia.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("julia", function(config, parserConf) { function wordRegexp(words, end) { if (typeof end === "undefined") { end = "\\b"; } return new RegExp("^((" + words.join(")|(") + "))" + end); } var octChar = "\\\\[0-7]{1,3}"; var hexChar = "\\\\x[A-Fa-f0-9]{1,2}"; var sChar = "\\\\[abefnrtv0%?'\"\\\\]"; var uChar = "([^\\u0027\\u005C\\uD800-\\uDFFF]|[\\uD800-\\uDFFF][\\uDC00-\\uDFFF])"; var operators = parserConf.operators || wordRegexp([ "[<>]:", "[<>=]=", "<<=?", ">>>?=?", "=>", "->", "\\/\\/", "[\\\\%*+\\-<>!=\\/^|&\\u00F7\\u22BB]=?", "\\?", "\\$", "~", ":", "\\u00D7", "\\u2208", "\\u2209", "\\u220B", "\\u220C", "\\u2218", "\\u221A", "\\u221B", "\\u2229", "\\u222A", "\\u2260", "\\u2264", "\\u2265", "\\u2286", "\\u2288", "\\u228A", "\\u22C5", "\\b(in|isa)\\b(?!\.?\\()"], ""); var delimiters = parserConf.delimiters || /^[;,()[\]{}]/; var identifiers = parserConf.identifiers || /^[_A-Za-z\u00A1-\u2217\u2219-\uFFFF][\w\u00A1-\u2217\u2219-\uFFFF]*!*/; var chars = wordRegexp([octChar, hexChar, sChar, uChar], "'"); var commonOpeners = ["begin", "function", "type", "struct", "immutable", "let", "macro", "for", "while", "quote", "if", "else", "elseif", "try", "finally", "catch", "do"]; var commonClosers = ["end", "else", "elseif", "catch", "finally"]; var commonKeywords = ["if", "else", "elseif", "while", "for", "begin", "let", "end", "do", "try", "catch", "finally", "return", "break", "continue", "global", "local", "const", "export", "import", "importall", "using", "function", "where", "macro", "module", "baremodule", "struct", "type", "mutable", "immutable", "quote", "typealias", "abstract", "primitive", "bitstype"]; var commonBuiltins = ["true", "false", "nothing", "NaN", "Inf"]; CodeMirror.registerHelper("hintWords", "julia", commonKeywords.concat(commonBuiltins)); var openers = wordRegexp(commonOpeners); var closers = wordRegexp(commonClosers); var keywords = wordRegexp(commonKeywords); var builtins = wordRegexp(commonBuiltins); var macro = /^@[_A-Za-z][\w]*/; var symbol = /^:[_A-Za-z\u00A1-\uFFFF][\w\u00A1-\uFFFF]*!*/; var stringPrefixes = /^(`|([_A-Za-z\u00A1-\uFFFF]*"("")?))/; function inArray(state) { return inGenerator(state, '[') } function inGenerator(state, bracket, depth) { if (typeof(bracket) === "undefined") { bracket = '('; } if (typeof(depth) === "undefined") { depth = 0; } var scope = currentScope(state, depth); if ((depth == 0 && scope === "if" && inGenerator(state, bracket, depth + 1)) || (scope === "for" && inGenerator(state, bracket, depth + 1)) || (scope === bracket)) { return true; } return false; } function currentScope(state, n) { if (typeof(n) === "undefined") { n = 0; } if (state.scopes.length <= n) { return null; } return state.scopes[state.scopes.length - (n + 1)]; } // tokenizers function tokenBase(stream, state) { // Handle multiline comments if (stream.match(/^#=/, false)) { state.tokenize = tokenComment; return state.tokenize(stream, state); } // Handle scope changes var leavingExpr = state.leavingExpr; if (stream.sol()) { leavingExpr = false; } state.leavingExpr = false; if (leavingExpr) { if (stream.match(/^'+/)) { return "operator"; } } if (stream.match(/\.{4,}/)) { return "error"; } else if (stream.match(/\.{1,3}/)) { return "operator"; } if (stream.eatSpace()) { return null; } var ch = stream.peek(); // Handle single line comments if (ch === '#') { stream.skipToEnd(); return "comment"; } if (ch === '[') { state.scopes.push('['); } if (ch === '(') { state.scopes.push('('); } if (inArray(state) && ch === ']') { if (currentScope(state) === "if") { state.scopes.pop(); } while (currentScope(state) === "for") { state.scopes.pop(); } state.scopes.pop(); state.leavingExpr = true; } if (inGenerator(state) && ch === ')') { if (currentScope(state) === "if") { state.scopes.pop(); } while (currentScope(state) === "for") { state.scopes.pop(); } state.scopes.pop(); state.leavingExpr = true; } if (inArray(state)) { if (state.lastToken == "end" && stream.match(/^:/)) { return "operator"; } if (stream.match(/^end/)) { return "number"; } } var match; if (match = stream.match(openers)) { state.scopes.push(match[0]); return "keyword"; } if (stream.match(closers)) { state.scopes.pop(); return "keyword"; } // Handle type annotations if (stream.match(/^::(?![:\$])/)) { state.tokenize = tokenAnnotation; return state.tokenize(stream, state); } // Handle symbols if (!leavingExpr && stream.match(symbol) || stream.match(/:([<>]:|<<=?|>>>?=?|->|\/\/|\.{2,3}|[\.\\%*+\-<>!\/^|&]=?|[~\?\$])/)) { return "builtin"; } // Handle parametric types //if (stream.match(/^{[^}]*}(?=\()/)) { // return "builtin"; //} // Handle operators and Delimiters if (stream.match(operators)) { return "operator"; } // Handle Number Literals if (stream.match(/^\.?\d/, false)) { var imMatcher = RegExp(/^im\b/); var numberLiteral = false; // Floats if (stream.match(/^\d*\.(?!\.)\d*([Eef][\+\-]?\d+)?/i)) { numberLiteral = true; } if (stream.match(/^\d+\.(?!\.)\d*/)) { numberLiteral = true; } if (stream.match(/^\.\d+/)) { numberLiteral = true; } if (stream.match(/^0x\.[0-9a-f]+p[\+\-]?\d+/i)) { numberLiteral = true; } // Integers if (stream.match(/^0x[0-9a-f]+/i)) { numberLiteral = true; } // Hex if (stream.match(/^0b[01]+/i)) { numberLiteral = true; } // Binary if (stream.match(/^0o[0-7]+/i)) { numberLiteral = true; } // Octal if (stream.match(/^[1-9]\d*(e[\+\-]?\d+)?/)) { numberLiteral = true; } // Decimal // Zero by itself with no other piece of number. if (stream.match(/^0(?![\dx])/i)) { numberLiteral = true; } if (numberLiteral) { // Integer literals may be "long" stream.match(imMatcher); state.leavingExpr = true; return "number"; } } // Handle Chars if (stream.match(/^'/)) { state.tokenize = tokenChar; return state.tokenize(stream, state); } // Handle Strings if (stream.match(stringPrefixes)) { state.tokenize = tokenStringFactory(stream.current()); return state.tokenize(stream, state); } if (stream.match(macro)) { return "meta"; } if (stream.match(delimiters)) { return null; } if (stream.match(keywords)) { return "keyword"; } if (stream.match(builtins)) { return "builtin"; } var isDefinition = state.isDefinition || state.lastToken == "function" || state.lastToken == "macro" || state.lastToken == "type" || state.lastToken == "struct" || state.lastToken == "immutable"; if (stream.match(identifiers)) { if (isDefinition) { if (stream.peek() === '.') { state.isDefinition = true; return "variable"; } state.isDefinition = false; return "def"; } if (stream.match(/^({[^}]*})*\(/, false)) { state.tokenize = tokenCallOrDef; return state.tokenize(stream, state); } state.leavingExpr = true; return "variable"; } // Handle non-detected items stream.next(); return "error"; } function tokenCallOrDef(stream, state) { var match = stream.match(/^(\(\s*)/); if (match) { if (state.firstParenPos < 0) state.firstParenPos = state.scopes.length; state.scopes.push('('); state.charsAdvanced += match[1].length; } if (currentScope(state) == '(' && stream.match(/^\)/)) { state.scopes.pop(); state.charsAdvanced += 1; if (state.scopes.length <= state.firstParenPos) { var isDefinition = stream.match(/^(\s*where\s+[^\s=]+)*\s*?=(?!=)/, false); stream.backUp(state.charsAdvanced); state.firstParenPos = -1; state.charsAdvanced = 0; state.tokenize = tokenBase; if (isDefinition) return "def"; return "builtin"; } } // Unfortunately javascript does not support multiline strings, so we have // to undo anything done upto here if a function call or definition splits // over two or more lines. if (stream.match(/^$/g, false)) { stream.backUp(state.charsAdvanced); while (state.scopes.length > state.firstParenPos) state.scopes.pop(); state.firstParenPos = -1; state.charsAdvanced = 0; state.tokenize = tokenBase; return "builtin"; } state.charsAdvanced += stream.match(/^([^()]*)/)[1].length; return state.tokenize(stream, state); } function tokenAnnotation(stream, state) { stream.match(/.*?(?=,|;|{|}|\(|\)|=|$|\s)/); if (stream.match(/^{/)) { state.nestedLevels++; } else if (stream.match(/^}/)) { state.nestedLevels--; } if (state.nestedLevels > 0) { stream.match(/.*?(?={|})/) || stream.next(); } else if (state.nestedLevels == 0) { state.tokenize = tokenBase; } return "builtin"; } function tokenComment(stream, state) { if (stream.match(/^#=/)) { state.nestedLevels++; } if (!stream.match(/.*?(?=(#=|=#))/)) { stream.skipToEnd(); } if (stream.match(/^=#/)) { state.nestedLevels--; if (state.nestedLevels == 0) state.tokenize = tokenBase; } return "comment"; } function tokenChar(stream, state) { var isChar = false, match; if (stream.match(chars)) { isChar = true; } else if (match = stream.match(/\\u([a-f0-9]{1,4})(?=')/i)) { var value = parseInt(match[1], 16); if (value <= 55295 || value >= 57344) { // (U+0,U+D7FF), (U+E000,U+FFFF) isChar = true; stream.next(); } } else if (match = stream.match(/\\U([A-Fa-f0-9]{5,8})(?=')/)) { var value = parseInt(match[1], 16); if (value <= 1114111) { // U+10FFFF isChar = true; stream.next(); } } if (isChar) { state.leavingExpr = true; state.tokenize = tokenBase; return "string"; } if (!stream.match(/^[^']+(?=')/)) { stream.skipToEnd(); } if (stream.match(/^'/)) { state.tokenize = tokenBase; } return "error"; } function tokenStringFactory(delimiter) { if (delimiter.substr(-3) === '"""') { delimiter = '"""'; } else if (delimiter.substr(-1) === '"') { delimiter = '"'; } function tokenString(stream, state) { if (stream.eat('\\')) { stream.next(); } else if (stream.match(delimiter)) { state.tokenize = tokenBase; state.leavingExpr = true; return "string"; } else { stream.eat(/[`"]/); } stream.eatWhile(/[^\\`"]/); return "string"; } return tokenString; } var external = { startState: function() { return { tokenize: tokenBase, scopes: [], lastToken: null, leavingExpr: false, isDefinition: false, nestedLevels: 0, charsAdvanced: 0, firstParenPos: -1 }; }, token: function(stream, state) { var style = state.tokenize(stream, state); var current = stream.current(); if (current && style) { state.lastToken = current; } return style; }, indent: function(state, textAfter) { var delta = 0; if ( textAfter === ']' || textAfter === ')' || textAfter === "end" || textAfter === "else" || textAfter === "catch" || textAfter === "elseif" || textAfter === "finally" ) { delta = -1; } return (state.scopes.length + delta) * config.indentUnit; }, electricInput: /\b(end|else|catch|finally)\b/, blockCommentStart: "#=", blockCommentEnd: "=#", lineComment: "#", closeBrackets: "()[]{}\"\"", fold: "indent" }; return external; }); CodeMirror.defineMIME("text/x-julia", "julia"); }); ================================================ FILE: third_party/CodeMirror/mode/livescript/index.html ================================================ CodeMirror: LiveScript mode

LiveScript mode

MIME types defined: text/x-livescript.

The LiveScript mode was written by Kenneth Bentley.

================================================ FILE: third_party/CodeMirror/mode/livescript/livescript.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /** * Link to the project's GitHub page: * https://github.com/duralog/CodeMirror */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('livescript', function(){ var tokenBase = function(stream, state) { var next_rule = state.next || "start"; if (next_rule) { state.next = state.next; var nr = Rules[next_rule]; if (nr.splice) { for (var i$ = 0; i$ < nr.length; ++i$) { var r = nr[i$]; if (r.regex && stream.match(r.regex)) { state.next = r.next || state.next; return r.token; } } stream.next(); return 'error'; } if (stream.match(r = Rules[next_rule])) { if (r.regex && stream.match(r.regex)) { state.next = r.next; return r.token; } else { stream.next(); return 'error'; } } } stream.next(); return 'error'; }; var external = { startState: function(){ return { next: 'start', lastToken: {style: null, indent: 0, content: ""} }; }, token: function(stream, state){ while (stream.pos == stream.start) var style = tokenBase(stream, state); state.lastToken = { style: style, indent: stream.indentation(), content: stream.current() }; return style.replace(/\./g, ' '); }, indent: function(state){ var indentation = state.lastToken.indent; if (state.lastToken.content.match(indenter)) { indentation += 2; } return indentation; } }; return external; }); var identifier = '(?![\\d\\s])[$\\w\\xAA-\\uFFDC](?:(?!\\s)[$\\w\\xAA-\\uFFDC]|-[A-Za-z])*'; 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*$'); var keywordend = '(?![$\\w]|-[A-Za-z]|\\s*:(?![:=]))'; var stringfill = { token: 'string', regex: '.+' }; var Rules = { start: [ { token: 'comment.doc', regex: '/\\*', next: 'comment' }, { token: 'comment', regex: '#.*' }, { token: 'keyword', 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 }, { token: 'constant.language', regex: '(?:true|false|yes|no|on|off|null|void|undefined)' + keywordend }, { token: 'invalid.illegal', regex: '(?:p(?:ackage|r(?:ivate|otected)|ublic)|i(?:mplements|nterface)|enum|static|yield)' + keywordend }, { token: 'language.support.class', regex: '(?:R(?:e(?:gExp|ferenceError)|angeError)|S(?:tring|yntaxError)|E(?:rror|valError)|Array|Boolean|Date|Function|Number|Object|TypeError|URIError)' + keywordend }, { token: 'language.support.function', regex: '(?:is(?:NaN|Finite)|parse(?:Int|Float)|Math|JSON|(?:en|de)codeURI(?:Component)?)' + keywordend }, { token: 'variable.language', regex: '(?:t(?:hat|il|o)|f(?:rom|allthrough)|it|by|e)' + keywordend }, { token: 'identifier', regex: identifier + '\\s*:(?![:=])' }, { token: 'variable', regex: identifier }, { token: 'keyword.operator', regex: '(?:\\.{3}|\\s+\\?)' }, { token: 'keyword.variable', regex: '(?:@+|::|\\.\\.)', next: 'key' }, { token: 'keyword.operator', regex: '\\.\\s*', next: 'key' }, { token: 'string', regex: '\\\\\\S[^\\s,;)}\\]]*' }, { token: 'string.doc', regex: '\'\'\'', next: 'qdoc' }, { token: 'string.doc', regex: '"""', next: 'qqdoc' }, { token: 'string', regex: '\'', next: 'qstring' }, { token: 'string', regex: '"', next: 'qqstring' }, { token: 'string', regex: '`', next: 'js' }, { token: 'string', regex: '<\\[', next: 'words' }, { token: 'string.regex', regex: '//', next: 'heregex' }, { token: 'string.regex', regex: '\\/(?:[^[\\/\\n\\\\]*(?:(?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[\\/\\n\\\\]*)*)\\/[gimy$]{0,4}', next: 'key' }, { token: 'constant.numeric', 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$]*)' }, { token: 'lparen', regex: '[({[]' }, { token: 'rparen', regex: '[)}\\]]', next: 'key' }, { token: 'keyword.operator', regex: '\\S+' }, { token: 'text', regex: '\\s+' } ], heregex: [ { token: 'string.regex', regex: '.*?//[gimy$?]{0,4}', next: 'start' }, { token: 'string.regex', regex: '\\s*#{' }, { token: 'comment.regex', regex: '\\s+(?:#.*)?' }, { token: 'string.regex', regex: '\\S+' } ], key: [ { token: 'keyword.operator', regex: '[.?@!]+' }, { token: 'identifier', regex: identifier, next: 'start' }, { token: 'text', regex: '', next: 'start' } ], comment: [ { token: 'comment.doc', regex: '.*?\\*/', next: 'start' }, { token: 'comment.doc', regex: '.+' } ], qdoc: [ { token: 'string', regex: ".*?'''", next: 'key' }, stringfill ], qqdoc: [ { token: 'string', regex: '.*?"""', next: 'key' }, stringfill ], qstring: [ { token: 'string', regex: '[^\\\\\']*(?:\\\\.[^\\\\\']*)*\'', next: 'key' }, stringfill ], qqstring: [ { token: 'string', regex: '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"', next: 'key' }, stringfill ], js: [ { token: 'string', regex: '[^\\\\`]*(?:\\\\.[^\\\\`]*)*`', next: 'key' }, stringfill ], words: [ { token: 'string', regex: '.*?\\]>', next: 'key' }, stringfill ] }; for (var idx in Rules) { var r = Rules[idx]; if (r.splice) { for (var i = 0, len = r.length; i < len; ++i) { var rr = r[i]; if (typeof rr.regex === 'string') { Rules[idx][i].regex = new RegExp('^' + rr.regex); } } } else if (typeof rr.regex === 'string') { Rules[idx].regex = new RegExp('^' + r.regex); } } CodeMirror.defineMIME('text/x-livescript', 'livescript'); }); ================================================ FILE: third_party/CodeMirror/mode/lua/index.html ================================================ CodeMirror: Lua mode

Lua mode

Loosely based on Franciszek Wawrzak's CodeMirror 1 mode. One configuration parameter is supported, specials, to which you can provide an array of strings to have those identifiers highlighted with the lua-special style.

MIME types defined: text/x-lua.

================================================ FILE: third_party/CodeMirror/mode/lua/lua.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's // CodeMirror 1 mode. // highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("lua", function(config, parserConfig) { var indentUnit = config.indentUnit; function prefixRE(words) { return new RegExp("^(?:" + words.join("|") + ")", "i"); } function wordRE(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var specials = wordRE(parserConfig.specials || []); // long list of standard functions from lua manual var builtins = wordRE([ "_G","_VERSION","assert","collectgarbage","dofile","error","getfenv","getmetatable","ipairs","load", "loadfile","loadstring","module","next","pairs","pcall","print","rawequal","rawget","rawset","require", "select","setfenv","setmetatable","tonumber","tostring","type","unpack","xpcall", "coroutine.create","coroutine.resume","coroutine.running","coroutine.status","coroutine.wrap","coroutine.yield", "debug.debug","debug.getfenv","debug.gethook","debug.getinfo","debug.getlocal","debug.getmetatable", "debug.getregistry","debug.getupvalue","debug.setfenv","debug.sethook","debug.setlocal","debug.setmetatable", "debug.setupvalue","debug.traceback", "close","flush","lines","read","seek","setvbuf","write", "io.close","io.flush","io.input","io.lines","io.open","io.output","io.popen","io.read","io.stderr","io.stdin", "io.stdout","io.tmpfile","io.type","io.write", "math.abs","math.acos","math.asin","math.atan","math.atan2","math.ceil","math.cos","math.cosh","math.deg", "math.exp","math.floor","math.fmod","math.frexp","math.huge","math.ldexp","math.log","math.log10","math.max", "math.min","math.modf","math.pi","math.pow","math.rad","math.random","math.randomseed","math.sin","math.sinh", "math.sqrt","math.tan","math.tanh", "os.clock","os.date","os.difftime","os.execute","os.exit","os.getenv","os.remove","os.rename","os.setlocale", "os.time","os.tmpname", "package.cpath","package.loaded","package.loaders","package.loadlib","package.path","package.preload", "package.seeall", "string.byte","string.char","string.dump","string.find","string.format","string.gmatch","string.gsub", "string.len","string.lower","string.match","string.rep","string.reverse","string.sub","string.upper", "table.concat","table.insert","table.maxn","table.remove","table.sort" ]); var keywords = wordRE(["and","break","elseif","false","nil","not","or","return", "true","function", "end", "if", "then", "else", "do", "while", "repeat", "until", "for", "in", "local" ]); var indentTokens = wordRE(["function", "if","repeat","do", "\\(", "{"]); var dedentTokens = wordRE(["end", "until", "\\)", "}"]); var dedentPartial = prefixRE(["end", "until", "\\)", "}", "else", "elseif"]); function readBracket(stream) { var level = 0; while (stream.eat("=")) ++level; stream.eat("["); return level; } function normal(stream, state) { var ch = stream.next(); if (ch == "-" && stream.eat("-")) { if (stream.eat("[") && stream.eat("[")) return (state.cur = bracketed(readBracket(stream), "comment"))(stream, state); stream.skipToEnd(); return "comment"; } if (ch == "\"" || ch == "'") return (state.cur = string(ch))(stream, state); if (ch == "[" && /[\[=]/.test(stream.peek())) return (state.cur = bracketed(readBracket(stream), "string"))(stream, state); if (/\d/.test(ch)) { stream.eatWhile(/[\w.%]/); return "number"; } if (/[\w_]/.test(ch)) { stream.eatWhile(/[\w\\\-_.]/); return "variable"; } return null; } function bracketed(level, style) { return function(stream, state) { var curlev = null, ch; while ((ch = stream.next()) != null) { if (curlev == null) {if (ch == "]") curlev = 0;} else if (ch == "=") ++curlev; else if (ch == "]" && curlev == level) { state.cur = normal; break; } else curlev = null; } return style; }; } function string(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) state.cur = normal; return "string"; }; } return { startState: function(basecol) { return {basecol: basecol || 0, indentDepth: 0, cur: normal}; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = state.cur(stream, state); var word = stream.current(); if (style == "variable") { if (keywords.test(word)) style = "keyword"; else if (builtins.test(word)) style = "builtin"; else if (specials.test(word)) style = "variable-2"; } if ((style != "comment") && (style != "string")){ if (indentTokens.test(word)) ++state.indentDepth; else if (dedentTokens.test(word)) --state.indentDepth; } return style; }, indent: function(state, textAfter) { var closing = dedentPartial.test(textAfter); return state.basecol + indentUnit * (state.indentDepth - (closing ? 1 : 0)); }, lineComment: "--", blockCommentStart: "--[[", blockCommentEnd: "]]" }; }); CodeMirror.defineMIME("text/x-lua", "lua"); }); ================================================ FILE: third_party/CodeMirror/mode/markdown/index.html ================================================ CodeMirror: Markdown mode

Markdown mode

If you also want support strikethrough, emoji and few other goodies, check out Github-Flavored Markdown mode.

Optionally depends on other modes for properly highlighted code blocks, and XML mode for properly highlighted inline XML blocks.

Markdown mode supports these options:

  • highlightFormatting: boolean
    Whether to separately highlight markdown meta characterts (*[]()etc.) (default: false).
  • maxBlockquoteDepth: boolean
    Maximum allowed blockquote nesting (default: 0 - infinite nesting).
  • xml: boolean
    Whether to highlight inline XML (default: true).
  • fencedCodeBlockHighlighting: boolean
    Whether to syntax-highlight fenced code blocks, if given mode is included (default: true).
  • tokenTypeOverrides: Object
    When you want ot override default token type names (e.g. {code: "code"}).
  • allowAtxHeaderWithoutSpace: boolean
    Allow lazy headers without whitespace between hashtag and text (default: false).

MIME types defined: text/x-markdown.

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/markdown/markdown.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../meta"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { var htmlMode = CodeMirror.getMode(cmCfg, "text/html"); var htmlModeMissing = htmlMode.name == "null" function getMode(name) { if (CodeMirror.findModeByName) { var found = CodeMirror.findModeByName(name); if (found) name = found.mime || found.mimes[0]; } var mode = CodeMirror.getMode(cmCfg, name); return mode.name == "null" ? null : mode; } // Should characters that affect highlighting be highlighted separate? // Does not include characters that will be output (such as `1.` and `-` for lists) if (modeCfg.highlightFormatting === undefined) modeCfg.highlightFormatting = false; // Maximum number of nested blockquotes. Set to 0 for infinite nesting. // Excess `>` will emit `error` token. if (modeCfg.maxBlockquoteDepth === undefined) modeCfg.maxBlockquoteDepth = 0; // Turn on task lists? ("- [ ] " and "- [x] ") if (modeCfg.taskLists === undefined) modeCfg.taskLists = false; // Turn on strikethrough syntax if (modeCfg.strikethrough === undefined) modeCfg.strikethrough = false; if (modeCfg.emoji === undefined) modeCfg.emoji = false; if (modeCfg.fencedCodeBlockHighlighting === undefined) modeCfg.fencedCodeBlockHighlighting = true; if (modeCfg.xml === undefined) modeCfg.xml = true; // Allow token types to be overridden by user-provided token types. if (modeCfg.tokenTypeOverrides === undefined) modeCfg.tokenTypeOverrides = {}; var tokenTypes = { header: "header", code: "comment", quote: "quote", list1: "variable-2", list2: "variable-3", list3: "keyword", hr: "hr", image: "image", imageAltText: "image-alt-text", imageMarker: "image-marker", formatting: "formatting", linkInline: "link", linkEmail: "link", linkText: "link", linkHref: "string", em: "em", strong: "strong", strikethrough: "strikethrough", emoji: "builtin" }; for (var tokenType in tokenTypes) { if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) { tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType]; } } var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/ , listRE = /^(?:[*\-+]|^[0-9]+([.)]))\s+/ , taskListRE = /^\[(x| )\](?=\s)/i // Must follow listRE , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/ , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/ , textRE = /^[^#!\[\]*_\\<>` "'(~:]+/ , fencedCodeRE = /^(~~~+|```+)[ \t]*([\w+#-]*)[^\n`]*$/ , linkDefRE = /^\s*\[[^\]]+?\]:.*$/ // naive link-definition , 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]/ , expandedTab = " " // CommonMark specifies tab as 4 spaces function switchInline(stream, state, f) { state.f = state.inline = f; return f(stream, state); } function switchBlock(stream, state, f) { state.f = state.block = f; return f(stream, state); } function lineIsEmpty(line) { return !line || !/\S/.test(line.string) } // Blocks function blankLine(state) { // Reset linkTitle state state.linkTitle = false; state.linkHref = false; state.linkText = false; // Reset EM state state.em = false; // Reset STRONG state state.strong = false; // Reset strikethrough state state.strikethrough = false; // Reset state.quote state.quote = 0; // Reset state.indentedCode state.indentedCode = false; if (state.f == htmlBlock) { var exit = htmlModeMissing if (!exit) { var inner = CodeMirror.innerMode(htmlMode, state.htmlState) exit = inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText) } if (exit) { state.f = inlineNormal; state.block = blockNormal; state.htmlState = null; } } // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; // Mark this line as blank state.prevLine = state.thisLine state.thisLine = {stream: null} return null; } function blockNormal(stream, state) { var firstTokenOnLine = stream.column() === state.indentation; var prevLineLineIsEmpty = lineIsEmpty(state.prevLine.stream); var prevLineIsIndentedCode = state.indentedCode; var prevLineIsHr = state.prevLine.hr; var prevLineIsList = state.list !== false; var maxNonCodeIndentation = (state.listStack[state.listStack.length - 1] || 0) + 3; state.indentedCode = false; var lineIndentation = state.indentation; // compute once per line (on first token) if (state.indentationDiff === null) { state.indentationDiff = state.indentation; if (prevLineIsList) { // Reset inline styles which shouldn't propagate aross list items state.em = false; state.strong = false; state.code = false; state.strikethrough = false; state.list = null; // While this list item's marker's indentation is less than the deepest // list item's content's indentation,pop the deepest list item // indentation off the stack, and update block indentation state while (lineIndentation < state.listStack[state.listStack.length - 1]) { state.listStack.pop(); if (state.listStack.length) { state.indentation = state.listStack[state.listStack.length - 1]; // less than the first list's indent -> the line is no longer a list } else { state.list = false; } } if (state.list !== false) { state.indentationDiff = lineIndentation - state.listStack[state.listStack.length - 1] } } } // not comprehensive (currently only for setext detection purposes) var allowsInlineContinuation = ( !prevLineLineIsEmpty && !prevLineIsHr && !state.prevLine.header && (!prevLineIsList || !prevLineIsIndentedCode) && !state.prevLine.fencedCodeEnd ); var isHr = (state.list === false || prevLineIsHr || prevLineLineIsEmpty) && state.indentation <= maxNonCodeIndentation && stream.match(hrRE); var match = null; if (state.indentationDiff >= 4 && (prevLineIsIndentedCode || state.prevLine.fencedCodeEnd || state.prevLine.header || prevLineLineIsEmpty)) { stream.skipToEnd(); state.indentedCode = true; return tokenTypes.code; } else if (stream.eatSpace()) { return null; } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(atxHeaderRE)) && match[1].length <= 6) { state.quote = 0; state.header = match[1].length; state.thisLine.header = true; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (state.indentation <= maxNonCodeIndentation && stream.eat('>')) { state.quote = firstTokenOnLine ? 1 : state.quote + 1; if (modeCfg.highlightFormatting) state.formatting = "quote"; stream.eatSpace(); return getType(state); } else if (!isHr && !state.setext && firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(listRE))) { var listType = match[1] ? "ol" : "ul"; state.indentation = lineIndentation + stream.current().length; state.list = true; state.quote = 0; // Add this list item's content's indentation to the stack state.listStack.push(state.indentation); if (modeCfg.taskLists && stream.match(taskListRE, false)) { state.taskList = true; } state.f = state.inline; if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType]; return getType(state); } else if (firstTokenOnLine && state.indentation <= maxNonCodeIndentation && (match = stream.match(fencedCodeRE, true))) { state.quote = 0; state.fencedEndRE = new RegExp(match[1] + "+ *$"); // try switching mode state.localMode = modeCfg.fencedCodeBlockHighlighting && getMode(match[2]); if (state.localMode) state.localState = CodeMirror.startState(state.localMode); state.f = state.block = local; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = -1 return getType(state); // SETEXT has lowest block-scope precedence after HR, so check it after // the others (code, blockquote, list...) } else if ( // if setext set, indicates line after ---/=== state.setext || ( // line before ---/=== (!allowsInlineContinuation || !prevLineIsList) && !state.quote && state.list === false && !state.code && !isHr && !linkDefRE.test(stream.string) && (match = stream.lookAhead(1)) && (match = match.match(setextHeaderRE)) ) ) { if ( !state.setext ) { state.header = match[0].charAt(0) == '=' ? 1 : 2; state.setext = state.header; } else { state.header = state.setext; // has no effect on type so we can reset it now state.setext = 0; stream.skipToEnd(); if (modeCfg.highlightFormatting) state.formatting = "header"; } state.thisLine.header = true; state.f = state.inline; return getType(state); } else if (isHr) { stream.skipToEnd(); state.hr = true; state.thisLine.hr = true; return tokenTypes.hr; } else if (stream.peek() === '[') { return switchInline(stream, state, footnoteLink); } return switchInline(stream, state, state.inline); } function htmlBlock(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (!htmlModeMissing) { var inner = CodeMirror.innerMode(htmlMode, state.htmlState) if ((inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText)) || (state.md_inside && stream.current().indexOf(">") > -1)) { state.f = inlineNormal; state.block = blockNormal; state.htmlState = null; } } return style; } function local(stream, state) { var currListInd = state.listStack[state.listStack.length - 1] || 0; var hasExitedList = state.indentation < currListInd; var maxFencedEndInd = currListInd + 3; if (state.fencedEndRE && state.indentation <= maxFencedEndInd && (hasExitedList || stream.match(state.fencedEndRE))) { if (modeCfg.highlightFormatting) state.formatting = "code-block"; var returnType; if (!hasExitedList) returnType = getType(state) state.localMode = state.localState = null; state.block = blockNormal; state.f = inlineNormal; state.fencedEndRE = null; state.code = 0 state.thisLine.fencedCodeEnd = true; if (hasExitedList) return switchBlock(stream, state, state.block); return returnType; } else if (state.localMode) { return state.localMode.token(stream, state.localState); } else { stream.skipToEnd(); return tokenTypes.code; } } // Inline function getType(state) { var styles = []; if (state.formatting) { styles.push(tokenTypes.formatting); if (typeof state.formatting === "string") state.formatting = [state.formatting]; for (var i = 0; i < state.formatting.length; i++) { styles.push(tokenTypes.formatting + "-" + state.formatting[i]); if (state.formatting[i] === "header") { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header); } // Add `formatting-quote` and `formatting-quote-#` for blockquotes // Add `error` instead if the maximum blockquote nesting depth is passed if (state.formatting[i] === "quote") { if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote); } else { styles.push("error"); } } } } if (state.taskOpen) { styles.push("meta"); return styles.length ? styles.join(' ') : null; } if (state.taskClosed) { styles.push("property"); return styles.length ? styles.join(' ') : null; } if (state.linkHref) { styles.push(tokenTypes.linkHref, "url"); } else { // Only apply inline styles to non-url text if (state.strong) { styles.push(tokenTypes.strong); } if (state.em) { styles.push(tokenTypes.em); } if (state.strikethrough) { styles.push(tokenTypes.strikethrough); } if (state.emoji) { styles.push(tokenTypes.emoji); } if (state.linkText) { styles.push(tokenTypes.linkText); } if (state.code) { styles.push(tokenTypes.code); } if (state.image) { styles.push(tokenTypes.image); } if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); } if (state.imageMarker) { styles.push(tokenTypes.imageMarker); } } if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); } if (state.quote) { styles.push(tokenTypes.quote); // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.quote + "-" + state.quote); } else { styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth); } } if (state.list !== false) { var listMod = (state.listStack.length - 1) % 3; if (!listMod) { styles.push(tokenTypes.list1); } else if (listMod === 1) { styles.push(tokenTypes.list2); } else { styles.push(tokenTypes.list3); } } if (state.trailingSpaceNewLine) { styles.push("trailing-space-new-line"); } else if (state.trailingSpace) { styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); } return styles.length ? styles.join(' ') : null; } function handleText(stream, state) { if (stream.match(textRE, true)) { return getType(state); } return undefined; } function inlineNormal(stream, state) { var style = state.text(stream, state); if (typeof style !== 'undefined') return style; if (state.list) { // List marker (*, +, -, 1., etc) state.list = null; return getType(state); } if (state.taskList) { var taskOpen = stream.match(taskListRE, true)[1] === " "; if (taskOpen) state.taskOpen = true; else state.taskClosed = true; if (modeCfg.highlightFormatting) state.formatting = "task"; state.taskList = false; return getType(state); } state.taskOpen = false; state.taskClosed = false; if (state.header && stream.match(/^#+$/, true)) { if (modeCfg.highlightFormatting) state.formatting = "header"; return getType(state); } var ch = stream.next(); // Matches link titles present on next line if (state.linkTitle) { state.linkTitle = false; var matchCh = ch; if (ch === '(') { matchCh = ')'; } matchCh = (matchCh+'').replace(/([.?*+^\[\]\\(){}|-])/g, "\\$1"); var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh; if (stream.match(new RegExp(regex), true)) { return tokenTypes.linkHref; } } // If this block is changed, it may need to be updated in GFM mode if (ch === '`') { var previousFormatting = state.formatting; if (modeCfg.highlightFormatting) state.formatting = "code"; stream.eatWhile('`'); var count = stream.current().length if (state.code == 0 && (!state.quote || count == 1)) { state.code = count return getType(state) } else if (count == state.code) { // Must be exact var t = getType(state) state.code = 0 return t } else { state.formatting = previousFormatting return getType(state) } } else if (state.code) { return getType(state); } if (ch === '\\') { stream.next(); if (modeCfg.highlightFormatting) { var type = getType(state); var formattingEscape = tokenTypes.formatting + "-escape"; return type ? type + " " + formattingEscape : formattingEscape; } } if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { state.imageMarker = true; state.image = true; if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === '[' && state.imageMarker && stream.match(/[^\]]*\](\(.*?\)| ?\[.*?\])/, false)) { state.imageMarker = false; state.imageAltText = true if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === ']' && state.imageAltText) { if (modeCfg.highlightFormatting) state.formatting = "image"; var type = getType(state); state.imageAltText = false; state.image = false; state.inline = state.f = linkHref; return type; } if (ch === '[' && !state.image) { if (state.linkText && stream.match(/^.*?\]/)) return getType(state) state.linkText = true; if (modeCfg.highlightFormatting) state.formatting = "link"; return getType(state); } if (ch === ']' && state.linkText) { if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); state.linkText = false; state.inline = state.f = stream.match(/\(.*?\)| ?\[.*?\]/, false) ? linkHref : inlineNormal return type; } if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkEmail; } if (modeCfg.xml && ch === '<' && stream.match(/^(!--|\?|!\[CDATA\[|[a-z][a-z0-9-]*(?:\s+[a-z_:.\-]+(?:\s*=\s*[^>]+)?)*\s*(?:>|$))/i, false)) { var end = stream.string.indexOf(">", stream.pos); if (end != -1) { var atts = stream.string.substring(stream.start, end); if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true; } stream.backUp(1); state.htmlState = CodeMirror.startState(htmlMode); return switchBlock(stream, state, htmlBlock); } if (modeCfg.xml && ch === '<' && stream.match(/^\/\w*?>/)) { state.md_inside = false; return "tag"; } else if (ch === "*" || ch === "_") { var len = 1, before = stream.pos == 1 ? " " : stream.string.charAt(stream.pos - 2) while (len < 3 && stream.eat(ch)) len++ var after = stream.peek() || " " // See http://spec.commonmark.org/0.27/#emphasis-and-strong-emphasis var leftFlanking = !/\s/.test(after) && (!punctuation.test(after) || /\s/.test(before) || punctuation.test(before)) var rightFlanking = !/\s/.test(before) && (!punctuation.test(before) || /\s/.test(after) || punctuation.test(after)) var setEm = null, setStrong = null if (len % 2) { // Em if (!state.em && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before))) setEm = true else if (state.em == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after))) setEm = false } if (len > 1) { // Strong if (!state.strong && leftFlanking && (ch === "*" || !rightFlanking || punctuation.test(before))) setStrong = true else if (state.strong == ch && rightFlanking && (ch === "*" || !leftFlanking || punctuation.test(after))) setStrong = false } if (setStrong != null || setEm != null) { if (modeCfg.highlightFormatting) state.formatting = setEm == null ? "strong" : setStrong == null ? "em" : "strong em" if (setEm === true) state.em = ch if (setStrong === true) state.strong = ch var t = getType(state) if (setEm === false) state.em = false if (setStrong === false) state.strong = false return t } } else if (ch === ' ') { if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(1); } } } if (modeCfg.strikethrough) { if (ch === '~' && stream.eatWhile(ch)) { if (state.strikethrough) {// Remove strikethrough if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; var t = getType(state); state.strikethrough = false; return t; } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough state.strikethrough = true; if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; return getType(state); } } else if (ch === ' ') { if (stream.match(/^~~/, true)) { // Probably surrounded by space if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(2); } } } } if (modeCfg.emoji && ch === ":" && stream.match(/^(?:[a-z_\d+][a-z_\d+-]*|\-[a-z_\d+][a-z_\d+-]*):/)) { state.emoji = true; if (modeCfg.highlightFormatting) state.formatting = "emoji"; var retType = getType(state); state.emoji = false; return retType; } if (ch === ' ') { if (stream.match(/^ +$/, false)) { state.trailingSpace++; } else if (state.trailingSpace) { state.trailingSpaceNewLine = true; } } return getType(state); } function linkInline(stream, state) { var ch = stream.next(); if (ch === ">") { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } stream.match(/^[^>]+/, true); return tokenTypes.linkInline; } function linkHref(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } var ch = stream.next(); if (ch === '(' || ch === '[') { state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]"); if (modeCfg.highlightFormatting) state.formatting = "link-string"; state.linkHref = true; return getType(state); } return 'error'; } var linkRE = { ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/, "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\]]|\\.)*\])*?(?=\])/ } function getLinkHrefInside(endChar) { return function(stream, state) { var ch = stream.next(); if (ch === endChar) { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link-string"; var returnState = getType(state); state.linkHref = false; return returnState; } stream.match(linkRE[endChar]) state.linkHref = true; return getType(state); }; } function footnoteLink(stream, state) { if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) { state.f = footnoteLinkInside; stream.next(); // Consume [ if (modeCfg.highlightFormatting) state.formatting = "link"; state.linkText = true; return getType(state); } return switchInline(stream, state, inlineNormal); } function footnoteLinkInside(stream, state) { if (stream.match(/^\]:/, true)) { state.f = state.inline = footnoteUrl; if (modeCfg.highlightFormatting) state.formatting = "link"; var returnType = getType(state); state.linkText = false; return returnType; } stream.match(/^([^\]\\]|\\.)+/, true); return tokenTypes.linkText; } function footnoteUrl(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } // Match URL stream.match(/^[^\s]+/, true); // Check for link title if (stream.peek() === undefined) { // End of line, set flag to check next line state.linkTitle = true; } else { // More content on line, check if link title stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true); } state.f = state.inline = inlineNormal; return tokenTypes.linkHref + " url"; } var mode = { startState: function() { return { f: blockNormal, prevLine: {stream: null}, thisLine: {stream: null}, block: blockNormal, htmlState: null, indentation: 0, inline: inlineNormal, text: handleText, formatting: false, linkText: false, linkHref: false, linkTitle: false, code: 0, em: false, strong: false, header: 0, setext: 0, hr: false, taskList: false, list: false, listStack: [], quote: 0, trailingSpace: 0, trailingSpaceNewLine: false, strikethrough: false, emoji: false, fencedEndRE: null }; }, copyState: function(s) { return { f: s.f, prevLine: s.prevLine, thisLine: s.thisLine, block: s.block, htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState), indentation: s.indentation, localMode: s.localMode, localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, inline: s.inline, text: s.text, formatting: false, linkText: s.linkText, linkTitle: s.linkTitle, linkHref: s.linkHref, code: s.code, em: s.em, strong: s.strong, strikethrough: s.strikethrough, emoji: s.emoji, header: s.header, setext: s.setext, hr: s.hr, taskList: s.taskList, list: s.list, listStack: s.listStack.slice(0), quote: s.quote, indentedCode: s.indentedCode, trailingSpace: s.trailingSpace, trailingSpaceNewLine: s.trailingSpaceNewLine, md_inside: s.md_inside, fencedEndRE: s.fencedEndRE }; }, token: function(stream, state) { // Reset state.formatting state.formatting = false; if (stream != state.thisLine.stream) { state.header = 0; state.hr = false; if (stream.match(/^\s*$/, true)) { blankLine(state); return null; } state.prevLine = state.thisLine state.thisLine = {stream: stream} // Reset state.taskList state.taskList = false; // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; if (!state.localState) { state.f = state.block; if (state.f != htmlBlock) { var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, expandedTab).length; state.indentation = indentation; state.indentationDiff = null; if (indentation > 0) return null; } } } return state.f(stream, state); }, innerMode: function(state) { if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode}; if (state.localState) return {state: state.localState, mode: state.localMode}; return {state: state, mode: mode}; }, indent: function(state, textAfter, line) { if (state.block == htmlBlock && htmlMode.indent) return htmlMode.indent(state.htmlState, textAfter, line) if (state.localState && state.localMode.indent) return state.localMode.indent(state.localState, textAfter, line) return CodeMirror.Pass }, blankLine: blankLine, getType: getType, blockCommentStart: "", closeBrackets: "()[]{}''\"\"``", fold: "markdown" }; return mode; }, "xml"); CodeMirror.defineMIME("text/markdown", "markdown"); CodeMirror.defineMIME("text/x-markdown", "markdown"); }); ================================================ FILE: third_party/CodeMirror/mode/markdown/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var config = {tabSize: 4, indentUnit: 2} var mode = CodeMirror.getMode(config, "markdown"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } var modeHighlightFormatting = CodeMirror.getMode(config, {name: "markdown", highlightFormatting: true}); function FT(name) { test.mode(name, modeHighlightFormatting, Array.prototype.slice.call(arguments, 1)); } var modeMT_noXml = CodeMirror.getMode(config, {name: "markdown", xml: false}); function MT_noXml(name) { test.mode(name, modeMT_noXml, Array.prototype.slice.call(arguments, 1)); } var modeMT_noFencedHighlight = CodeMirror.getMode(config, {name: "markdown", fencedCodeBlockHighlighting: false}); function MT_noFencedHighlight(name) { test.mode(name, modeMT_noFencedHighlight, Array.prototype.slice.call(arguments, 1)); } var modeAtxNoSpace = CodeMirror.getMode(config, {name: "markdown", allowAtxHeaderWithoutSpace: true}); function AtxNoSpaceTest(name) { test.mode(name, modeAtxNoSpace, Array.prototype.slice.call(arguments, 1)); } var modeOverrideClasses = CodeMirror.getMode(config, { name: "markdown", strikethrough: true, emoji: true, tokenTypeOverrides: { "header" : "override-header", "code" : "override-code", "quote" : "override-quote", "list1" : "override-list1", "list2" : "override-list2", "list3" : "override-list3", "hr" : "override-hr", "image" : "override-image", "imageAltText": "override-image-alt-text", "imageMarker": "override-image-marker", "linkInline" : "override-link-inline", "linkEmail" : "override-link-email", "linkText" : "override-link-text", "linkHref" : "override-link-href", "em" : "override-em", "strong" : "override-strong", "strikethrough" : "override-strikethrough", "emoji" : "override-emoji" }}); function TokenTypeOverrideTest(name) { test.mode(name, modeOverrideClasses, Array.prototype.slice.call(arguments, 1)); } var modeFormattingOverride = CodeMirror.getMode(config, { name: "markdown", highlightFormatting: true, tokenTypeOverrides: { "formatting" : "override-formatting" }}); function FormatTokenTypeOverrideTest(name) { test.mode(name, modeFormattingOverride, Array.prototype.slice.call(arguments, 1)); } var modeET = CodeMirror.getMode(config, {name: "markdown", emoji: true}); function ET(name) { test.mode(name, modeET, Array.prototype.slice.call(arguments, 1)); } FT("formatting_emAsterisk", "[em&formatting&formatting-em *][em foo][em&formatting&formatting-em *]"); FT("formatting_emUnderscore", "[em&formatting&formatting-em _][em foo][em&formatting&formatting-em _]"); FT("formatting_strongAsterisk", "[strong&formatting&formatting-strong **][strong foo][strong&formatting&formatting-strong **]"); FT("formatting_strongUnderscore", "[strong&formatting&formatting-strong __][strong foo][strong&formatting&formatting-strong __]"); FT("formatting_codeBackticks", "[comment&formatting&formatting-code `][comment foo][comment&formatting&formatting-code `]"); FT("formatting_doubleBackticks", "[comment&formatting&formatting-code ``][comment foo ` bar][comment&formatting&formatting-code ``]"); FT("formatting_atxHeader", "[header&header-1&formatting&formatting-header&formatting-header-1 # ][header&header-1 foo # bar ][header&header-1&formatting&formatting-header&formatting-header-1 #]"); FT("formatting_setextHeader", "[header&header-1 foo]", "[header&header-1&formatting&formatting-header&formatting-header-1 =]"); FT("formatting_blockquote", "[quote"e-1&formatting&formatting-quote&formatting-quote-1 > ][quote"e-1 foo]"); FT("formatting_list", "[variable-2&formatting&formatting-list&formatting-list-ul - ][variable-2 foo]"); FT("formatting_list", "[variable-2&formatting&formatting-list&formatting-list-ol 1. ][variable-2 foo]"); FT("formatting_link", "[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 )]"); FT("formatting_linkReference", "[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 ]]]", "[link&formatting&formatting-link [][link bar][link&formatting&formatting-link ]]:] [string&url http://example.com/]"); FT("formatting_linkWeb", "[link&formatting&formatting-link <][link http://example.com/][link&formatting&formatting-link >]"); FT("formatting_linkEmail", "[link&formatting&formatting-link <][link user@example.com][link&formatting&formatting-link >]"); FT("formatting_escape", "[formatting-escape \\*]"); FT("formatting_image", "[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 )]"); FT("codeBlock", "[comment&formatting&formatting-code-block ```css]", "[tag foo]", "[comment&formatting&formatting-code-block ```]"); MT("plainText", "foo"); // Don't style single trailing space MT("trailingSpace1", "foo "); // Two or more trailing spaces should be styled with line break character MT("trailingSpace2", "foo[trailing-space-a ][trailing-space-new-line ]"); MT("trailingSpace3", "foo[trailing-space-a ][trailing-space-b ][trailing-space-new-line ]"); MT("trailingSpace4", "foo[trailing-space-a ][trailing-space-b ][trailing-space-a ][trailing-space-new-line ]"); // Code blocks using 4 spaces (regardless of CodeMirror.tabSize value) MT("codeBlocksUsing4Spaces", " [comment foo]"); // Code blocks using 4 spaces with internal indentation MT("codeBlocksUsing4SpacesIndentation", " [comment bar]", " [comment hello]", " [comment world]", " [comment foo]", "bar"); // Code blocks should end even after extra indented lines MT("codeBlocksWithTrailingIndentedLine", " [comment foo]", " [comment bar]", " [comment baz]", " ", "hello"); // Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value) MT("codeBlocksUsing1Tab", "\t[comment foo]"); // No code blocks directly after paragraph // http://spec.commonmark.org/0.19/#example-65 MT("noCodeBlocksAfterParagraph", "Foo", " Bar"); MT("codeBlocksAfterATX", "[header&header-1 # foo]", " [comment code]"); MT("codeBlocksAfterSetext", "[header&header-2 foo]", "[header&header-2 ---]", " [comment code]"); MT("codeBlocksAfterFencedCode", "[comment ```]", "[comment foo]", "[comment ```]", " [comment code]"); // Inline code using backticks MT("inlineCodeUsingBackticks", "foo [comment `bar`]"); // Block code using single backtick (shouldn't work) MT("blockCodeSingleBacktick", "[comment `]", "[comment foo]", "[comment `]"); // Unclosed backticks // Instead of simply marking as CODE, it would be nice to have an // incomplete flag for CODE, that is styled slightly different. MT("unclosedBackticks", "foo [comment `bar]"); // Per documentation: "To include a literal backtick character within a // code span, you can use multiple backticks as the opening and closing // delimiters" MT("doubleBackticks", "[comment ``foo ` bar``]"); // Tests based on Dingus // http://daringfireball.net/projects/markdown/dingus // // Multiple backticks within an inline code block MT("consecutiveBackticks", "[comment `foo```bar`]"); // Multiple backticks within an inline code block with a second code block MT("consecutiveBackticks", "[comment `foo```bar`] hello [comment `world`]"); // Unclosed with several different groups of backticks MT("unclosedBackticks", "[comment ``foo ``` bar` hello]"); // Closed with several different groups of backticks MT("closedBackticks", "[comment ``foo ``` bar` hello``] world"); // info string cannot contain backtick, thus should result in inline code MT("closingFencedMarksOnSameLine", "[comment ``` code ```] foo"); // atx headers // http://daringfireball.net/projects/markdown/syntax#header MT("atxH1", "[header&header-1 # foo]"); MT("atxH2", "[header&header-2 ## foo]"); MT("atxH3", "[header&header-3 ### foo]"); MT("atxH4", "[header&header-4 #### foo]"); MT("atxH5", "[header&header-5 ##### foo]"); MT("atxH6", "[header&header-6 ###### foo]"); // http://spec.commonmark.org/0.19/#example-24 MT("noAtxH7", "####### foo"); // http://spec.commonmark.org/0.19/#example-25 MT("noAtxH1WithoutSpace", "#5 bolt"); // CommonMark requires a space after # but most parsers don't AtxNoSpaceTest("atxNoSpaceAllowed_H1NoSpace", "[header&header-1 #foo]"); AtxNoSpaceTest("atxNoSpaceAllowed_H4NoSpace", "[header&header-4 ####foo]"); AtxNoSpaceTest("atxNoSpaceAllowed_H1Space", "[header&header-1 # foo]"); // Inline styles should be parsed inside headers MT("atxH1inline", "[header&header-1 # foo ][header&header-1&em *bar*]"); MT("atxIndentedTooMuch", "[header&header-1 # foo]", " [comment # bar]"); // disable atx inside blockquote until we implement proper blockquote inner mode // TODO: fix to be CommonMark-compliant MT("atxNestedInsideBlockquote", "[quote"e-1 > # foo]"); MT("atxAfterBlockquote", "[quote"e-1 > foo]", "[header&header-1 # bar]"); // Setext headers - H1, H2 // Per documentation, "Any number of underlining =’s or -’s will work." // http://daringfireball.net/projects/markdown/syntax#header // Ideally, the text would be marked as `header` as well, but this is // not really feasible at the moment. So, instead, we're testing against // what works today, to avoid any regressions. // // Check if single underlining = works MT("setextH1", "[header&header-1 foo]", "[header&header-1 =]"); // Check if 3+ ='s work MT("setextH1", "[header&header-1 foo]", "[header&header-1 ===]"); // Check if single underlining - works MT("setextH2", "[header&header-2 foo]", "[header&header-2 -]"); // Check if 3+ -'s work MT("setextH2", "[header&header-2 foo]", "[header&header-2 ---]"); // http://spec.commonmark.org/0.19/#example-45 MT("setextH2AllowSpaces", "[header&header-2 foo]", " [header&header-2 ---- ]"); // http://spec.commonmark.org/0.19/#example-44 MT("noSetextAfterIndentedCodeBlock", " [comment foo]", "[hr ---]"); MT("setextAfterFencedCode", "[comment ```]", "[comment foo]", "[comment ```]", "[header&header-2 bar]", "[header&header-2 ---]"); MT("setextAferATX", "[header&header-1 # foo]", "[header&header-2 bar]", "[header&header-2 ---]"); // http://spec.commonmark.org/0.19/#example-51 MT("noSetextAfterQuote", "[quote"e-1 > foo]", "[hr ---]", "", "[quote"e-1 > foo]", "[quote"e-1 bar]", "[hr ---]"); MT("noSetextAfterList", "[variable-2 - foo]", "[hr ---]"); MT("noSetextAfterList_listContinuation", "[variable-2 - foo]", "bar", "[hr ---]"); MT("setextAfterList_afterIndentedCode", "[variable-2 - foo]", "", " [comment bar]", "[header&header-2 baz]", "[header&header-2 ---]"); MT("setextAfterList_afterFencedCodeBlocks", "[variable-2 - foo]", "", " [comment ```]", " [comment bar]", " [comment ```]", "[header&header-2 baz]", "[header&header-2 ---]"); MT("setextAfterList_afterHeader", "[variable-2 - foo]", " [variable-2&header&header-1 # bar]", "[header&header-2 baz]", "[header&header-2 ---]"); MT("setextAfterList_afterHr", "[variable-2 - foo]", "", " [hr ---]", "[header&header-2 bar]", "[header&header-2 ---]"); MT("setext_nestedInlineMarkup", "[header&header-1 foo ][em&header&header-1 *bar*]", "[header&header-1 =]"); MT("setext_linkDef", "[link [[aaa]]:] [string&url http://google.com 'title']", "[hr ---]"); // currently, looks max one line ahead, thus won't catch valid CommonMark // markup MT("setext_oneLineLookahead", "foo", "[header&header-1 bar]", "[header&header-1 =]"); // ensure we don't regard space after dash as a list MT("setext_emptyList", "[header&header-2 foo]", "[header&header-2 - ]", "foo"); // Single-line blockquote with trailing space MT("blockquoteSpace", "[quote"e-1 > foo]"); // Single-line blockquote MT("blockquoteNoSpace", "[quote"e-1 >foo]"); // No blank line before blockquote MT("blockquoteNoBlankLine", "foo", "[quote"e-1 > bar]"); MT("blockquoteNested", "[quote"e-1 > foo]", "[quote"e-1 >][quote"e-2 > foo]", "[quote"e-1 >][quote"e-2 >][quote"e-3 > foo]"); // ensure quote-level is inferred correctly even if indented MT("blockquoteNestedIndented", " [quote"e-1 > foo]", " [quote"e-1 >][quote"e-2 > foo]", " [quote"e-1 >][quote"e-2 >][quote"e-3 > foo]"); // ensure quote-level is inferred correctly even if indented MT("blockquoteIndentedTooMuch", "foo", " > bar"); // Single-line blockquote followed by normal paragraph MT("blockquoteThenParagraph", "[quote"e-1 >foo]", "", "bar"); // Multi-line blockquote (lazy mode) MT("multiBlockquoteLazy", "[quote"e-1 >foo]", "[quote"e-1 bar]"); // Multi-line blockquote followed by normal paragraph (lazy mode) MT("multiBlockquoteLazyThenParagraph", "[quote"e-1 >foo]", "[quote"e-1 bar]", "", "hello"); // Multi-line blockquote (non-lazy mode) MT("multiBlockquote", "[quote"e-1 >foo]", "[quote"e-1 >bar]"); // Multi-line blockquote followed by normal paragraph (non-lazy mode) MT("multiBlockquoteThenParagraph", "[quote"e-1 >foo]", "[quote"e-1 >bar]", "", "hello"); // disallow lists inside blockquote for now because it causes problems outside blockquote // TODO: fix to be CommonMark-compliant MT("listNestedInBlockquote", "[quote"e-1 > - foo]"); // disallow fenced blocks inside blockquote because it causes problems outside blockquote // TODO: fix to be CommonMark-compliant MT("fencedBlockNestedInBlockquote", "[quote"e-1 > ```]", "[quote"e-1 > code]", "[quote"e-1 > ```]", // ensure we still allow inline code "[quote"e-1 > ][quote"e-1&comment `code`]"); // Header with leading space after continued blockquote (#3287, negative indentation) MT("headerAfterContinuedBlockquote", "[quote"e-1 > foo]", "[quote"e-1 bar]", "", " [header&header-1 # hello]"); // Check list types MT("listAsterisk", "foo", "bar", "", "[variable-2 * foo]", "[variable-2 * bar]"); MT("listPlus", "foo", "bar", "", "[variable-2 + foo]", "[variable-2 + bar]"); MT("listDash", "foo", "bar", "", "[variable-2 - foo]", "[variable-2 - bar]"); MT("listNumber", "foo", "bar", "", "[variable-2 1. foo]", "[variable-2 2. bar]"); MT("listFromParagraph", "foo", "[variable-2 1. bar]", "[variable-2 2. hello]"); // List after hr MT("listAfterHr", "[hr ---]", "[variable-2 - bar]"); // List after header MT("listAfterHeader", "[header&header-1 # foo]", "[variable-2 - bar]"); // hr after list MT("hrAfterList", "[variable-2 - foo]", "[hr -----]"); MT("hrAfterFencedCode", "[comment ```]", "[comment code]", "[comment ```]", "[hr ---]"); // allow hr inside lists // (require prev line to be empty or hr, TODO: non-CommonMark-compliant) MT("hrInsideList", "[variable-2 - foo]", "", " [hr ---]", " [hr ---]", "", " [comment ---]"); MT("consecutiveHr", "[hr ---]", "[hr ---]", "[hr ---]"); // Formatting in lists (*) MT("listAsteriskFormatting", "[variable-2 * ][variable-2&em *foo*][variable-2 bar]", "[variable-2 * ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 * ][variable-2&em&strong ***foo***][variable-2 bar]", "[variable-2 * ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (+) MT("listPlusFormatting", "[variable-2 + ][variable-2&em *foo*][variable-2 bar]", "[variable-2 + ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 + ][variable-2&em&strong ***foo***][variable-2 bar]", "[variable-2 + ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (-) MT("listDashFormatting", "[variable-2 - ][variable-2&em *foo*][variable-2 bar]", "[variable-2 - ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 - ][variable-2&em&strong ***foo***][variable-2 bar]", "[variable-2 - ][variable-2&comment `foo`][variable-2 bar]"); // Formatting in lists (1.) MT("listNumberFormatting", "[variable-2 1. ][variable-2&em *foo*][variable-2 bar]", "[variable-2 2. ][variable-2&strong **foo**][variable-2 bar]", "[variable-2 3. ][variable-2&em&strong ***foo***][variable-2 bar]", "[variable-2 4. ][variable-2&comment `foo`][variable-2 bar]"); // Paragraph lists MT("listParagraph", "[variable-2 * foo]", "", "[variable-2 * bar]"); // Multi-paragraph lists // // 4 spaces MT("listMultiParagraph", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2 hello]"); // 4 spaces, extra blank lines (should still be list, per Dingus) MT("listMultiParagraphExtra", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "", " [variable-2 hello]"); // 4 spaces, plus 1 space (should still be list, per Dingus) MT("listMultiParagraphExtraSpace", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2 hello]", "", " [variable-2 world]"); // 1 tab MT("listTab", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "\t[variable-2 hello]"); // No indent MT("listNoIndent", "[variable-2 * foo]", "", "[variable-2 * bar]", "", "hello"); MT("listCommonMarkIndentationCode", "[variable-2 * Code blocks also affect]", " [variable-3 * The next level starts where the contents start.]", " [variable-3 * Anything less than that will keep the item on the same level.]", " [variable-3 * Each list item can indent the first level further and further.]", " [variable-3 * For the most part, this makes sense while writing a list.]", " [keyword * This means two items with same indentation can be different levels.]", " [keyword * Each level has an indent requirement that can change between items.]", " [keyword * A list item that meets this will be part of the next level.]", " [variable-3 * Otherwise, it will be part of the level where it does meet this.]", " [variable-2 * World]"); // should handle nested and un-nested lists MT("listCommonMark_MixedIndents", "[variable-2 * list1]", " [variable-2 list1]", " [variable-2&header&header-1 # heading still part of list1]", " [variable-2 text after heading still part of list1]", "", " [comment indented codeblock]", " [variable-2 list1 after code block]", " [variable-3 * list2]", // amount of spaces on empty lines between lists doesn't matter " ", // extra empty lines irrelevant "", "", " [variable-3 indented text part of list2]", " [keyword * list3]", "", " [variable-3 text at level of list2]", "", " [variable-2 de-indented text part of list1 again]", "", " [variable-2&comment ```]", " [comment code]", " [variable-2&comment ```]", "", " [variable-2 text after fenced code]"); // should correctly parse numbered list content indentation MT("listCommonMark_NumeberedListIndent", "[variable-2 1000. list with base indent of 6]", "", " [variable-2 text must be indented 6 spaces at minimum]", "", " [variable-2 9-spaces indented text still part of list]", "", " [comment indented codeblock starts at 10 spaces]", "", " [comment text indented by 5 spaces no longer belong to list]"); // should consider tab as 4 spaces MT("listCommonMark_TabIndented", "[variable-2 * list]", "\t[variable-3 * list2]", "", "\t\t[variable-3 part of list2]"); MT("listAfterBlockquote", "[quote"e-1 > foo]", "[variable-2 - bar]"); // shouldn't create sublist if it's indented more than allowed MT("nestedListIndentedTooMuch", "[variable-2 - foo]", " [variable-2 - bar]"); MT("listIndentedTooMuchAfterParagraph", "foo", " - bar"); // Blockquote MT("blockquote", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [variable-2"e"e-1 > hello]"); // Code block MT("blockquoteCode", "[variable-2 * foo]", "", "[variable-2 * bar]", "", " [comment > hello]", "", " [variable-2 world]"); // Code block followed by text MT("blockquoteCodeText", "[variable-2 * foo]", "", " [variable-2 bar]", "", " [comment hello]", "", " [variable-2 world]"); // Nested list MT("listAsteriskNested", "[variable-2 * foo]", "", " [variable-3 * bar]"); MT("listPlusNested", "[variable-2 + foo]", "", " [variable-3 + bar]"); MT("listDashNested", "[variable-2 - foo]", "", " [variable-3 - bar]"); MT("listNumberNested", "[variable-2 1. foo]", "", " [variable-3 2. bar]"); MT("listMixed", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [keyword - hello]", "", " [variable-2 1. world]"); MT("listBlockquote", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [quote"e-1&variable-3 > hello]"); MT("listCode", "[variable-2 * foo]", "", " [variable-3 + bar]", "", " [comment hello]"); // Code with internal indentation MT("listCodeIndentation", "[variable-2 * foo]", "", " [comment bar]", " [comment hello]", " [comment world]", " [comment foo]", " [variable-2 bar]"); // List nesting edge cases MT("listNested", "[variable-2 * foo]", "", " [variable-3 * bar]", "", " [variable-3 hello]" ); MT("listNested", "[variable-2 * foo]", "", " [variable-3 * bar]", "", " [keyword * foo]" ); // Code followed by text MT("listCodeText", "[variable-2 * foo]", "", " [comment bar]", "", "hello"); // Following tests directly from official Markdown documentation // http://daringfireball.net/projects/markdown/syntax#hr MT("hrSpace", "[hr * * *]"); MT("hr", "[hr ***]"); MT("hrLong", "[hr *****]"); MT("hrSpaceDash", "[hr - - -]"); MT("hrDashLong", "[hr ---------------------------------------]"); //Images MT("Images", "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://link.to/image.jpg)]") //Images with highlight alt text MT("imageEm", "[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)]"); MT("imageStrong", "[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)]"); MT("imageEmStrong", "[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)]"); // Inline link with title MT("linkTitle", "[link [[foo]]][string&url (http://example.com/ \"bar\")] hello"); // Inline link without title MT("linkNoTitle", "[link [[foo]]][string&url (http://example.com/)] bar"); // Inline link with image MT("linkImage", "[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"); // Inline link with Em MT("linkEm", "[link [[][link&em *foo*][link ]]][string&url (http://example.com/)] bar"); // Inline link with Strong MT("linkStrong", "[link [[][link&strong **foo**][link ]]][string&url (http://example.com/)] bar"); // Inline link with EmStrong MT("linkEmStrong", "[link [[][link&em&strong ***foo***][link ]]][string&url (http://example.com/)] bar"); MT("multilineLink", "[link [[foo]", "[link bar]]][string&url (https://foo#_a)]", "should not be italics") // Image with title MT("imageTitle", "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/ \"bar\")] hello"); // Image without title MT("imageNoTitle", "[image&image-marker !][image&image-alt-text&link [[alt text]]][string&url (http://example.com/)] bar"); // Image with asterisks MT("imageAsterisks", "[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"); // Not a link. Should be normal text due to square brackets being used // regularly in text, especially in quoted material, and no space is allowed // between square brackets and parentheses (per Dingus). MT("notALink", "[link [[foo]]] (bar)"); // Reference-style links MT("linkReference", "[link [[foo]]][string&url [[bar]]] hello"); // Reference-style links with Em MT("linkReferenceEm", "[link [[][link&em *foo*][link ]]][string&url [[bar]]] hello"); // Reference-style links with Strong MT("linkReferenceStrong", "[link [[][link&strong **foo**][link ]]][string&url [[bar]]] hello"); // Reference-style links with EmStrong MT("linkReferenceEmStrong", "[link [[][link&em&strong ***foo***][link ]]][string&url [[bar]]] hello"); // Reference-style links with optional space separator (per documentation) // "You can optionally use a space to separate the sets of brackets" MT("linkReferenceSpace", "[link [[foo]]] [string&url [[bar]]] hello"); // Should only allow a single space ("...use *a* space...") MT("linkReferenceDoubleSpace", "[link [[foo]]] [link [[bar]]] hello"); // Reference-style links with implicit link name MT("linkImplicit", "[link [[foo]]][string&url [[]]] hello"); // @todo It would be nice if, at some point, the document was actually // checked to see if the referenced link exists // Link label, for reference-style links (taken from documentation) MT("labelNoTitle", "[link [[foo]]:] [string&url http://example.com/]"); MT("labelIndented", " [link [[foo]]:] [string&url http://example.com/]"); MT("labelSpaceTitle", "[link [[foo bar]]:] [string&url http://example.com/ \"hello\"]"); MT("labelDoubleTitle", "[link [[foo bar]]:] [string&url http://example.com/ \"hello\"] \"world\""); MT("labelTitleDoubleQuotes", "[link [[foo]]:] [string&url http://example.com/ \"bar\"]"); MT("labelTitleSingleQuotes", "[link [[foo]]:] [string&url http://example.com/ 'bar']"); MT("labelTitleParentheses", "[link [[foo]]:] [string&url http://example.com/ (bar)]"); MT("labelTitleInvalid", "[link [[foo]]:] [string&url http://example.com/] bar"); MT("labelLinkAngleBrackets", "[link [[foo]]:] [string&url \"bar\"]"); MT("labelTitleNextDoubleQuotes", "[link [[foo]]:] [string&url http://example.com/]", "[string \"bar\"] hello"); MT("labelTitleNextSingleQuotes", "[link [[foo]]:] [string&url http://example.com/]", "[string 'bar'] hello"); MT("labelTitleNextParentheses", "[link [[foo]]:] [string&url http://example.com/]", "[string (bar)] hello"); MT("labelTitleNextMixed", "[link [[foo]]:] [string&url http://example.com/]", "(bar\" hello"); MT("labelEscape", "[link [[foo \\]] ]]:] [string&url http://example.com/]"); MT("labelEscapeColon", "[link [[foo \\]]: bar]]:] [string&url http://example.com/]"); MT("labelEscapeEnd", "\\[[foo\\]]: http://example.com/"); MT("linkWeb", "[link ] foo"); MT("linkWebDouble", "[link ] foo [link ]"); MT("linkEmail", "[link ] foo"); MT("linkEmailDouble", "[link ] foo [link ]"); MT("emAsterisk", "[em *foo*] bar"); MT("emUnderscore", "[em _foo_] bar"); MT("emInWordAsterisk", "foo[em *bar*]hello"); MT("emInWordUnderscore", "foo_bar_hello"); // Per documentation: "...surround an * or _ with spaces, it’ll be // treated as a literal asterisk or underscore." MT("emEscapedBySpaceIn", "foo [em _bar _ hello_] world"); MT("emEscapedBySpaceOut", "foo _ bar [em _hello_] world"); MT("emEscapedByNewline", "foo", "_ bar [em _hello_] world"); // Unclosed emphasis characters // Instead of simply marking as EM / STRONG, it would be nice to have an // incomplete flag for EM and STRONG, that is styled slightly different. MT("emIncompleteAsterisk", "foo [em *bar]"); MT("emIncompleteUnderscore", "foo [em _bar]"); MT("strongAsterisk", "[strong **foo**] bar"); MT("strongUnderscore", "[strong __foo__] bar"); MT("emStrongAsterisk", "[em *foo][em&strong **bar*][strong hello**] world"); MT("emStrongUnderscore", "[em _foo ][em&strong __bar_][strong hello__] world"); // "...same character must be used to open and close an emphasis span."" MT("emStrongMixed", "[em _foo][em&strong **bar*hello__ world]"); MT("emStrongMixed", "[em *foo ][em&strong __bar_hello** world]"); MT("linkWithNestedParens", "[link [[foo]]][string&url (bar(baz))]") // These characters should be escaped: // \ backslash // ` backtick // * asterisk // _ underscore // {} curly braces // [] square brackets // () parentheses // # hash mark // + plus sign // - minus sign (hyphen) // . dot // ! exclamation mark MT("escapeBacktick", "foo \\`bar\\`"); MT("doubleEscapeBacktick", "foo \\\\[comment `bar\\\\`]"); MT("escapeAsterisk", "foo \\*bar\\*"); MT("doubleEscapeAsterisk", "foo \\\\[em *bar\\\\*]"); MT("escapeUnderscore", "foo \\_bar\\_"); MT("doubleEscapeUnderscore", "foo \\\\[em _bar\\\\_]"); MT("escapeHash", "\\# foo"); MT("doubleEscapeHash", "\\\\# foo"); MT("escapeNewline", "\\", "[em *foo*]"); // Class override tests TokenTypeOverrideTest("overrideHeader1", "[override-header&override-header-1 # Foo]"); TokenTypeOverrideTest("overrideHeader2", "[override-header&override-header-2 ## Foo]"); TokenTypeOverrideTest("overrideHeader3", "[override-header&override-header-3 ### Foo]"); TokenTypeOverrideTest("overrideHeader4", "[override-header&override-header-4 #### Foo]"); TokenTypeOverrideTest("overrideHeader5", "[override-header&override-header-5 ##### Foo]"); TokenTypeOverrideTest("overrideHeader6", "[override-header&override-header-6 ###### Foo]"); TokenTypeOverrideTest("overrideCode", "[override-code `foo`]"); TokenTypeOverrideTest("overrideCodeBlock", "[override-code ```]", "[override-code foo]", "[override-code ```]"); TokenTypeOverrideTest("overrideQuote", "[override-quote&override-quote-1 > foo]", "[override-quote&override-quote-1 > bar]"); TokenTypeOverrideTest("overrideQuoteNested", "[override-quote&override-quote-1 > foo]", "[override-quote&override-quote-1 >][override-quote&override-quote-2 > bar]", "[override-quote&override-quote-1 >][override-quote&override-quote-2 >][override-quote&override-quote-3 > baz]"); TokenTypeOverrideTest("overrideLists", "[override-list1 - foo]", "", " [override-list2 + bar]", "", " [override-list3 * baz]", "", " [override-list1 1. qux]", "", " [override-list2 - quux]"); TokenTypeOverrideTest("overrideHr", "[override-hr * * *]"); TokenTypeOverrideTest("overrideImage", "[override-image&override-image-marker !][override-image&override-image-alt-text&link [[alt text]]][override-link-href&url (http://link.to/image.jpg)]"); TokenTypeOverrideTest("overrideLinkText", "[override-link-text [[foo]]][override-link-href&url (http://example.com)]"); TokenTypeOverrideTest("overrideLinkEmailAndInline", "[override-link-email <][override-link-inline foo@example.com>]"); TokenTypeOverrideTest("overrideEm", "[override-em *foo*]"); TokenTypeOverrideTest("overrideStrong", "[override-strong **foo**]"); TokenTypeOverrideTest("overrideStrikethrough", "[override-strikethrough ~~foo~~]"); TokenTypeOverrideTest("overrideEmoji", "[override-emoji :foo:]"); FormatTokenTypeOverrideTest("overrideFormatting", "[override-formatting-escape \\*]"); // Tests to make sure GFM-specific things aren't getting through MT("taskList", "[variable-2 * ][link&variable-2 [[ ]]][variable-2 bar]"); MT("fencedCodeBlocks", "[comment ```]", "[comment foo]", "", "[comment bar]", "[comment ```]", "baz"); MT("fencedCodeBlocks_invalidClosingFence_trailingText", "[comment ```]", "[comment foo]", "[comment ``` must not have trailing text]", "[comment baz]"); MT("fencedCodeBlocks_invalidClosingFence_trailingTabs", "[comment ```]", "[comment foo]", "[comment ```\t]", "[comment baz]"); MT("fencedCodeBlocks_validClosingFence", "[comment ```]", "[comment foo]", // may have trailing spaces "[comment ``` ]", "baz"); MT("fencedCodeBlocksInList_closingFenceIndented", "[variable-2 - list]", " [variable-2&comment ```]", " [comment foo]", " [variable-2&comment ```]", " [variable-2 baz]"); MT("fencedCodeBlocksInList_closingFenceIndentedTooMuch", "[variable-2 - list]", " [variable-2&comment ```]", " [comment foo]", " [comment ```]", " [comment baz]"); MT("fencedCodeBlockModeSwitching", "[comment ```javascript]", "[variable foo]", "", "[comment ```]", "bar"); MT_noFencedHighlight("fencedCodeBlock_noHighlight", "[comment ```javascript]", "[comment foo]", "[comment ```]"); MT("fencedCodeBlockModeSwitchingObjc", "[comment ```objective-c]", "[keyword @property] [variable NSString] [operator *] [variable foo];", "[comment ```]", "bar"); MT("fencedCodeBlocksMultipleChars", "[comment `````]", "[comment foo]", "[comment ```]", "[comment foo]", "[comment `````]", "bar"); MT("fencedCodeBlocksTildes", "[comment ~~~]", "[comment foo]", "[comment ~~~]", "bar"); MT("fencedCodeBlocksTildesMultipleChars", "[comment ~~~~~]", "[comment ~~~]", "[comment foo]", "[comment ~~~~~]", "bar"); MT("fencedCodeBlocksMultipleChars", "[comment `````]", "[comment foo]", "[comment ```]", "[comment foo]", "[comment `````]", "bar"); MT("fencedCodeBlocksMixed", "[comment ~~~]", "[comment ```]", "[comment foo]", "[comment ~~~]", "bar"); MT("fencedCodeBlocksAfterBlockquote", "[quote"e-1 > foo]", "[comment ```]", "[comment bar]", "[comment ```]"); // fencedCode indented too much should act as simple indentedCode // (hence has no highlight formatting) FT("tooMuchIndentedFencedCode", " [comment ```]", " [comment code]", " [comment ```]"); MT("autoTerminateFencedCodeWhenLeavingList", "[variable-2 - list1]", " [variable-3 - list2]", " [variable-3&comment ```]", " [comment code]", " [variable-3 - list2]", " [variable-2&comment ```]", " [comment code]", "[quote"e-1 > foo]"); // Tests that require XML mode MT("xmlMode", "[tag&bracket <][tag div][tag&bracket >]", " *foo*", " [tag&bracket <][tag http://github.com][tag&bracket />]", "[tag&bracket ]", "[link ]"); MT("xmlModeWithMarkdownInside", "[tag&bracket <][tag div] [attribute markdown]=[string 1][tag&bracket >]", "[em *foo*]", "[link ]", "[tag ]", "[link ]", "[tag&bracket <][tag div][tag&bracket >]", "[tag&bracket ]"); MT("xmlModeLineBreakInTags", "[tag&bracket <][tag div] [attribute id]=[string \"1\"]", " [attribute class]=[string \"sth\"][tag&bracket >]xxx", "[tag&bracket ]"); MT("xmlModeCommentWithBlankLine", "[comment ]"); MT("xmlModeCDATA", "[atom ]"); MT("xmlModePreprocessor", "[meta ]"); MT_noXml("xmlHighlightDisabled", "
foo
"); // Tests Emojis ET("emojiDefault", "[builtin :foobar:]"); ET("emojiTable", " :--:"); })(); ================================================ FILE: third_party/CodeMirror/mode/mathematica/index.html ================================================ CodeMirror: Mathematica mode

Mathematica mode

MIME types defined: text/x-mathematica (Mathematica).

================================================ FILE: third_party/CodeMirror/mode/mathematica/mathematica.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Mathematica mode copyright (c) 2015 by Calin Barbat // Based on code by Patrick Scheibe (halirutan) // See: https://github.com/halirutan/Mathematica-Source-Highlighting/tree/master/src/lang-mma.js (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('mathematica', function(_config, _parserConfig) { // used pattern building blocks var Identifier = '[a-zA-Z\\$][a-zA-Z0-9\\$]*'; var pBase = "(?:\\d+)"; var pFloat = "(?:\\.\\d+|\\d+\\.\\d*|\\d+)"; var pFloatBase = "(?:\\.\\w+|\\w+\\.\\w*|\\w+)"; var pPrecision = "(?:`(?:`?"+pFloat+")?)"; // regular expressions var reBaseForm = new RegExp('(?:'+pBase+'(?:\\^\\^'+pFloatBase+pPrecision+'?(?:\\*\\^[+-]?\\d+)?))'); var reFloatForm = new RegExp('(?:' + pFloat + pPrecision + '?(?:\\*\\^[+-]?\\d+)?)'); var reIdInContext = new RegExp('(?:`?)(?:' + Identifier + ')(?:`(?:' + Identifier + '))*(?:`?)'); function tokenBase(stream, state) { var ch; // get next character ch = stream.next(); // string if (ch === '"') { state.tokenize = tokenString; return state.tokenize(stream, state); } // comment if (ch === '(') { if (stream.eat('*')) { state.commentLevel++; state.tokenize = tokenComment; return state.tokenize(stream, state); } } // go back one character stream.backUp(1); // look for numbers // Numbers in a baseform if (stream.match(reBaseForm, true, false)) { return 'number'; } // Mathematica numbers. Floats (1.2, .2, 1.) can have optionally a precision (`float) or an accuracy definition // (``float). Note: while 1.2` is possible 1.2`` is not. At the end an exponent (float*^+12) can follow. if (stream.match(reFloatForm, true, false)) { return 'number'; } /* In[23] and Out[34] */ if (stream.match(/(?:In|Out)\[[0-9]*\]/, true, false)) { return 'atom'; } // usage if (stream.match(/([a-zA-Z\$][a-zA-Z0-9\$]*(?:`[a-zA-Z0-9\$]+)*::usage)/, true, false)) { return 'meta'; } // message if (stream.match(/([a-zA-Z\$][a-zA-Z0-9\$]*(?:`[a-zA-Z0-9\$]+)*::[a-zA-Z\$][a-zA-Z0-9\$]*):?/, true, false)) { return 'string-2'; } // this makes a look-ahead match for something like variable:{_Integer} // the match is then forwarded to the mma-patterns tokenizer. if (stream.match(/([a-zA-Z\$][a-zA-Z0-9\$]*\s*:)(?:(?:[a-zA-Z\$][a-zA-Z0-9\$]*)|(?:[^:=>~@\^\&\*\)\[\]'\?,\|])).*/, true, false)) { return 'variable-2'; } // catch variables which are used together with Blank (_), BlankSequence (__) or BlankNullSequence (___) // Cannot start with a number, but can have numbers at any other position. Examples // blub__Integer, a1_, b34_Integer32 if (stream.match(/[a-zA-Z\$][a-zA-Z0-9\$]*_+[a-zA-Z\$][a-zA-Z0-9\$]*/, true, false)) { return 'variable-2'; } if (stream.match(/[a-zA-Z\$][a-zA-Z0-9\$]*_+/, true, false)) { return 'variable-2'; } if (stream.match(/_+[a-zA-Z\$][a-zA-Z0-9\$]*/, true, false)) { return 'variable-2'; } // Named characters in Mathematica, like \[Gamma]. if (stream.match(/\\\[[a-zA-Z\$][a-zA-Z0-9\$]*\]/, true, false)) { return 'variable-3'; } // Match all braces separately if (stream.match(/(?:\[|\]|{|}|\(|\))/, true, false)) { return 'bracket'; } // Catch Slots (#, ##, #3, ##9 and the V10 named slots #name). I have never seen someone using more than one digit after #, so we match // only one. if (stream.match(/(?:#[a-zA-Z\$][a-zA-Z0-9\$]*|#+[0-9]?)/, true, false)) { return 'variable-2'; } // Literals like variables, keywords, functions if (stream.match(reIdInContext, true, false)) { return 'keyword'; } // operators. Note that operators like @@ or /; are matched separately for each symbol. if (stream.match(/(?:\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%)/, true, false)) { return 'operator'; } // everything else is an error stream.next(); // advance the stream. return 'error'; } function tokenString(stream, state) { var next, end = false, escaped = false; while ((next = stream.next()) != null) { if (next === '"' && !escaped) { end = true; break; } escaped = !escaped && next === '\\'; } if (end && !escaped) { state.tokenize = tokenBase; } return 'string'; }; function tokenComment(stream, state) { var prev, next; while(state.commentLevel > 0 && (next = stream.next()) != null) { if (prev === '(' && next === '*') state.commentLevel++; if (prev === '*' && next === ')') state.commentLevel--; prev = next; } if (state.commentLevel <= 0) { state.tokenize = tokenBase; } return 'comment'; } return { startState: function() {return {tokenize: tokenBase, commentLevel: 0};}, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, blockCommentStart: "(*", blockCommentEnd: "*)" }; }); CodeMirror.defineMIME('text/x-mathematica', { name: 'mathematica' }); }); ================================================ FILE: third_party/CodeMirror/mode/mbox/index.html ================================================ CodeMirror: mbox mode

mbox mode

MIME types defined: application/mbox.

================================================ FILE: third_party/CodeMirror/mode/mbox/mbox.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var rfc2822 = [ "From", "Sender", "Reply-To", "To", "Cc", "Bcc", "Message-ID", "In-Reply-To", "References", "Resent-From", "Resent-Sender", "Resent-To", "Resent-Cc", "Resent-Bcc", "Resent-Message-ID", "Return-Path", "Received" ]; var rfc2822NoEmail = [ "Date", "Subject", "Comments", "Keywords", "Resent-Date" ]; CodeMirror.registerHelper("hintWords", "mbox", rfc2822.concat(rfc2822NoEmail)); var whitespace = /^[ \t]/; var separator = /^From /; // See RFC 4155 var rfc2822Header = new RegExp("^(" + rfc2822.join("|") + "): "); var rfc2822HeaderNoEmail = new RegExp("^(" + rfc2822NoEmail.join("|") + "): "); var header = /^[^:]+:/; // Optional fields defined in RFC 2822 var email = /^[^ ]+@[^ ]+/; var untilEmail = /^.*?(?=[^ ]+?@[^ ]+)/; var bracketedEmail = /^<.*?>/; var untilBracketedEmail = /^.*?(?=<.*>)/; function styleForHeader(header) { if (header === "Subject") return "header"; return "string"; } function readToken(stream, state) { if (stream.sol()) { // From last line state.inSeparator = false; if (state.inHeader && stream.match(whitespace)) { // Header folding return null; } else { state.inHeader = false; state.header = null; } if (stream.match(separator)) { state.inHeaders = true; state.inSeparator = true; return "atom"; } var match; var emailPermitted = false; if ((match = stream.match(rfc2822HeaderNoEmail)) || (emailPermitted = true) && (match = stream.match(rfc2822Header))) { state.inHeaders = true; state.inHeader = true; state.emailPermitted = emailPermitted; state.header = match[1]; return "atom"; } // Use vim's heuristics: recognize custom headers only if the line is in a // block of legitimate headers. if (state.inHeaders && (match = stream.match(header))) { state.inHeader = true; state.emailPermitted = true; state.header = match[1]; return "atom"; } state.inHeaders = false; stream.skipToEnd(); return null; } if (state.inSeparator) { if (stream.match(email)) return "link"; if (stream.match(untilEmail)) return "atom"; stream.skipToEnd(); return "atom"; } if (state.inHeader) { var style = styleForHeader(state.header); if (state.emailPermitted) { if (stream.match(bracketedEmail)) return style + " link"; if (stream.match(untilBracketedEmail)) return style; } stream.skipToEnd(); return style; } stream.skipToEnd(); return null; }; CodeMirror.defineMode("mbox", function() { return { startState: function() { return { // Is in a mbox separator inSeparator: false, // Is in a mail header inHeader: false, // If bracketed email is permitted. Only applicable when inHeader emailPermitted: false, // Name of current header header: null, // Is in a region of mail headers inHeaders: false }; }, token: readToken, blankLine: function(state) { state.inHeaders = state.inSeparator = state.inHeader = false; } }; }); CodeMirror.defineMIME("application/mbox", "mbox"); }); ================================================ FILE: third_party/CodeMirror/mode/meta.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.modeInfo = [ {name: "APL", mime: "text/apl", mode: "apl", ext: ["dyalog", "apl"]}, {name: "PGP", mimes: ["application/pgp", "application/pgp-encrypted", "application/pgp-keys", "application/pgp-signature"], mode: "asciiarmor", ext: ["asc", "pgp", "sig"]}, {name: "ASN.1", mime: "text/x-ttcn-asn", mode: "asn.1", ext: ["asn", "asn1"]}, {name: "Asterisk", mime: "text/x-asterisk", mode: "asterisk", file: /^extensions\.conf$/i}, {name: "Brainfuck", mime: "text/x-brainfuck", mode: "brainfuck", ext: ["b", "bf"]}, {name: "C", mime: "text/x-csrc", mode: "clike", ext: ["c", "h", "ino"]}, {name: "C++", mime: "text/x-c++src", mode: "clike", ext: ["cpp", "c++", "cc", "cxx", "hpp", "h++", "hh", "hxx"], alias: ["cpp"]}, {name: "Cobol", mime: "text/x-cobol", mode: "cobol", ext: ["cob", "cpy"]}, {name: "C#", mime: "text/x-csharp", mode: "clike", ext: ["cs"], alias: ["csharp"]}, {name: "Clojure", mime: "text/x-clojure", mode: "clojure", ext: ["clj", "cljc", "cljx"]}, {name: "ClojureScript", mime: "text/x-clojurescript", mode: "clojure", ext: ["cljs"]}, {name: "Closure Stylesheets (GSS)", mime: "text/x-gss", mode: "css", ext: ["gss"]}, {name: "CMake", mime: "text/x-cmake", mode: "cmake", ext: ["cmake", "cmake.in"], file: /^CMakeLists.txt$/}, {name: "CoffeeScript", mimes: ["application/vnd.coffeescript", "text/coffeescript", "text/x-coffeescript"], mode: "coffeescript", ext: ["coffee"], alias: ["coffee", "coffee-script"]}, {name: "Common Lisp", mime: "text/x-common-lisp", mode: "commonlisp", ext: ["cl", "lisp", "el"], alias: ["lisp"]}, {name: "Cypher", mime: "application/x-cypher-query", mode: "cypher", ext: ["cyp", "cypher"]}, {name: "Cython", mime: "text/x-cython", mode: "python", ext: ["pyx", "pxd", "pxi"]}, {name: "Crystal", mime: "text/x-crystal", mode: "crystal", ext: ["cr"]}, {name: "CSS", mime: "text/css", mode: "css", ext: ["css"]}, {name: "CQL", mime: "text/x-cassandra", mode: "sql", ext: ["cql"]}, {name: "D", mime: "text/x-d", mode: "d", ext: ["d"]}, {name: "Dart", mimes: ["application/dart", "text/x-dart"], mode: "dart", ext: ["dart"]}, {name: "diff", mime: "text/x-diff", mode: "diff", ext: ["diff", "patch"]}, {name: "Django", mime: "text/x-django", mode: "django"}, {name: "Dockerfile", mime: "text/x-dockerfile", mode: "dockerfile", file: /^Dockerfile$/}, {name: "DTD", mime: "application/xml-dtd", mode: "dtd", ext: ["dtd"]}, {name: "Dylan", mime: "text/x-dylan", mode: "dylan", ext: ["dylan", "dyl", "intr"]}, {name: "EBNF", mime: "text/x-ebnf", mode: "ebnf"}, {name: "ECL", mime: "text/x-ecl", mode: "ecl", ext: ["ecl"]}, {name: "edn", mime: "application/edn", mode: "clojure", ext: ["edn"]}, {name: "Eiffel", mime: "text/x-eiffel", mode: "eiffel", ext: ["e"]}, {name: "Elm", mime: "text/x-elm", mode: "elm", ext: ["elm"]}, {name: "Embedded Javascript", mime: "application/x-ejs", mode: "htmlembedded", ext: ["ejs"]}, {name: "Embedded Ruby", mime: "application/x-erb", mode: "htmlembedded", ext: ["erb"]}, {name: "Erlang", mime: "text/x-erlang", mode: "erlang", ext: ["erl"]}, {name: "Esper", mime: "text/x-esper", mode: "sql"}, {name: "Factor", mime: "text/x-factor", mode: "factor", ext: ["factor"]}, {name: "FCL", mime: "text/x-fcl", mode: "fcl"}, {name: "Forth", mime: "text/x-forth", mode: "forth", ext: ["forth", "fth", "4th"]}, {name: "Fortran", mime: "text/x-fortran", mode: "fortran", ext: ["f", "for", "f77", "f90", "f95"]}, {name: "F#", mime: "text/x-fsharp", mode: "mllike", ext: ["fs"], alias: ["fsharp"]}, {name: "Gas", mime: "text/x-gas", mode: "gas", ext: ["s"]}, {name: "Gherkin", mime: "text/x-feature", mode: "gherkin", ext: ["feature"]}, {name: "GitHub Flavored Markdown", mime: "text/x-gfm", mode: "gfm", file: /^(readme|contributing|history).md$/i}, {name: "Go", mime: "text/x-go", mode: "go", ext: ["go"]}, {name: "Groovy", mime: "text/x-groovy", mode: "groovy", ext: ["groovy", "gradle"], file: /^Jenkinsfile$/}, {name: "HAML", mime: "text/x-haml", mode: "haml", ext: ["haml"]}, {name: "Haskell", mime: "text/x-haskell", mode: "haskell", ext: ["hs"]}, {name: "Haskell (Literate)", mime: "text/x-literate-haskell", mode: "haskell-literate", ext: ["lhs"]}, {name: "Haxe", mime: "text/x-haxe", mode: "haxe", ext: ["hx"]}, {name: "HXML", mime: "text/x-hxml", mode: "haxe", ext: ["hxml"]}, {name: "ASP.NET", mime: "application/x-aspx", mode: "htmlembedded", ext: ["aspx"], alias: ["asp", "aspx"]}, {name: "HTML", mime: "text/html", mode: "htmlmixed", ext: ["html", "htm", "handlebars", "hbs"], alias: ["xhtml"]}, {name: "HTTP", mime: "message/http", mode: "http"}, {name: "IDL", mime: "text/x-idl", mode: "idl", ext: ["pro"]}, {name: "Pug", mime: "text/x-pug", mode: "pug", ext: ["jade", "pug"], alias: ["jade"]}, {name: "Java", mime: "text/x-java", mode: "clike", ext: ["java"]}, {name: "Java Server Pages", mime: "application/x-jsp", mode: "htmlembedded", ext: ["jsp"], alias: ["jsp"]}, {name: "JavaScript", mimes: ["text/javascript", "text/ecmascript", "application/javascript", "application/x-javascript", "application/ecmascript"], mode: "javascript", ext: ["js"], alias: ["ecmascript", "js", "node"]}, {name: "JSON", mimes: ["application/json", "application/x-json"], mode: "javascript", ext: ["json", "map"], alias: ["json5"]}, {name: "JSON-LD", mime: "application/ld+json", mode: "javascript", ext: ["jsonld"], alias: ["jsonld"]}, {name: "JSX", mime: "text/jsx", mode: "jsx", ext: ["jsx"]}, {name: "Jinja2", mime: "text/jinja2", mode: "jinja2", ext: ["j2", "jinja", "jinja2"]}, {name: "Julia", mime: "text/x-julia", mode: "julia", ext: ["jl"]}, {name: "Kotlin", mime: "text/x-kotlin", mode: "clike", ext: ["kt"]}, {name: "LESS", mime: "text/x-less", mode: "css", ext: ["less"]}, {name: "LiveScript", mime: "text/x-livescript", mode: "livescript", ext: ["ls"], alias: ["ls"]}, {name: "Lua", mime: "text/x-lua", mode: "lua", ext: ["lua"]}, {name: "Markdown", mime: "text/x-markdown", mode: "markdown", ext: ["markdown", "md", "mkd"]}, {name: "mIRC", mime: "text/mirc", mode: "mirc"}, {name: "MariaDB SQL", mime: "text/x-mariadb", mode: "sql"}, {name: "Mathematica", mime: "text/x-mathematica", mode: "mathematica", ext: ["m", "nb"]}, {name: "Modelica", mime: "text/x-modelica", mode: "modelica", ext: ["mo"]}, {name: "MUMPS", mime: "text/x-mumps", mode: "mumps", ext: ["mps"]}, {name: "MS SQL", mime: "text/x-mssql", mode: "sql"}, {name: "mbox", mime: "application/mbox", mode: "mbox", ext: ["mbox"]}, {name: "MySQL", mime: "text/x-mysql", mode: "sql"}, {name: "Nginx", mime: "text/x-nginx-conf", mode: "nginx", file: /nginx.*\.conf$/i}, {name: "NSIS", mime: "text/x-nsis", mode: "nsis", ext: ["nsh", "nsi"]}, {name: "NTriples", mimes: ["application/n-triples", "application/n-quads", "text/n-triples"], mode: "ntriples", ext: ["nt", "nq"]}, {name: "Objective-C", mime: "text/x-objectivec", mode: "clike", ext: ["m", "mm"], alias: ["objective-c", "objc"]}, {name: "OCaml", mime: "text/x-ocaml", mode: "mllike", ext: ["ml", "mli", "mll", "mly"]}, {name: "Octave", mime: "text/x-octave", mode: "octave", ext: ["m"]}, {name: "Oz", mime: "text/x-oz", mode: "oz", ext: ["oz"]}, {name: "Pascal", mime: "text/x-pascal", mode: "pascal", ext: ["p", "pas"]}, {name: "PEG.js", mime: "null", mode: "pegjs", ext: ["jsonld"]}, {name: "Perl", mime: "text/x-perl", mode: "perl", ext: ["pl", "pm"]}, {name: "PHP", mimes: ["text/x-php", "application/x-httpd-php", "application/x-httpd-php-open"], mode: "php", ext: ["php", "php3", "php4", "php5", "php7", "phtml"]}, {name: "Pig", mime: "text/x-pig", mode: "pig", ext: ["pig"]}, {name: "Plain Text", mime: "text/plain", mode: "null", ext: ["txt", "text", "conf", "def", "list", "log"]}, {name: "PLSQL", mime: "text/x-plsql", mode: "sql", ext: ["pls"]}, {name: "PowerShell", mime: "application/x-powershell", mode: "powershell", ext: ["ps1", "psd1", "psm1"]}, {name: "Properties files", mime: "text/x-properties", mode: "properties", ext: ["properties", "ini", "in"], alias: ["ini", "properties"]}, {name: "ProtoBuf", mime: "text/x-protobuf", mode: "protobuf", ext: ["proto"]}, {name: "Python", mime: "text/x-python", mode: "python", ext: ["BUILD", "bzl", "py", "pyw"], file: /^(BUCK|BUILD)$/}, {name: "Puppet", mime: "text/x-puppet", mode: "puppet", ext: ["pp"]}, {name: "Q", mime: "text/x-q", mode: "q", ext: ["q"]}, {name: "R", mime: "text/x-rsrc", mode: "r", ext: ["r", "R"], alias: ["rscript"]}, {name: "reStructuredText", mime: "text/x-rst", mode: "rst", ext: ["rst"], alias: ["rst"]}, {name: "RPM Changes", mime: "text/x-rpm-changes", mode: "rpm"}, {name: "RPM Spec", mime: "text/x-rpm-spec", mode: "rpm", ext: ["spec"]}, {name: "Ruby", mime: "text/x-ruby", mode: "ruby", ext: ["rb"], alias: ["jruby", "macruby", "rake", "rb", "rbx"]}, {name: "Rust", mime: "text/x-rustsrc", mode: "rust", ext: ["rs"]}, {name: "SAS", mime: "text/x-sas", mode: "sas", ext: ["sas"]}, {name: "Sass", mime: "text/x-sass", mode: "sass", ext: ["sass"]}, {name: "Scala", mime: "text/x-scala", mode: "clike", ext: ["scala"]}, {name: "Scheme", mime: "text/x-scheme", mode: "scheme", ext: ["scm", "ss"]}, {name: "SCSS", mime: "text/x-scss", mode: "css", ext: ["scss"]}, {name: "Shell", mimes: ["text/x-sh", "application/x-sh"], mode: "shell", ext: ["sh", "ksh", "bash"], alias: ["bash", "sh", "zsh"], file: /^PKGBUILD$/}, {name: "Sieve", mime: "application/sieve", mode: "sieve", ext: ["siv", "sieve"]}, {name: "Slim", mimes: ["text/x-slim", "application/x-slim"], mode: "slim", ext: ["slim"]}, {name: "Smalltalk", mime: "text/x-stsrc", mode: "smalltalk", ext: ["st"]}, {name: "Smarty", mime: "text/x-smarty", mode: "smarty", ext: ["tpl"]}, {name: "Solr", mime: "text/x-solr", mode: "solr"}, {name: "SML", mime: "text/x-sml", mode: "mllike", ext: ["sml", "sig", "fun", "smackspec"]}, {name: "Soy", mime: "text/x-soy", mode: "soy", ext: ["soy"], alias: ["closure template"]}, {name: "SPARQL", mime: "application/sparql-query", mode: "sparql", ext: ["rq", "sparql"], alias: ["sparul"]}, {name: "Spreadsheet", mime: "text/x-spreadsheet", mode: "spreadsheet", alias: ["excel", "formula"]}, {name: "SQL", mime: "text/x-sql", mode: "sql", ext: ["sql"]}, {name: "SQLite", mime: "text/x-sqlite", mode: "sql"}, {name: "Squirrel", mime: "text/x-squirrel", mode: "clike", ext: ["nut"]}, {name: "Stylus", mime: "text/x-styl", mode: "stylus", ext: ["styl"]}, {name: "Swift", mime: "text/x-swift", mode: "swift", ext: ["swift"]}, {name: "sTeX", mime: "text/x-stex", mode: "stex"}, {name: "LaTeX", mime: "text/x-latex", mode: "stex", ext: ["text", "ltx", "tex"], alias: ["tex"]}, {name: "SystemVerilog", mime: "text/x-systemverilog", mode: "verilog", ext: ["v", "sv", "svh"]}, {name: "Tcl", mime: "text/x-tcl", mode: "tcl", ext: ["tcl"]}, {name: "Textile", mime: "text/x-textile", mode: "textile", ext: ["textile"]}, {name: "TiddlyWiki ", mime: "text/x-tiddlywiki", mode: "tiddlywiki"}, {name: "Tiki wiki", mime: "text/tiki", mode: "tiki"}, {name: "TOML", mime: "text/x-toml", mode: "toml", ext: ["toml"]}, {name: "Tornado", mime: "text/x-tornado", mode: "tornado"}, {name: "troff", mime: "text/troff", mode: "troff", ext: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]}, {name: "TTCN", mime: "text/x-ttcn", mode: "ttcn", ext: ["ttcn", "ttcn3", "ttcnpp"]}, {name: "TTCN_CFG", mime: "text/x-ttcn-cfg", mode: "ttcn-cfg", ext: ["cfg"]}, {name: "Turtle", mime: "text/turtle", mode: "turtle", ext: ["ttl"]}, {name: "TypeScript", mime: "application/typescript", mode: "javascript", ext: ["ts"], alias: ["ts"]}, {name: "TypeScript-JSX", mime: "text/typescript-jsx", mode: "jsx", ext: ["tsx"], alias: ["tsx"]}, {name: "Twig", mime: "text/x-twig", mode: "twig"}, {name: "Web IDL", mime: "text/x-webidl", mode: "webidl", ext: ["webidl"]}, {name: "VB.NET", mime: "text/x-vb", mode: "vb", ext: ["vb"]}, {name: "VBScript", mime: "text/vbscript", mode: "vbscript", ext: ["vbs"]}, {name: "Velocity", mime: "text/velocity", mode: "velocity", ext: ["vtl"]}, {name: "Verilog", mime: "text/x-verilog", mode: "verilog", ext: ["v"]}, {name: "VHDL", mime: "text/x-vhdl", mode: "vhdl", ext: ["vhd", "vhdl"]}, {name: "Vue.js Component", mimes: ["script/x-vue", "text/x-vue"], mode: "vue", ext: ["vue"]}, {name: "XML", mimes: ["application/xml", "text/xml"], mode: "xml", ext: ["xml", "xsl", "xsd", "svg"], alias: ["rss", "wsdl", "xsd"]}, {name: "XQuery", mime: "application/xquery", mode: "xquery", ext: ["xy", "xquery"]}, {name: "Yacas", mime: "text/x-yacas", mode: "yacas", ext: ["ys"]}, {name: "YAML", mimes: ["text/x-yaml", "text/yaml"], mode: "yaml", ext: ["yaml", "yml"], alias: ["yml"]}, {name: "Z80", mime: "text/x-z80", mode: "z80", ext: ["z80"]}, {name: "mscgen", mime: "text/x-mscgen", mode: "mscgen", ext: ["mscgen", "mscin", "msc"]}, {name: "xu", mime: "text/x-xu", mode: "mscgen", ext: ["xu"]}, {name: "msgenny", mime: "text/x-msgenny", mode: "mscgen", ext: ["msgenny"]} ]; // Ensure all modes have a mime property for backwards compatibility for (var i = 0; i < CodeMirror.modeInfo.length; i++) { var info = CodeMirror.modeInfo[i]; if (info.mimes) info.mime = info.mimes[0]; } CodeMirror.findModeByMIME = function(mime) { mime = mime.toLowerCase(); for (var i = 0; i < CodeMirror.modeInfo.length; i++) { var info = CodeMirror.modeInfo[i]; if (info.mime == mime) return info; if (info.mimes) for (var j = 0; j < info.mimes.length; j++) if (info.mimes[j] == mime) return info; } if (/\+xml$/.test(mime)) return CodeMirror.findModeByMIME("application/xml") if (/\+json$/.test(mime)) return CodeMirror.findModeByMIME("application/json") }; CodeMirror.findModeByExtension = function(ext) { for (var i = 0; i < CodeMirror.modeInfo.length; i++) { var info = CodeMirror.modeInfo[i]; if (info.ext) for (var j = 0; j < info.ext.length; j++) if (info.ext[j] == ext) return info; } }; CodeMirror.findModeByFileName = function(filename) { for (var i = 0; i < CodeMirror.modeInfo.length; i++) { var info = CodeMirror.modeInfo[i]; if (info.file && info.file.test(filename)) return info; } var dot = filename.lastIndexOf("."); var ext = dot > -1 && filename.substring(dot + 1, filename.length); if (ext) return CodeMirror.findModeByExtension(ext); }; CodeMirror.findModeByName = function(name) { name = name.toLowerCase(); for (var i = 0; i < CodeMirror.modeInfo.length; i++) { var info = CodeMirror.modeInfo[i]; if (info.name.toLowerCase() == name) return info; if (info.alias) for (var j = 0; j < info.alias.length; j++) if (info.alias[j].toLowerCase() == name) return info; } }; }); ================================================ FILE: third_party/CodeMirror/mode/mirc/index.html ================================================ CodeMirror: mIRC mode

mIRC mode

MIME types defined: text/mirc.

================================================ FILE: third_party/CodeMirror/mode/mirc/mirc.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE //mIRC mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMIME("text/mirc", "mirc"); CodeMirror.defineMode("mirc", function() { function parseWords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var specials = parseWords("$! $$ $& $? $+ $abook $abs $active $activecid " + "$activewid $address $addtok $agent $agentname $agentstat $agentver " + "$alias $and $anick $ansi2mirc $aop $appactive $appstate $asc $asctime " + "$asin $atan $avoice $away $awaymsg $awaytime $banmask $base $bfind " + "$binoff $biton $bnick $bvar $bytes $calc $cb $cd $ceil $chan $chanmodes " + "$chantypes $chat $chr $cid $clevel $click $cmdbox $cmdline $cnick $color " + "$com $comcall $comchan $comerr $compact $compress $comval $cos $count " + "$cr $crc $creq $crlf $ctime $ctimer $ctrlenter $date $day $daylight " + "$dbuh $dbuw $dccignore $dccport $dde $ddename $debug $decode $decompress " + "$deltok $devent $dialog $did $didreg $didtok $didwm $disk $dlevel $dll " + "$dllcall $dname $dns $duration $ebeeps $editbox $emailaddr $encode $error " + "$eval $event $exist $feof $ferr $fgetc $file $filename $filtered $finddir " + "$finddirn $findfile $findfilen $findtok $fline $floor $fopen $fread $fserve " + "$fulladdress $fulldate $fullname $fullscreen $get $getdir $getdot $gettok $gmt " + "$group $halted $hash $height $hfind $hget $highlight $hnick $hotline " + "$hotlinepos $ial $ialchan $ibl $idle $iel $ifmatch $ignore $iif $iil " + "$inelipse $ini $inmidi $inpaste $inpoly $input $inrect $inroundrect " + "$insong $instok $int $inwave $ip $isalias $isbit $isdde $isdir $isfile " + "$isid $islower $istok $isupper $keychar $keyrpt $keyval $knick $lactive " + "$lactivecid $lactivewid $left $len $level $lf $line $lines $link $lock " + "$lock $locked $log $logstamp $logstampfmt $longfn $longip $lower $ltimer " + "$maddress $mask $matchkey $matchtok $md5 $me $menu $menubar $menucontext " + "$menutype $mid $middir $mircdir $mircexe $mircini $mklogfn $mnick $mode " + "$modefirst $modelast $modespl $mouse $msfile $network $newnick $nick $nofile " + "$nopath $noqt $not $notags $notify $null $numeric $numok $oline $onpoly " + "$opnick $or $ord $os $passivedcc $pic $play $pnick $port $portable $portfree " + "$pos $prefix $prop $protect $puttok $qt $query $rand $r $rawmsg $read $readomo " + "$readn $regex $regml $regsub $regsubex $remove $remtok $replace $replacex " + "$reptok $result $rgb $right $round $scid $scon $script $scriptdir $scriptline " + "$sdir $send $server $serverip $sfile $sha1 $shortfn $show $signal $sin " + "$site $sline $snick $snicks $snotify $sock $sockbr $sockerr $sockname " + "$sorttok $sound $sqrt $ssl $sreq $sslready $status $strip $str $stripped " + "$syle $submenu $switchbar $tan $target $ticks $time $timer $timestamp " + "$timestampfmt $timezone $tip $titlebar $toolbar $treebar $trust $ulevel " + "$ulist $upper $uptime $url $usermode $v1 $v2 $var $vcmd $vcmdstat $vcmdver " + "$version $vnick $vol $wid $width $wildsite $wildtok $window $wrap $xor"); var keywords = parseWords("abook ajinvite alias aline ame amsg anick aop auser autojoin avoice " + "away background ban bcopy beep bread break breplace bset btrunc bunset bwrite " + "channel clear clearall cline clipboard close cnick color comclose comopen " + "comreg continue copy creq ctcpreply ctcps dcc dccserver dde ddeserver " + "debug dec describe dialog did didtok disable disconnect dlevel dline dll " + "dns dqwindow drawcopy drawdot drawfill drawline drawpic drawrect drawreplace " + "drawrot drawsave drawscroll drawtext ebeeps echo editbox emailaddr enable " + "events exit fclose filter findtext finger firewall flash flist flood flush " + "flushini font fopen fseek fsend fserve fullname fwrite ghide gload gmove " + "gopts goto gplay gpoint gqreq groups gshow gsize gstop gtalk gunload hadd " + "halt haltdef hdec hdel help hfree hinc hload hmake hop hsave ial ialclear " + "ialmark identd if ignore iline inc invite iuser join kick linesep links list " + "load loadbuf localinfo log mdi me menubar mkdir mnick mode msg nick noop notice " + "notify omsg onotice part partall pdcc perform play playctrl pop protect pvoice " + "qme qmsg query queryn quit raw reload remini remote remove rename renwin " + "reseterror resetidle return rlevel rline rmdir run ruser save savebuf saveini " + "say scid scon server set showmirc signam sline sockaccept sockclose socklist " + "socklisten sockmark sockopen sockpause sockread sockrename sockudp sockwrite " + "sound speak splay sreq strip switchbar timer timestamp titlebar tnick tokenize " + "toolbar topic tray treebar ulist unload unset unsetall updatenl url uwho " + "var vcadd vcmd vcrem vol while whois window winhelp write writeint if isalnum " + "isalpha isaop isavoice isban ischan ishop isignore isin isincs isletter islower " + "isnotify isnum ison isop isprotect isreg isupper isvoice iswm iswmcs " + "elseif else goto menu nicklist status title icon size option text edit " + "button check radio box scroll list combo link tab item"); var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch"); var isOperatorChar = /[+\-*&%=<>!?^\/\|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenBase(stream, state) { var beforeParams = state.beforeParams; state.beforeParams = false; var ch = stream.next(); if (/[\[\]{}\(\),\.]/.test(ch)) { if (ch == "(" && beforeParams) state.inParams = true; else if (ch == ")") state.inParams = false; return null; } else if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } else if (ch == "\\") { stream.eat("\\"); stream.eat(/./); return "number"; } else if (ch == "/" && stream.eat("*")) { return chain(stream, state, tokenComment); } else if (ch == ";" && stream.match(/ *\( *\(/)) { return chain(stream, state, tokenUnparsed); } else if (ch == ";" && !state.inParams) { stream.skipToEnd(); return "comment"; } else if (ch == '"') { stream.eat(/"/); return "keyword"; } else if (ch == "$") { stream.eatWhile(/[$_a-z0-9A-Z\.:]/); if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) { return "keyword"; } else { state.beforeParams = true; return "builtin"; } } else if (ch == "%") { stream.eatWhile(/[^,\s()]/); state.beforeParams = true; return "string"; } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } else { stream.eatWhile(/[\w\$_{}]/); var word = stream.current().toLowerCase(); if (keywords && keywords.propertyIsEnumerable(word)) return "keyword"; if (functions && functions.propertyIsEnumerable(word)) { state.beforeParams = true; return "keyword"; } return null; } } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenUnparsed(stream, state) { var maybeEnd = 0, ch; while (ch = stream.next()) { if (ch == ";" && maybeEnd == 2) { state.tokenize = tokenBase; break; } if (ch == ")") maybeEnd++; else if (ch != " ") maybeEnd = 0; } return "meta"; } return { startState: function() { return { tokenize: tokenBase, beforeParams: false, inParams: false }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); } }; }); }); ================================================ FILE: third_party/CodeMirror/mode/mllike/index.html ================================================ CodeMirror: ML-like mode

OCaml mode

F# mode

MIME types defined: text/x-ocaml (OCaml) and text/x-fsharp (F#).

================================================ FILE: third_party/CodeMirror/mode/mllike/mllike.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('mllike', function(_config, parserConfig) { var words = { 'as': 'keyword', 'do': 'keyword', 'else': 'keyword', 'end': 'keyword', 'exception': 'keyword', 'fun': 'keyword', 'functor': 'keyword', 'if': 'keyword', 'in': 'keyword', 'include': 'keyword', 'let': 'keyword', 'of': 'keyword', 'open': 'keyword', 'rec': 'keyword', 'struct': 'keyword', 'then': 'keyword', 'type': 'keyword', 'val': 'keyword', 'while': 'keyword', 'with': 'keyword' }; var extraWords = parserConfig.extraWords || {}; for (var prop in extraWords) { if (extraWords.hasOwnProperty(prop)) { words[prop] = parserConfig.extraWords[prop]; } } var hintWords = []; for (var k in words) { hintWords.push(k); } CodeMirror.registerHelper("hintWords", "mllike", hintWords); function tokenBase(stream, state) { var ch = stream.next(); if (ch === '"') { state.tokenize = tokenString; return state.tokenize(stream, state); } if (ch === '{') { if (stream.eat('|')) { state.longString = true; state.tokenize = tokenLongString; return state.tokenize(stream, state); } } if (ch === '(') { if (stream.eat('*')) { state.commentLevel++; state.tokenize = tokenComment; return state.tokenize(stream, state); } } if (ch === '~' || ch === '?') { stream.eatWhile(/\w/); return 'variable-2'; } if (ch === '`') { stream.eatWhile(/\w/); return 'quote'; } if (ch === '/' && parserConfig.slashComments && stream.eat('/')) { stream.skipToEnd(); return 'comment'; } if (/\d/.test(ch)) { if (ch === '0' && stream.eat(/[bB]/)) { stream.eatWhile(/[01]/); } if (ch === '0' && stream.eat(/[xX]/)) { stream.eatWhile(/[0-9a-fA-F]/) } if (ch === '0' && stream.eat(/[oO]/)) { stream.eatWhile(/[0-7]/); } else { stream.eatWhile(/[\d_]/); if (stream.eat('.')) { stream.eatWhile(/[\d]/); } if (stream.eat(/[eE]/)) { stream.eatWhile(/[\d\-+]/); } } return 'number'; } if ( /[+\-*&%=<>!?|@\.~:]/.test(ch)) { return 'operator'; } if (/[\w\xa1-\uffff]/.test(ch)) { stream.eatWhile(/[\w\xa1-\uffff]/); var cur = stream.current(); return words.hasOwnProperty(cur) ? words[cur] : 'variable'; } return null } function tokenString(stream, state) { var next, end = false, escaped = false; while ((next = stream.next()) != null) { if (next === '"' && !escaped) { end = true; break; } escaped = !escaped && next === '\\'; } if (end && !escaped) { state.tokenize = tokenBase; } return 'string'; }; function tokenComment(stream, state) { var prev, next; while(state.commentLevel > 0 && (next = stream.next()) != null) { if (prev === '(' && next === '*') state.commentLevel++; if (prev === '*' && next === ')') state.commentLevel--; prev = next; } if (state.commentLevel <= 0) { state.tokenize = tokenBase; } return 'comment'; } function tokenLongString(stream, state) { var prev, next; while (state.longString && (next = stream.next()) != null) { if (prev === '|' && next === '}') state.longString = false; prev = next; } if (!state.longString) { state.tokenize = tokenBase; } return 'string'; } return { startState: function() {return {tokenize: tokenBase, commentLevel: 0, longString: false};}, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, blockCommentStart: "(*", blockCommentEnd: "*)", lineComment: parserConfig.slashComments ? "//" : null }; }); CodeMirror.defineMIME('text/x-ocaml', { name: 'mllike', extraWords: { 'and': 'keyword', 'assert': 'keyword', 'begin': 'keyword', 'class': 'keyword', 'constraint': 'keyword', 'done': 'keyword', 'downto': 'keyword', 'external': 'keyword', 'function': 'keyword', 'initializer': 'keyword', 'lazy': 'keyword', 'match': 'keyword', 'method': 'keyword', 'module': 'keyword', 'mutable': 'keyword', 'new': 'keyword', 'nonrec': 'keyword', 'object': 'keyword', 'private': 'keyword', 'sig': 'keyword', 'to': 'keyword', 'try': 'keyword', 'value': 'keyword', 'virtual': 'keyword', 'when': 'keyword', // builtins 'raise': 'builtin', 'failwith': 'builtin', 'true': 'builtin', 'false': 'builtin', // Pervasives builtins 'asr': 'builtin', 'land': 'builtin', 'lor': 'builtin', 'lsl': 'builtin', 'lsr': 'builtin', 'lxor': 'builtin', 'mod': 'builtin', 'or': 'builtin', // More Pervasives 'raise_notrace': 'builtin', 'trace': 'builtin', 'exit': 'builtin', 'print_string': 'builtin', 'print_endline': 'builtin', 'int': 'type', 'float': 'type', 'bool': 'type', 'char': 'type', 'string': 'type', 'unit': 'type', // Modules 'List': 'builtin' } }); CodeMirror.defineMIME('text/x-fsharp', { name: 'mllike', extraWords: { 'abstract': 'keyword', 'assert': 'keyword', 'base': 'keyword', 'begin': 'keyword', 'class': 'keyword', 'default': 'keyword', 'delegate': 'keyword', 'do!': 'keyword', 'done': 'keyword', 'downcast': 'keyword', 'downto': 'keyword', 'elif': 'keyword', 'extern': 'keyword', 'finally': 'keyword', 'for': 'keyword', 'function': 'keyword', 'global': 'keyword', 'inherit': 'keyword', 'inline': 'keyword', 'interface': 'keyword', 'internal': 'keyword', 'lazy': 'keyword', 'let!': 'keyword', 'match': 'keyword', 'member': 'keyword', 'module': 'keyword', 'mutable': 'keyword', 'namespace': 'keyword', 'new': 'keyword', 'null': 'keyword', 'override': 'keyword', 'private': 'keyword', 'public': 'keyword', 'return!': 'keyword', 'return': 'keyword', 'select': 'keyword', 'static': 'keyword', 'to': 'keyword', 'try': 'keyword', 'upcast': 'keyword', 'use!': 'keyword', 'use': 'keyword', 'void': 'keyword', 'when': 'keyword', 'yield!': 'keyword', 'yield': 'keyword', // Reserved words 'atomic': 'keyword', 'break': 'keyword', 'checked': 'keyword', 'component': 'keyword', 'const': 'keyword', 'constraint': 'keyword', 'constructor': 'keyword', 'continue': 'keyword', 'eager': 'keyword', 'event': 'keyword', 'external': 'keyword', 'fixed': 'keyword', 'method': 'keyword', 'mixin': 'keyword', 'object': 'keyword', 'parallel': 'keyword', 'process': 'keyword', 'protected': 'keyword', 'pure': 'keyword', 'sealed': 'keyword', 'tailcall': 'keyword', 'trait': 'keyword', 'virtual': 'keyword', 'volatile': 'keyword', // builtins 'List': 'builtin', 'Seq': 'builtin', 'Map': 'builtin', 'Set': 'builtin', 'Option': 'builtin', 'int': 'builtin', 'string': 'builtin', 'not': 'builtin', 'true': 'builtin', 'false': 'builtin', 'raise': 'builtin', 'failwith': 'builtin' }, slashComments: true }); CodeMirror.defineMIME('text/x-sml', { name: 'mllike', extraWords: { 'abstype': 'keyword', 'and': 'keyword', 'andalso': 'keyword', 'case': 'keyword', 'datatype': 'keyword', 'fn': 'keyword', 'handle': 'keyword', 'infix': 'keyword', 'infixr': 'keyword', 'local': 'keyword', 'nonfix': 'keyword', 'op': 'keyword', 'orelse': 'keyword', 'raise': 'keyword', 'withtype': 'keyword', 'eqtype': 'keyword', 'sharing': 'keyword', 'sig': 'keyword', 'signature': 'keyword', 'structure': 'keyword', 'where': 'keyword', 'true': 'keyword', 'false': 'keyword', // types 'int': 'builtin', 'real': 'builtin', 'string': 'builtin', 'char': 'builtin', 'bool': 'builtin' }, slashComments: true }); }); ================================================ FILE: third_party/CodeMirror/mode/modelica/index.html ================================================ CodeMirror: Modelica mode

Modelica mode

Simple mode that tries to handle Modelica as well as it can.

MIME types defined: text/x-modelica (Modlica code).

================================================ FILE: third_party/CodeMirror/mode/modelica/modelica.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Modelica support for CodeMirror, copyright (c) by Lennart Ochel (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); }) (function(CodeMirror) { "use strict"; CodeMirror.defineMode("modelica", function(config, parserConfig) { var indentUnit = config.indentUnit; var keywords = parserConfig.keywords || {}; var builtin = parserConfig.builtin || {}; var atoms = parserConfig.atoms || {}; var isSingleOperatorChar = /[;=\(:\),{}.*<>+\-\/^\[\]]/; var isDoubleOperatorChar = /(:=|<=|>=|==|<>|\.\+|\.\-|\.\*|\.\/|\.\^)/; var isDigit = /[0-9]/; var isNonDigit = /[_a-zA-Z]/; function tokenLineComment(stream, state) { stream.skipToEnd(); state.tokenize = null; return "comment"; } function tokenBlockComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenString(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == '"' && !escaped) { state.tokenize = null; state.sol = false; break; } escaped = !escaped && ch == "\\"; } return "string"; } function tokenIdent(stream, state) { stream.eatWhile(isDigit); while (stream.eat(isDigit) || stream.eat(isNonDigit)) { } var cur = stream.current(); if(state.sol && (cur == "package" || cur == "model" || cur == "when" || cur == "connector")) state.level++; else if(state.sol && cur == "end" && state.level > 0) state.level--; state.tokenize = null; state.sol = false; if (keywords.propertyIsEnumerable(cur)) return "keyword"; else if (builtin.propertyIsEnumerable(cur)) return "builtin"; else if (atoms.propertyIsEnumerable(cur)) return "atom"; else return "variable"; } function tokenQIdent(stream, state) { while (stream.eat(/[^']/)) { } state.tokenize = null; state.sol = false; if(stream.eat("'")) return "variable"; else return "error"; } function tokenUnsignedNuber(stream, state) { stream.eatWhile(isDigit); if (stream.eat('.')) { stream.eatWhile(isDigit); } if (stream.eat('e') || stream.eat('E')) { if (!stream.eat('-')) stream.eat('+'); stream.eatWhile(isDigit); } state.tokenize = null; state.sol = false; return "number"; } // Interface return { startState: function() { return { tokenize: null, level: 0, sol: true }; }, token: function(stream, state) { if(state.tokenize != null) { return state.tokenize(stream, state); } if(stream.sol()) { state.sol = true; } // WHITESPACE if(stream.eatSpace()) { state.tokenize = null; return null; } var ch = stream.next(); // LINECOMMENT if(ch == '/' && stream.eat('/')) { state.tokenize = tokenLineComment; } // BLOCKCOMMENT else if(ch == '/' && stream.eat('*')) { state.tokenize = tokenBlockComment; } // TWO SYMBOL TOKENS else if(isDoubleOperatorChar.test(ch+stream.peek())) { stream.next(); state.tokenize = null; return "operator"; } // SINGLE SYMBOL TOKENS else if(isSingleOperatorChar.test(ch)) { state.tokenize = null; return "operator"; } // IDENT else if(isNonDigit.test(ch)) { state.tokenize = tokenIdent; } // Q-IDENT else if(ch == "'" && stream.peek() && stream.peek() != "'") { state.tokenize = tokenQIdent; } // STRING else if(ch == '"') { state.tokenize = tokenString; } // UNSIGNED_NUBER else if(isDigit.test(ch)) { state.tokenize = tokenUnsignedNuber; } // ERROR else { state.tokenize = null; return "error"; } return state.tokenize(stream, state); }, indent: function(state, textAfter) { if (state.tokenize != null) return CodeMirror.Pass; var level = state.level; if(/(algorithm)/.test(textAfter)) level--; if(/(equation)/.test(textAfter)) level--; if(/(initial algorithm)/.test(textAfter)) level--; if(/(initial equation)/.test(textAfter)) level--; if(/(end)/.test(textAfter)) level--; if(level > 0) return indentUnit*level; else return 0; }, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i=0; i CodeMirror: MscGen mode

MscGen mode

Xù mode

MsGenny mode

Simple mode for highlighting MscGen and two derived sequence chart languages.

MIME types defined: text/x-mscgen text/x-xu text/x-msgenny

================================================ FILE: third_party/CodeMirror/mode/mscgen/mscgen.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // mode(s) for the sequence chart dsl's mscgen, xù and msgenny // For more information on mscgen, see the site of the original author: // http://www.mcternan.me.uk/mscgen // // This mode for mscgen and the two derivative languages were // originally made for use in the mscgen_js interpreter // (https://sverweij.github.io/mscgen_js) (function(mod) { if ( typeof exports == "object" && typeof module == "object")// CommonJS mod(require("../../lib/codemirror")); else if ( typeof define == "function" && define.amd)// AMD define(["../../lib/codemirror"], mod); else// Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var languages = { mscgen: { "keywords" : ["msc"], "options" : ["hscale", "width", "arcgradient", "wordwraparcs"], "constants" : ["true", "false", "on", "off"], "attributes" : ["label", "idurl", "id", "url", "linecolor", "linecolour", "textcolor", "textcolour", "textbgcolor", "textbgcolour", "arclinecolor", "arclinecolour", "arctextcolor", "arctextcolour", "arctextbgcolor", "arctextbgcolour", "arcskip"], "brackets" : ["\\{", "\\}"], // [ and ] are brackets too, but these get handled in with lists "arcsWords" : ["note", "abox", "rbox", "box"], "arcsOthers" : ["\\|\\|\\|", "\\.\\.\\.", "---", "--", "<->", "==", "<<=>>", "<=>", "\\.\\.", "<<>>", "::", "<:>", "->", "=>>", "=>", ">>", ":>", "<-", "<<=", "<=", "<<", "<:", "x-", "-x"], "singlecomment" : ["//", "#"], "operators" : ["="] }, xu: { "keywords" : ["msc", "xu"], "options" : ["hscale", "width", "arcgradient", "wordwraparcs", "wordwrapentities", "watermark"], "constants" : ["true", "false", "on", "off", "auto"], "attributes" : ["label", "idurl", "id", "url", "linecolor", "linecolour", "textcolor", "textcolour", "textbgcolor", "textbgcolour", "arclinecolor", "arclinecolour", "arctextcolor", "arctextcolour", "arctextbgcolor", "arctextbgcolour", "arcskip", "title", "deactivate", "activate", "activation"], "brackets" : ["\\{", "\\}"], // [ and ] are brackets too, but these get handled in with lists "arcsWords" : ["note", "abox", "rbox", "box", "alt", "else", "opt", "break", "par", "seq", "strict", "neg", "critical", "ignore", "consider", "assert", "loop", "ref", "exc"], "arcsOthers" : ["\\|\\|\\|", "\\.\\.\\.", "---", "--", "<->", "==", "<<=>>", "<=>", "\\.\\.", "<<>>", "::", "<:>", "->", "=>>", "=>", ">>", ":>", "<-", "<<=", "<=", "<<", "<:", "x-", "-x"], "singlecomment" : ["//", "#"], "operators" : ["="] }, msgenny: { "keywords" : null, "options" : ["hscale", "width", "arcgradient", "wordwraparcs", "wordwrapentities", "watermark"], "constants" : ["true", "false", "on", "off", "auto"], "attributes" : null, "brackets" : ["\\{", "\\}"], "arcsWords" : ["note", "abox", "rbox", "box", "alt", "else", "opt", "break", "par", "seq", "strict", "neg", "critical", "ignore", "consider", "assert", "loop", "ref", "exc"], "arcsOthers" : ["\\|\\|\\|", "\\.\\.\\.", "---", "--", "<->", "==", "<<=>>", "<=>", "\\.\\.", "<<>>", "::", "<:>", "->", "=>>", "=>", ">>", ":>", "<-", "<<=", "<=", "<<", "<:", "x-", "-x"], "singlecomment" : ["//", "#"], "operators" : ["="] } } CodeMirror.defineMode("mscgen", function(_, modeConfig) { var language = languages[modeConfig && modeConfig.language || "mscgen"] return { startState: startStateFn, copyState: copyStateFn, token: produceTokenFunction(language), lineComment : "#", blockCommentStart : "/*", blockCommentEnd : "*/" }; }); CodeMirror.defineMIME("text/x-mscgen", "mscgen"); CodeMirror.defineMIME("text/x-xu", {name: "mscgen", language: "xu"}); CodeMirror.defineMIME("text/x-msgenny", {name: "mscgen", language: "msgenny"}); function wordRegexpBoundary(pWords) { return new RegExp("\\b(" + pWords.join("|") + ")\\b", "i"); } function wordRegexp(pWords) { return new RegExp("(" + pWords.join("|") + ")", "i"); } function startStateFn() { return { inComment : false, inString : false, inAttributeList : false, inScript : false }; } function copyStateFn(pState) { return { inComment : pState.inComment, inString : pState.inString, inAttributeList : pState.inAttributeList, inScript : pState.inScript }; } function produceTokenFunction(pConfig) { return function(pStream, pState) { if (pStream.match(wordRegexp(pConfig.brackets), true, true)) { return "bracket"; } /* comments */ if (!pState.inComment) { if (pStream.match(/\/\*[^\*\/]*/, true, true)) { pState.inComment = true; return "comment"; } if (pStream.match(wordRegexp(pConfig.singlecomment), true, true)) { pStream.skipToEnd(); return "comment"; } } if (pState.inComment) { if (pStream.match(/[^\*\/]*\*\//, true, true)) pState.inComment = false; else pStream.skipToEnd(); return "comment"; } /* strings */ if (!pState.inString && pStream.match(/\"(\\\"|[^\"])*/, true, true)) { pState.inString = true; return "string"; } if (pState.inString) { if (pStream.match(/[^\"]*\"/, true, true)) pState.inString = false; else pStream.skipToEnd(); return "string"; } /* keywords & operators */ if (!!pConfig.keywords && pStream.match(wordRegexpBoundary(pConfig.keywords), true, true)) return "keyword"; if (pStream.match(wordRegexpBoundary(pConfig.options), true, true)) return "keyword"; if (pStream.match(wordRegexpBoundary(pConfig.arcsWords), true, true)) return "keyword"; if (pStream.match(wordRegexp(pConfig.arcsOthers), true, true)) return "keyword"; if (!!pConfig.operators && pStream.match(wordRegexp(pConfig.operators), true, true)) return "operator"; if (!!pConfig.constants && pStream.match(wordRegexp(pConfig.constants), true, true)) return "variable"; /* attribute lists */ if (!pConfig.inAttributeList && !!pConfig.attributes && pStream.match(/\[/, true, true)) { pConfig.inAttributeList = true; return "bracket"; } if (pConfig.inAttributeList) { if (pConfig.attributes !== null && pStream.match(wordRegexpBoundary(pConfig.attributes), true, true)) { return "attribute"; } if (pStream.match(/]/, true, true)) { pConfig.inAttributeList = false; return "bracket"; } } pStream.next(); return "base"; }; } }); ================================================ FILE: third_party/CodeMirror/mode/mscgen/mscgen_test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "mscgen"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("empty chart", "[keyword msc][bracket {]", "[base ]", "[bracket }]" ); MT("comments", "[comment // a single line comment]", "[comment # another single line comment /* and */ ignored here]", "[comment /* A multi-line comment even though it contains]", "[comment msc keywords and \"quoted text\"*/]"); MT("strings", "[string \"// a string\"]", "[string \"a string running over]", "[string two lines\"]", "[string \"with \\\"escaped quote\"]" ); MT("xù/ msgenny keywords classify as 'base'", "[base watermark]", "[base wordwrapentities]", "[base alt loop opt ref else break par seq assert]" ); MT("xù/ msgenny constants classify as 'base'", "[base auto]" ); MT("mscgen constants classify as 'variable'", "[variable true]", "[variable false]", "[variable on]", "[variable off]" ); MT("mscgen options classify as keyword", "[keyword hscale]", "[keyword width]", "[keyword arcgradient]", "[keyword wordwraparcs]" ); MT("mscgen arcs classify as keyword", "[keyword note]","[keyword abox]","[keyword rbox]","[keyword box]", "[keyword |||...---]", "[keyword ..--==::]", "[keyword ->]", "[keyword <-]", "[keyword <->]", "[keyword =>]", "[keyword <=]", "[keyword <=>]", "[keyword =>>]", "[keyword <<=]", "[keyword <<=>>]", "[keyword >>]", "[keyword <<]", "[keyword <<>>]", "[keyword -x]", "[keyword x-]", "[keyword -X]", "[keyword X-]", "[keyword :>]", "[keyword <:]", "[keyword <:>]" ); MT("within an attribute list, attributes classify as attribute", "[bracket [[][attribute label]", "[attribute id]","[attribute url]","[attribute idurl]", "[attribute linecolor]","[attribute linecolour]","[attribute textcolor]","[attribute textcolour]","[attribute textbgcolor]","[attribute textbgcolour]", "[attribute arclinecolor]","[attribute arclinecolour]","[attribute arctextcolor]","[attribute arctextcolour]","[attribute arctextbgcolor]","[attribute arctextbgcolour]", "[attribute arcskip][bracket ]]]" ); MT("outside an attribute list, attributes classify as base", "[base label]", "[base id]","[base url]","[base idurl]", "[base linecolor]","[base linecolour]","[base textcolor]","[base textcolour]","[base textbgcolor]","[base textbgcolour]", "[base arclinecolor]","[base arclinecolour]","[base arctextcolor]","[base arctextcolour]","[base arctextbgcolor]","[base arctextbgcolour]", "[base arcskip]" ); MT("a typical program", "[comment # typical mscgen program]", "[keyword msc][base ][bracket {]", "[keyword wordwraparcs][operator =][variable true][base , ][keyword hscale][operator =][string \"0.8\"][base , ][keyword arcgradient][operator =][base 30;]", "[base a][bracket [[][attribute label][operator =][string \"Entity A\"][bracket ]]][base ,]", "[base b][bracket [[][attribute label][operator =][string \"Entity B\"][bracket ]]][base ,]", "[base c][bracket [[][attribute label][operator =][string \"Entity C\"][bracket ]]][base ;]", "[base a ][keyword =>>][base b][bracket [[][attribute label][operator =][string \"Hello entity B\"][bracket ]]][base ;]", "[base a ][keyword <<][base b][bracket [[][attribute label][operator =][string \"Here's an answer dude!\"][bracket ]]][base ;]", "[base c ][keyword :>][base *][bracket [[][attribute label][operator =][string \"What about me?\"][base , ][attribute textcolor][operator =][base red][bracket ]]][base ;]", "[bracket }]" ); })(); ================================================ FILE: third_party/CodeMirror/mode/mscgen/msgenny_test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-msgenny"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "msgenny"); } MT("comments", "[comment // a single line comment]", "[comment # another single line comment /* and */ ignored here]", "[comment /* A multi-line comment even though it contains]", "[comment msc keywords and \"quoted text\"*/]"); MT("strings", "[string \"// a string\"]", "[string \"a string running over]", "[string two lines\"]", "[string \"with \\\"escaped quote\"]" ); MT("xù/ msgenny keywords classify as 'keyword'", "[keyword watermark]", "[keyword wordwrapentities]", "[keyword alt]","[keyword loop]","[keyword opt]","[keyword ref]","[keyword else]","[keyword break]","[keyword par]","[keyword seq]","[keyword assert]" ); MT("xù/ msgenny constants classify as 'variable'", "[variable auto]", "[variable true]", "[variable false]", "[variable on]", "[variable off]" ); MT("mscgen options classify as keyword", "[keyword hscale]", "[keyword width]", "[keyword arcgradient]", "[keyword wordwraparcs]" ); MT("mscgen arcs classify as keyword", "[keyword note]","[keyword abox]","[keyword rbox]","[keyword box]", "[keyword |||...---]", "[keyword ..--==::]", "[keyword ->]", "[keyword <-]", "[keyword <->]", "[keyword =>]", "[keyword <=]", "[keyword <=>]", "[keyword =>>]", "[keyword <<=]", "[keyword <<=>>]", "[keyword >>]", "[keyword <<]", "[keyword <<>>]", "[keyword -x]", "[keyword x-]", "[keyword -X]", "[keyword X-]", "[keyword :>]", "[keyword <:]", "[keyword <:>]" ); MT("within an attribute list, mscgen/ xù attributes classify as base", "[base [[label]", "[base idurl id url]", "[base linecolor linecolour textcolor textcolour textbgcolor textbgcolour]", "[base arclinecolor arclinecolour arctextcolor arctextcolour arctextbgcolor arctextbgcolour]", "[base arcskip]]]" ); MT("outside an attribute list, mscgen/ xù attributes classify as base", "[base label]", "[base idurl id url]", "[base linecolor linecolour textcolor textcolour textbgcolor textbgcolour]", "[base arclinecolor arclinecolour arctextcolor arctextcolour arctextbgcolor arctextbgcolour]", "[base arcskip]" ); MT("a typical program", "[comment # typical msgenny program]", "[keyword wordwraparcs][operator =][variable true][base , ][keyword hscale][operator =][string \"0.8\"][base , ][keyword arcgradient][operator =][base 30;]", "[base a : ][string \"Entity A\"][base ,]", "[base b : Entity B,]", "[base c : Entity C;]", "[base a ][keyword =>>][base b: ][string \"Hello entity B\"][base ;]", "[base a ][keyword alt][base c][bracket {]", "[base a ][keyword <<][base b: ][string \"Here's an answer dude!\"][base ;]", "[keyword ---][base : ][string \"sorry, won't march - comm glitch\"]", "[base a ][keyword x-][base b: ][string \"Here's an answer dude! (won't arrive...)\"][base ;]", "[bracket }]", "[base c ][keyword :>][base *: What about me?;]" ); })(); ================================================ FILE: third_party/CodeMirror/mode/mscgen/xu_test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-xu"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "xu"); } MT("empty chart", "[keyword msc][bracket {]", "[base ]", "[bracket }]" ); MT("empty chart", "[keyword xu][bracket {]", "[base ]", "[bracket }]" ); MT("comments", "[comment // a single line comment]", "[comment # another single line comment /* and */ ignored here]", "[comment /* A multi-line comment even though it contains]", "[comment msc keywords and \"quoted text\"*/]"); MT("strings", "[string \"// a string\"]", "[string \"a string running over]", "[string two lines\"]", "[string \"with \\\"escaped quote\"]" ); MT("xù/ msgenny keywords classify as 'keyword'", "[keyword watermark]", "[keyword alt]","[keyword loop]","[keyword opt]","[keyword ref]","[keyword else]","[keyword break]","[keyword par]","[keyword seq]","[keyword assert]" ); MT("xù/ msgenny constants classify as 'variable'", "[variable auto]", "[variable true]", "[variable false]", "[variable on]", "[variable off]" ); MT("mscgen options classify as keyword", "[keyword hscale]", "[keyword width]", "[keyword arcgradient]", "[keyword wordwraparcs]" ); MT("mscgen arcs classify as keyword", "[keyword note]","[keyword abox]","[keyword rbox]","[keyword box]", "[keyword |||...---]", "[keyword ..--==::]", "[keyword ->]", "[keyword <-]", "[keyword <->]", "[keyword =>]", "[keyword <=]", "[keyword <=>]", "[keyword =>>]", "[keyword <<=]", "[keyword <<=>>]", "[keyword >>]", "[keyword <<]", "[keyword <<>>]", "[keyword -x]", "[keyword x-]", "[keyword -X]", "[keyword X-]", "[keyword :>]", "[keyword <:]", "[keyword <:>]" ); MT("within an attribute list, attributes classify as attribute", "[bracket [[][attribute label]", "[attribute id]","[attribute url]","[attribute idurl]", "[attribute linecolor]","[attribute linecolour]","[attribute textcolor]","[attribute textcolour]","[attribute textbgcolor]","[attribute textbgcolour]", "[attribute arclinecolor]","[attribute arclinecolour]","[attribute arctextcolor]","[attribute arctextcolour]","[attribute arctextbgcolor]","[attribute arctextbgcolour]", "[attribute arcskip]","[attribute title]", "[attribute activate]","[attribute deactivate]","[attribute activation][bracket ]]]" ); MT("outside an attribute list, attributes classify as base", "[base label]", "[base id]","[base url]","[base idurl]", "[base linecolor]","[base linecolour]","[base textcolor]","[base textcolour]","[base textbgcolor]","[base textbgcolour]", "[base arclinecolor]","[base arclinecolour]","[base arctextcolor]","[base arctextcolour]","[base arctextbgcolor]","[base arctextbgcolour]", "[base arcskip]", "[base title]" ); MT("a typical program", "[comment # typical xu program]", "[keyword xu][base ][bracket {]", "[keyword wordwraparcs][operator =][string \"true\"][base , ][keyword hscale][operator =][string \"0.8\"][base , ][keyword arcgradient][operator =][base 30, ][keyword width][operator =][variable auto][base ;]", "[base a][bracket [[][attribute label][operator =][string \"Entity A\"][bracket ]]][base ,]", "[base b][bracket [[][attribute label][operator =][string \"Entity B\"][bracket ]]][base ,]", "[base c][bracket [[][attribute label][operator =][string \"Entity C\"][bracket ]]][base ;]", "[base a ][keyword =>>][base b][bracket [[][attribute label][operator =][string \"Hello entity B\"][bracket ]]][base ;]", "[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 ;]", "[base c ][keyword :>][base *][bracket [[][attribute label][operator =][string \"What about me?\"][base , ][attribute textcolor][operator =][base red][bracket ]]][base ;]", "[bracket }]" ); })(); ================================================ FILE: third_party/CodeMirror/mode/mumps/index.html ================================================  CodeMirror: MUMPS mode

MUMPS mode

================================================ FILE: third_party/CodeMirror/mode/mumps/mumps.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /* This MUMPS Language script was constructed using vbscript.js as a template. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("mumps", function() { function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b", "i"); } var singleOperators = new RegExp("^[\\+\\-\\*/&#!_?\\\\<>=\\'\\[\\]]"); var doubleOperators = new RegExp("^(('=)|(<=)|(>=)|('>)|('<)|([[)|(]])|(^$))"); var singleDelimiters = new RegExp("^[\\.,:]"); var brackets = new RegExp("[()]"); var identifiers = new RegExp("^[%A-Za-z][A-Za-z0-9]*"); 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"]; // The following list includes instrinsic functions _and_ special variables 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"]; var intrinsicFuncs = wordRegexp(intrinsicFuncsWords); var command = wordRegexp(commandKeywords); function tokenBase(stream, state) { if (stream.sol()) { state.label = true; state.commandMode = 0; } // The character has meaning in MUMPS. Ignoring consecutive // spaces would interfere with interpreting whether the next non-space // character belongs to the command or argument context. // Examine each character and update a mode variable whose interpretation is: // >0 => command 0 => argument <0 => command post-conditional var ch = stream.peek(); if (ch == " " || ch == "\t") { // Pre-process state.label = false; if (state.commandMode == 0) state.commandMode = 1; else if ((state.commandMode < 0) || (state.commandMode == 2)) state.commandMode = 0; } else if ((ch != ".") && (state.commandMode > 0)) { if (ch == ":") state.commandMode = -1; // SIS - Command post-conditional else state.commandMode = 2; } // Do not color parameter list as line tag if ((ch === "(") || (ch === "\u0009")) state.label = false; // MUMPS comment starts with ";" if (ch === ";") { stream.skipToEnd(); return "comment"; } // Number Literals // SIS/RLM - MUMPS permits canonic number followed by concatenate operator if (stream.match(/^[-+]?\d+(\.\d+)?([eE][-+]?\d+)?/)) return "number"; // Handle Strings if (ch == '"') { if (stream.skipTo('"')) { stream.next(); return "string"; } else { stream.skipToEnd(); return "error"; } } // Handle operators and Delimiters if (stream.match(doubleOperators) || stream.match(singleOperators)) return "operator"; // Prevents leading "." in DO block from falling through to error if (stream.match(singleDelimiters)) return null; if (brackets.test(ch)) { stream.next(); return "bracket"; } if (state.commandMode > 0 && stream.match(command)) return "variable-2"; if (stream.match(intrinsicFuncs)) return "builtin"; if (stream.match(identifiers)) return "variable"; // Detect dollar-sign when not a documented intrinsic function // "^" may introduce a GVN or SSVN - Color same as function if (ch === "$" || ch === "^") { stream.next(); return "builtin"; } // MUMPS Indirection if (ch === "@") { stream.next(); return "string-2"; } if (/[\w%]/.test(ch)) { stream.eatWhile(/[\w%]/); return "variable"; } // Handle non-detected items stream.next(); return "error"; } return { startState: function() { return { label: false, commandMode: 0 }; }, token: function(stream, state) { var style = tokenBase(stream, state); if (state.label) return "tag"; return style; } }; }); CodeMirror.defineMIME("text/x-mumps", "mumps"); }); ================================================ FILE: third_party/CodeMirror/mode/nginx/index.html ================================================ CodeMirror: NGINX mode

NGINX mode

MIME types defined: text/x-nginx-conf.

================================================ FILE: third_party/CodeMirror/mode/nginx/nginx.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("nginx", function(config) { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = words( /* ngxDirectiveControl */ "break return rewrite set" + /* 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" ); var keywords_block = words( /* ngxDirectiveBlock */ "http mail events server types location upstream charset_map limit_except if geo map" ); var keywords_important = words( /* ngxDirectiveImportant */ "include root server server_name listen internal proxy_pass memcached_pass fastcgi_pass try_files" ); var indentUnit = config.indentUnit, type; function ret(style, tp) {type = tp; return style;} function tokenBase(stream, state) { stream.eatWhile(/[\w\$_]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) { return "keyword"; } else if (keywords_block.propertyIsEnumerable(cur)) { return "variable-2"; } else if (keywords_important.propertyIsEnumerable(cur)) { return "string-2"; } /**/ var ch = stream.next(); if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("meta", stream.current());} else if (ch == "/" && stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } else if (ch == "<" && stream.eat("!")) { state.tokenize = tokenSGMLComment; return tokenSGMLComment(stream, state); } else if (ch == "=") ret(null, "compare"); else if ((ch == "~" || ch == "|") && stream.eat("=")) return ret(null, "compare"); else if (ch == "\"" || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("comment", "comment"); } else if (ch == "!") { stream.match(/^\s*\w*/); return ret("keyword", "important"); } else if (/\d/.test(ch)) { stream.eatWhile(/[\w.%]/); return ret("number", "unit"); } else if (/[,.+>*\/]/.test(ch)) { return ret(null, "select-op"); } else if (/[;{}:\[\]]/.test(ch)) { return ret(null, ch); } else { stream.eatWhile(/[\w\\\-]/); return ret("variable", "variable"); } } function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenSGMLComment(stream, state) { var dashes = 0, ch; while ((ch = stream.next()) != null) { if (dashes >= 2 && ch == ">") { state.tokenize = tokenBase; break; } dashes = (ch == "-") ? dashes + 1 : 0; } return ret("comment", "comment"); } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } return { startState: function(base) { return {tokenize: tokenBase, baseIndent: base || 0, stack: []}; }, token: function(stream, state) { if (stream.eatSpace()) return null; type = null; var style = state.tokenize(stream, state); var context = state.stack[state.stack.length-1]; if (type == "hash" && context == "rule") style = "atom"; else if (style == "variable") { if (context == "rule") style = "number"; else if (!context || context == "@media{") style = "tag"; } if (context == "rule" && /^[\{\};]$/.test(type)) state.stack.pop(); if (type == "{") { if (context == "@media") state.stack[state.stack.length-1] = "@media{"; else state.stack.push("{"); } else if (type == "}") state.stack.pop(); else if (type == "@media") state.stack.push("@media"); else if (context == "{" && type != "comment") state.stack.push("rule"); return style; }, indent: function(state, textAfter) { var n = state.stack.length; if (/^\}/.test(textAfter)) n -= state.stack[state.stack.length-1] == "rule" ? 2 : 1; return state.baseIndent + n * indentUnit; }, electricChars: "}" }; }); CodeMirror.defineMIME("text/x-nginx-conf", "nginx"); }); ================================================ FILE: third_party/CodeMirror/mode/nsis/index.html ================================================ CodeMirror: NSIS mode

NSIS mode

MIME types defined: text/x-nsis.

================================================ FILE: third_party/CodeMirror/mode/nsis/nsis.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Author: Jan T. Sott (http://github.com/idleberg) (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/simple")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../addon/mode/simple"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineSimpleMode("nsis",{ start:[ // Numbers {regex: /(?:[+-]?)(?:0x[\d,a-f]+)|(?:0o[0-7]+)|(?:0b[0,1]+)|(?:\d+.?\d*)/, token: "number"}, // Strings { regex: /"(?:[^\\"]|\\.)*"?/, token: "string" }, { regex: /'(?:[^\\']|\\.)*'?/, token: "string" }, { regex: /`(?:[^\\`]|\\.)*`?/, token: "string" }, // Compile Time Commands {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"}, // Conditional Compilation {regex: /^\s*(?:\!(if(?:n?def)?|ifmacron?def|macro))\b/, token: "keyword", indent: true}, {regex: /^\s*(?:\!(else|endif|macroend))\b/, token: "keyword", dedent: true}, // Runtime Commands {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"}, {regex: /^\s*(?:Function|PageEx|Section(?:Group)?)\b/, token: "keyword", indent: true}, {regex: /^\s*(?:(Function|PageEx|Section(?:Group)?)End)\b/, token: "keyword", dedent: true}, // Command Options {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"}, {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"}, // LogicLib.nsh {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}, // FileFunc.nsh {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}, // Memento.nsh {regex: /\$\{(?:Memento(?:Section(?:Done|End|Restore|Save)?|UnselectedSection))\}/, token: "variable-2", dedent: true}, // TextFunc.nsh {regex: /\$\{(?:Config(?:Read|ReadS|Write|WriteS)|File(?:Join|ReadFromEnd|Recode)|Line(?:Find|Read|Sum)|Text(?:Compare|CompareS)|TrimNewLines)\}/, token: "variable-2", dedent: true}, // WinVer.nsh {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}, // WordFunc.nsh {regex: /\$\{(?:StrFilterS?|Version(?:Compare|Convert)|Word(?:AddS?|Find(?:(?:2|3)X)?S?|InsertS?|ReplaceS?))\}/, token: "variable-2", dedent: true}, // x64.nsh {regex: /\$\{(?:RunningX64)\}/, token: "variable", dedent: true}, {regex: /\$\{(?:Disable|Enable)X64FSRedirection\}/, token: "variable-2", dedent: true}, // Line Comment {regex: /(#|;).*/, token: "comment"}, // Block Comment {regex: /\/\*/, token: "comment", next: "comment"}, // Operator {regex: /[-+\/*=<>!]+/, token: "operator"}, // Variable {regex: /\$\w+/, token: "variable"}, // Constant {regex: /\${[\w\.:-]+}/, token: "variable-2"}, // Language String {regex: /\$\([\w\.:-]+\)/, token: "variable-3"} ], comment: [ {regex: /.*?\*\//, token: "comment", next: "start"}, {regex: /.*/, token: "comment"} ], meta: { electricInput: /^\s*((Function|PageEx|Section|Section(Group)?)End|(\!(endif|macroend))|\$\{(End(If|Unless|While)|Loop(Until)|Next)\})$/, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: ["#", ";"] } }); CodeMirror.defineMIME("text/x-nsis", "nsis"); }); ================================================ FILE: third_party/CodeMirror/mode/ntriples/index.html ================================================ CodeMirror: N-Triples mode

N-Triples mode

The N-Triples mode also works well with on N-Quad documents.

MIME types defined: application/n-triples.


N-Quads add a fourth element to the statement to track which graph the statement is from. Otherwise, it's identical to N-Triples.

MIME types defined: application/n-quads.

================================================ FILE: third_party/CodeMirror/mode/ntriples/ntriples.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /********************************************************** * This script provides syntax highlighting support for * the N-Triples format. * N-Triples format specification: * https://www.w3.org/TR/n-triples/ ***********************************************************/ /* The following expression defines the defined ASF grammar transitions. pre_subject -> { ( writing_subject_uri | writing_bnode_uri ) -> pre_predicate -> writing_predicate_uri -> pre_object -> writing_object_uri | writing_object_bnode | ( writing_object_literal -> writing_literal_lang | writing_literal_type ) -> post_object -> BEGIN } otherwise { -> ERROR } */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("ntriples", function() { var Location = { PRE_SUBJECT : 0, WRITING_SUB_URI : 1, WRITING_BNODE_URI : 2, PRE_PRED : 3, WRITING_PRED_URI : 4, PRE_OBJ : 5, WRITING_OBJ_URI : 6, WRITING_OBJ_BNODE : 7, WRITING_OBJ_LITERAL : 8, WRITING_LIT_LANG : 9, WRITING_LIT_TYPE : 10, POST_OBJ : 11, ERROR : 12 }; function transitState(currState, c) { var currLocation = currState.location; var ret; // Opening. if (currLocation == Location.PRE_SUBJECT && c == '<') ret = Location.WRITING_SUB_URI; else if(currLocation == Location.PRE_SUBJECT && c == '_') ret = Location.WRITING_BNODE_URI; else if(currLocation == Location.PRE_PRED && c == '<') ret = Location.WRITING_PRED_URI; else if(currLocation == Location.PRE_OBJ && c == '<') ret = Location.WRITING_OBJ_URI; else if(currLocation == Location.PRE_OBJ && c == '_') ret = Location.WRITING_OBJ_BNODE; else if(currLocation == Location.PRE_OBJ && c == '"') ret = Location.WRITING_OBJ_LITERAL; // Closing. else if(currLocation == Location.WRITING_SUB_URI && c == '>') ret = Location.PRE_PRED; else if(currLocation == Location.WRITING_BNODE_URI && c == ' ') ret = Location.PRE_PRED; else if(currLocation == Location.WRITING_PRED_URI && c == '>') ret = Location.PRE_OBJ; else if(currLocation == Location.WRITING_OBJ_URI && c == '>') ret = Location.POST_OBJ; else if(currLocation == Location.WRITING_OBJ_BNODE && c == ' ') ret = Location.POST_OBJ; else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '"') ret = Location.POST_OBJ; else if(currLocation == Location.WRITING_LIT_LANG && c == ' ') ret = Location.POST_OBJ; else if(currLocation == Location.WRITING_LIT_TYPE && c == '>') ret = Location.POST_OBJ; // Closing typed and language literal. else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '@') ret = Location.WRITING_LIT_LANG; else if(currLocation == Location.WRITING_OBJ_LITERAL && c == '^') ret = Location.WRITING_LIT_TYPE; // Spaces. else if( c == ' ' && ( currLocation == Location.PRE_SUBJECT || currLocation == Location.PRE_PRED || currLocation == Location.PRE_OBJ || currLocation == Location.POST_OBJ ) ) ret = currLocation; // Reset. else if(currLocation == Location.POST_OBJ && c == '.') ret = Location.PRE_SUBJECT; // Error else ret = Location.ERROR; currState.location=ret; } return { startState: function() { return { location : Location.PRE_SUBJECT, uris : [], anchors : [], bnodes : [], langs : [], types : [] }; }, token: function(stream, state) { var ch = stream.next(); if(ch == '<') { transitState(state, ch); var parsedURI = ''; stream.eatWhile( function(c) { if( c != '#' && c != '>' ) { parsedURI += c; return true; } return false;} ); state.uris.push(parsedURI); if( stream.match('#', false) ) return 'variable'; stream.next(); transitState(state, '>'); return 'variable'; } if(ch == '#') { var parsedAnchor = ''; stream.eatWhile(function(c) { if(c != '>' && c != ' ') { parsedAnchor+= c; return true; } return false;}); state.anchors.push(parsedAnchor); return 'variable-2'; } if(ch == '>') { transitState(state, '>'); return 'variable'; } if(ch == '_') { transitState(state, ch); var parsedBNode = ''; stream.eatWhile(function(c) { if( c != ' ' ) { parsedBNode += c; return true; } return false;}); state.bnodes.push(parsedBNode); stream.next(); transitState(state, ' '); return 'builtin'; } if(ch == '"') { transitState(state, ch); stream.eatWhile( function(c) { return c != '"'; } ); stream.next(); if( stream.peek() != '@' && stream.peek() != '^' ) { transitState(state, '"'); } return 'string'; } if( ch == '@' ) { transitState(state, '@'); var parsedLang = ''; stream.eatWhile(function(c) { if( c != ' ' ) { parsedLang += c; return true; } return false;}); state.langs.push(parsedLang); stream.next(); transitState(state, ' '); return 'string-2'; } if( ch == '^' ) { stream.next(); transitState(state, '^'); var parsedType = ''; stream.eatWhile(function(c) { if( c != '>' ) { parsedType += c; return true; } return false;} ); state.types.push(parsedType); stream.next(); transitState(state, '>'); return 'variable'; } if( ch == ' ' ) { transitState(state, ch); } if( ch == '.' ) { transitState(state, ch); } } }; }); // define the registered Media Type for n-triples: // https://www.w3.org/TR/n-triples/#n-triples-mediatype CodeMirror.defineMIME("application/n-triples", "ntriples"); // N-Quads is based on the N-Triples format (so same highlighting works) // https://www.w3.org/TR/n-quads/ CodeMirror.defineMIME("application/n-quads", "ntriples"); // previously used, though technically incorrect media type for n-triples CodeMirror.defineMIME("text/n-triples", "ntriples"); }); ================================================ FILE: third_party/CodeMirror/mode/octave/index.html ================================================ CodeMirror: Octave mode

Octave mode

MIME types defined: text/x-octave.

================================================ FILE: third_party/CodeMirror/mode/octave/octave.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("octave", function() { function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); } var singleOperators = new RegExp("^[\\+\\-\\*/&|\\^~<>!@'\\\\]"); var singleDelimiters = new RegExp('^[\\(\\[\\{\\},:=;]'); var doubleOperators = new RegExp("^((==)|(~=)|(<=)|(>=)|(<<)|(>>)|(\\.[\\+\\-\\*/\\^\\\\]))"); var doubleDelimiters = new RegExp("^((!=)|(\\+=)|(\\-=)|(\\*=)|(/=)|(&=)|(\\|=)|(\\^=))"); var tripleDelimiters = new RegExp("^((>>=)|(<<=))"); var expressionEnd = new RegExp("^[\\]\\)]"); var identifiers = new RegExp("^[_A-Za-z\xa1-\uffff][_A-Za-z0-9\xa1-\uffff]*"); var builtins = wordRegexp([ 'error', 'eval', 'function', 'abs', 'acos', 'atan', 'asin', 'cos', 'cosh', 'exp', 'log', 'prod', 'sum', 'log10', 'max', 'min', 'sign', 'sin', 'sinh', 'sqrt', 'tan', 'reshape', 'break', 'zeros', 'default', 'margin', 'round', 'ones', 'rand', 'syn', 'ceil', 'floor', 'size', 'clear', 'zeros', 'eye', 'mean', 'std', 'cov', 'det', 'eig', 'inv', 'norm', 'rank', 'trace', 'expm', 'logm', 'sqrtm', 'linspace', 'plot', 'title', 'xlabel', 'ylabel', 'legend', 'text', 'grid', 'meshgrid', 'mesh', 'num2str', 'fft', 'ifft', 'arrayfun', 'cellfun', 'input', 'fliplr', 'flipud', 'ismember' ]); var keywords = wordRegexp([ 'return', 'case', 'switch', 'else', 'elseif', 'end', 'endif', 'endfunction', 'if', 'otherwise', 'do', 'for', 'while', 'try', 'catch', 'classdef', 'properties', 'events', 'methods', 'global', 'persistent', 'endfor', 'endwhile', 'printf', 'sprintf', 'disp', 'until', 'continue', 'pkg' ]); // tokenizers function tokenTranspose(stream, state) { if (!stream.sol() && stream.peek() === '\'') { stream.next(); state.tokenize = tokenBase; return 'operator'; } state.tokenize = tokenBase; return tokenBase(stream, state); } function tokenComment(stream, state) { if (stream.match(/^.*%}/)) { state.tokenize = tokenBase; return 'comment'; }; stream.skipToEnd(); return 'comment'; } function tokenBase(stream, state) { // whitespaces if (stream.eatSpace()) return null; // Handle one line Comments if (stream.match('%{')){ state.tokenize = tokenComment; stream.skipToEnd(); return 'comment'; } if (stream.match(/^[%#]/)){ stream.skipToEnd(); return 'comment'; } // Handle Number Literals if (stream.match(/^[0-9\.+-]/, false)) { if (stream.match(/^[+-]?0x[0-9a-fA-F]+[ij]?/)) { stream.tokenize = tokenBase; return 'number'; }; if (stream.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?[ij]?/)) { return 'number'; }; if (stream.match(/^[+-]?\d+([EeDd][+-]?\d+)?[ij]?/)) { return 'number'; }; } if (stream.match(wordRegexp(['nan','NaN','inf','Inf']))) { return 'number'; }; // Handle Strings var m = stream.match(/^"(?:[^"]|"")*("|$)/) || stream.match(/^'(?:[^']|'')*('|$)/) if (m) { return m[1] ? 'string' : "string error"; } // Handle words if (stream.match(keywords)) { return 'keyword'; } ; if (stream.match(builtins)) { return 'builtin'; } ; if (stream.match(identifiers)) { return 'variable'; } ; if (stream.match(singleOperators) || stream.match(doubleOperators)) { return 'operator'; }; if (stream.match(singleDelimiters) || stream.match(doubleDelimiters) || stream.match(tripleDelimiters)) { return null; }; if (stream.match(expressionEnd)) { state.tokenize = tokenTranspose; return null; }; // Handle non-detected items stream.next(); return 'error'; }; return { startState: function() { return { tokenize: tokenBase }; }, token: function(stream, state) { var style = state.tokenize(stream, state); if (style === 'number' || style === 'variable'){ state.tokenize = tokenTranspose; } return style; }, lineComment: '%', fold: 'indent' }; }); CodeMirror.defineMIME("text/x-octave", "octave"); }); ================================================ FILE: third_party/CodeMirror/mode/oz/index.html ================================================ CodeMirror: Oz mode

Oz mode

MIME type defined: text/x-oz.

================================================ FILE: third_party/CodeMirror/mode/oz/oz.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("oz", function (conf) { function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); } var singleOperators = /[\^@!\|<>#~\.\*\-\+\\/,=]/; var doubleOperators = /(<-)|(:=)|(=<)|(>=)|(<=)|(<:)|(>:)|(=:)|(\\=)|(\\=:)|(!!)|(==)|(::)/; var tripleOperators = /(:::)|(\.\.\.)|(=<:)|(>=:)/; var middle = ["in", "then", "else", "of", "elseof", "elsecase", "elseif", "catch", "finally", "with", "require", "prepare", "import", "export", "define", "do"]; var end = ["end"]; var atoms = wordRegexp(["true", "false", "nil", "unit"]); var commonKeywords = wordRegexp(["andthen", "at", "attr", "declare", "feat", "from", "lex", "mod", "div", "mode", "orelse", "parser", "prod", "prop", "scanner", "self", "syn", "token"]); var openingKeywords = wordRegexp(["local", "proc", "fun", "case", "class", "if", "cond", "or", "dis", "choice", "not", "thread", "try", "raise", "lock", "for", "suchthat", "meth", "functor"]); var middleKeywords = wordRegexp(middle); var endKeywords = wordRegexp(end); // Tokenizers function tokenBase(stream, state) { if (stream.eatSpace()) { return null; } // Brackets if(stream.match(/[{}]/)) { return "bracket"; } // Special [] keyword if (stream.match(/(\[])/)) { return "keyword" } // Operators if (stream.match(tripleOperators) || stream.match(doubleOperators)) { return "operator"; } // Atoms if(stream.match(atoms)) { return 'atom'; } // Opening keywords var matched = stream.match(openingKeywords); if (matched) { if (!state.doInCurrentLine) state.currentIndent++; else state.doInCurrentLine = false; // Special matching for signatures if(matched[0] == "proc" || matched[0] == "fun") state.tokenize = tokenFunProc; else if(matched[0] == "class") state.tokenize = tokenClass; else if(matched[0] == "meth") state.tokenize = tokenMeth; return 'keyword'; } // Middle and other keywords if (stream.match(middleKeywords) || stream.match(commonKeywords)) { return "keyword" } // End keywords if (stream.match(endKeywords)) { state.currentIndent--; return 'keyword'; } // Eat the next char for next comparisons var ch = stream.next(); // Strings if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } // Numbers if (/[~\d]/.test(ch)) { if (ch == "~") { if(! /^[0-9]/.test(stream.peek())) return null; else if (( stream.next() == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || stream.match(/^[0-9]*(\.[0-9]+)?([eE][~+]?[0-9]+)?/)) return "number"; } if ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || stream.match(/^[0-9]*(\.[0-9]+)?([eE][~+]?[0-9]+)?/)) return "number"; return null; } // Comments if (ch == "%") { stream.skipToEnd(); return 'comment'; } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } } // Single operators if(singleOperators.test(ch)) { return "operator"; } // If nothing match, we skip the entire alphanumerical block stream.eatWhile(/\w/); return "variable"; } function tokenClass(stream, state) { if (stream.eatSpace()) { return null; } stream.match(/([A-Z][A-Za-z0-9_]*)|(`.+`)/); state.tokenize = tokenBase; return "variable-3" } function tokenMeth(stream, state) { if (stream.eatSpace()) { return null; } stream.match(/([a-zA-Z][A-Za-z0-9_]*)|(`.+`)/); state.tokenize = tokenBase; return "def" } function tokenFunProc(stream, state) { if (stream.eatSpace()) { return null; } if(!state.hasPassedFirstStage && stream.eat("{")) { state.hasPassedFirstStage = true; return "bracket"; } else if(state.hasPassedFirstStage) { stream.match(/([A-Z][A-Za-z0-9_]*)|(`.+`)|\$/); state.hasPassedFirstStage = false; state.tokenize = tokenBase; return "def" } else { state.tokenize = tokenBase; return null; } } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenString(quote) { return function (stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) { end = true; break; } escaped = !escaped && next == "\\"; } if (end || !escaped) state.tokenize = tokenBase; return "string"; }; } function buildElectricInputRegEx() { // Reindentation should occur on [] or on a match of any of // the block closing keywords, at the end of a line. var allClosings = middle.concat(end); return new RegExp("[\\[\\]]|(" + allClosings.join("|") + ")$"); } return { startState: function () { return { tokenize: tokenBase, currentIndent: 0, doInCurrentLine: false, hasPassedFirstStage: false }; }, token: function (stream, state) { if (stream.sol()) state.doInCurrentLine = 0; return state.tokenize(stream, state); }, indent: function (state, textAfter) { var trueText = textAfter.replace(/^\s+|\s+$/g, ''); if (trueText.match(endKeywords) || trueText.match(middleKeywords) || trueText.match(/(\[])/)) return conf.indentUnit * (state.currentIndent - 1); if (state.currentIndent < 0) return 0; return state.currentIndent * conf.indentUnit; }, fold: "indent", electricInput: buildElectricInputRegEx(), lineComment: "%", blockCommentStart: "/*", blockCommentEnd: "*/" }; }); CodeMirror.defineMIME("text/x-oz", "oz"); }); ================================================ FILE: third_party/CodeMirror/mode/pascal/index.html ================================================ CodeMirror: Pascal mode

Pascal mode

MIME types defined: text/x-pascal.

================================================ FILE: third_party/CodeMirror/mode/pascal/pascal.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pascal", function() { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = words( "absolute and array asm begin case const constructor destructor div do " + "downto else end file for function goto if implementation in inherited " + "inline interface label mod nil not object of operator or packed procedure " + "program record reintroduce repeat self set shl shr string then to type " + "unit until uses var while with xor as class dispinterface except exports " + "finalization finally initialization inline is library on out packed " + "property raise resourcestring threadvar try absolute abstract alias " + "assembler bitpacked break cdecl continue cppdecl cvar default deprecated " + "dynamic enumerator experimental export external far far16 forward generic " + "helper implements index interrupt iocheck local message name near " + "nodefault noreturn nostackframe oldfpccall otherwise overload override " + "pascal platform private protected public published read register " + "reintroduce result safecall saveregisters softfloat specialize static " + "stdcall stored strict unaligned unimplemented varargs virtual write"); var atoms = {"null": true}; var isOperatorChar = /[+\-*&%=<>!?|\/]/; function tokenBase(stream, state) { var ch = stream.next(); if (ch == "#" && state.startOfLine) { stream.skipToEnd(); return "meta"; } if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (ch == "(" && stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return null; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (ch == "/") { if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) return "keyword"; if (atoms.propertyIsEnumerable(cur)) return "atom"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !escaped) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == ")" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } // Interface return { startState: function() { return {tokenize: null}; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta") return style; return style; }, electricChars: "{}" }; }); CodeMirror.defineMIME("text/x-pascal", "pascal"); }); ================================================ FILE: third_party/CodeMirror/mode/pegjs/index.html ================================================ CodeMirror: PEG.js Mode

PEG.js Mode

The PEG.js Mode

Created by Forbes Lindesay.

================================================ FILE: third_party/CodeMirror/mode/pegjs/pegjs.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../javascript/javascript")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../javascript/javascript"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pegjs", function (config) { var jsMode = CodeMirror.getMode(config, "javascript"); function identifier(stream) { return stream.match(/^[a-zA-Z_][a-zA-Z0-9_]*/); } return { startState: function () { return { inString: false, stringType: null, inComment: false, inCharacterClass: false, braced: 0, lhs: true, localState: null }; }, token: function (stream, state) { if (stream) //check for state changes if (!state.inString && !state.inComment && ((stream.peek() == '"') || (stream.peek() == "'"))) { state.stringType = stream.peek(); stream.next(); // Skip quote state.inString = true; // Update state } if (!state.inString && !state.inComment && stream.match(/^\/\*/)) { state.inComment = true; } //return state if (state.inString) { while (state.inString && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.inString = false; // Clear flag } else if (stream.peek() === '\\') { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return state.lhs ? "property string" : "string"; // Token style } else if (state.inComment) { while (state.inComment && !stream.eol()) { if (stream.match(/\*\//)) { state.inComment = false; // Clear flag } else { stream.match(/^.[^\*]*/); } } return "comment"; } else if (state.inCharacterClass) { while (state.inCharacterClass && !stream.eol()) { if (!(stream.match(/^[^\]\\]+/) || stream.match(/^\\./))) { state.inCharacterClass = false; } } } else if (stream.peek() === '[') { stream.next(); state.inCharacterClass = true; return 'bracket'; } else if (stream.match(/^\/\//)) { stream.skipToEnd(); return "comment"; } else if (state.braced || stream.peek() === '{') { if (state.localState === null) { state.localState = CodeMirror.startState(jsMode); } var token = jsMode.token(stream, state.localState); var text = stream.current(); if (!token) { for (var i = 0; i < text.length; i++) { if (text[i] === '{') { state.braced++; } else if (text[i] === '}') { state.braced--; } }; } return token; } else if (identifier(stream)) { if (stream.peek() === ':') { return 'variable'; } return 'variable-2'; } else if (['[', ']', '(', ')'].indexOf(stream.peek()) != -1) { stream.next(); return 'bracket'; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }, "javascript"); }); ================================================ FILE: third_party/CodeMirror/mode/perl/index.html ================================================ CodeMirror: Perl mode

Perl mode

MIME types defined: text/x-perl.

================================================ FILE: third_party/CodeMirror/mode/perl/perl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // CodeMirror2 mode/perl/perl.js (text/x-perl) beta 0.10 (2011-11-08) // This is a part of CodeMirror from https://github.com/sabaca/CodeMirror_mode_perl (mail@sabaca.com) (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("perl",function(){ // http://perldoc.perl.org var PERL={ // null - magic touch // 1 - keyword // 2 - def // 3 - atom // 4 - operator // 5 - variable-2 (predefined) // [x,y] - x=1,2,3; y=must be defined if x{...} // PERL operators '->' : 4, '++' : 4, '--' : 4, '**' : 4, // ! ~ \ and unary + and - '=~' : 4, '!~' : 4, '*' : 4, '/' : 4, '%' : 4, 'x' : 4, '+' : 4, '-' : 4, '.' : 4, '<<' : 4, '>>' : 4, // named unary operators '<' : 4, '>' : 4, '<=' : 4, '>=' : 4, 'lt' : 4, 'gt' : 4, 'le' : 4, 'ge' : 4, '==' : 4, '!=' : 4, '<=>' : 4, 'eq' : 4, 'ne' : 4, 'cmp' : 4, '~~' : 4, '&' : 4, '|' : 4, '^' : 4, '&&' : 4, '||' : 4, '//' : 4, '..' : 4, '...' : 4, '?' : 4, ':' : 4, '=' : 4, '+=' : 4, '-=' : 4, '*=' : 4, // etc. ??? ',' : 4, '=>' : 4, '::' : 4, // list operators (rightward) 'not' : 4, 'and' : 4, 'or' : 4, 'xor' : 4, // 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?;) 'BEGIN' : [5,1], 'END' : [5,1], 'PRINT' : [5,1], 'PRINTF' : [5,1], 'GETC' : [5,1], 'READ' : [5,1], 'READLINE' : [5,1], 'DESTROY' : [5,1], 'TIE' : [5,1], 'TIEHANDLE' : [5,1], 'UNTIE' : [5,1], 'STDIN' : 5, 'STDIN_TOP' : 5, 'STDOUT' : 5, 'STDOUT_TOP' : 5, 'STDERR' : 5, 'STDERR_TOP' : 5, '$ARG' : 5, '$_' : 5, '@ARG' : 5, '@_' : 5, '$LIST_SEPARATOR' : 5, '$"' : 5, '$PROCESS_ID' : 5, '$PID' : 5, '$$' : 5, '$REAL_GROUP_ID' : 5, '$GID' : 5, '$(' : 5, '$EFFECTIVE_GROUP_ID' : 5, '$EGID' : 5, '$)' : 5, '$PROGRAM_NAME' : 5, '$0' : 5, '$SUBSCRIPT_SEPARATOR' : 5, '$SUBSEP' : 5, '$;' : 5, '$REAL_USER_ID' : 5, '$UID' : 5, '$<' : 5, '$EFFECTIVE_USER_ID' : 5, '$EUID' : 5, '$>' : 5, '$a' : 5, '$b' : 5, '$COMPILING' : 5, '$^C' : 5, '$DEBUGGING' : 5, '$^D' : 5, '${^ENCODING}' : 5, '$ENV' : 5, '%ENV' : 5, '$SYSTEM_FD_MAX' : 5, '$^F' : 5, '@F' : 5, '${^GLOBAL_PHASE}' : 5, '$^H' : 5, '%^H' : 5, '@INC' : 5, '%INC' : 5, '$INPLACE_EDIT' : 5, '$^I' : 5, '$^M' : 5, '$OSNAME' : 5, '$^O' : 5, '${^OPEN}' : 5, '$PERLDB' : 5, '$^P' : 5, '$SIG' : 5, '%SIG' : 5, '$BASETIME' : 5, '$^T' : 5, '${^TAINT}' : 5, '${^UNICODE}' : 5, '${^UTF8CACHE}' : 5, '${^UTF8LOCALE}' : 5, '$PERL_VERSION' : 5, '$^V' : 5, '${^WIN32_SLOPPY_STAT}' : 5, '$EXECUTABLE_NAME' : 5, '$^X' : 5, '$1' : 5, // - regexp $1, $2... '$MATCH' : 5, '$&' : 5, '${^MATCH}' : 5, '$PREMATCH' : 5, '$`' : 5, '${^PREMATCH}' : 5, '$POSTMATCH' : 5, "$'" : 5, '${^POSTMATCH}' : 5, '$LAST_PAREN_MATCH' : 5, '$+' : 5, '$LAST_SUBMATCH_RESULT' : 5, '$^N' : 5, '@LAST_MATCH_END' : 5, '@+' : 5, '%LAST_PAREN_MATCH' : 5, '%+' : 5, '@LAST_MATCH_START' : 5, '@-' : 5, '%LAST_MATCH_START' : 5, '%-' : 5, '$LAST_REGEXP_CODE_RESULT' : 5, '$^R' : 5, '${^RE_DEBUG_FLAGS}' : 5, '${^RE_TRIE_MAXBUF}' : 5, '$ARGV' : 5, '@ARGV' : 5, 'ARGV' : 5, 'ARGVOUT' : 5, '$OUTPUT_FIELD_SEPARATOR' : 5, '$OFS' : 5, '$,' : 5, '$INPUT_LINE_NUMBER' : 5, '$NR' : 5, '$.' : 5, '$INPUT_RECORD_SEPARATOR' : 5, '$RS' : 5, '$/' : 5, '$OUTPUT_RECORD_SEPARATOR' : 5, '$ORS' : 5, '$\\' : 5, '$OUTPUT_AUTOFLUSH' : 5, '$|' : 5, '$ACCUMULATOR' : 5, '$^A' : 5, '$FORMAT_FORMFEED' : 5, '$^L' : 5, '$FORMAT_PAGE_NUMBER' : 5, '$%' : 5, '$FORMAT_LINES_LEFT' : 5, '$-' : 5, '$FORMAT_LINE_BREAK_CHARACTERS' : 5, '$:' : 5, '$FORMAT_LINES_PER_PAGE' : 5, '$=' : 5, '$FORMAT_TOP_NAME' : 5, '$^' : 5, '$FORMAT_NAME' : 5, '$~' : 5, '${^CHILD_ERROR_NATIVE}' : 5, '$EXTENDED_OS_ERROR' : 5, '$^E' : 5, '$EXCEPTIONS_BEING_CAUGHT' : 5, '$^S' : 5, '$WARNING' : 5, '$^W' : 5, '${^WARNING_BITS}' : 5, '$OS_ERROR' : 5, '$ERRNO' : 5, '$!' : 5, '%OS_ERROR' : 5, '%ERRNO' : 5, '%!' : 5, '$CHILD_ERROR' : 5, '$?' : 5, '$EVAL_ERROR' : 5, '$@' : 5, '$OFMT' : 5, '$#' : 5, '$*' : 5, '$ARRAY_BASE' : 5, '$[' : 5, '$OLD_PERL_VERSION' : 5, '$]' : 5, // PERL blocks 'if' :[1,1], elsif :[1,1], 'else' :[1,1], 'while' :[1,1], unless :[1,1], 'for' :[1,1], foreach :[1,1], // PERL functions 'abs' :1, // - absolute value function accept :1, // - accept an incoming socket connect alarm :1, // - schedule a SIGALRM 'atan2' :1, // - arctangent of Y/X in the range -PI to PI bind :1, // - binds an address to a socket binmode :1, // - prepare binary files for I/O bless :1, // - create an object bootstrap :1, // 'break' :1, // - break out of a "given" block caller :1, // - get context of the current subroutine call chdir :1, // - change your current working directory chmod :1, // - changes the permissions on a list of files chomp :1, // - remove a trailing record separator from a string chop :1, // - remove the last character from a string chown :1, // - change the ownership on a list of files chr :1, // - get character this number represents chroot :1, // - make directory new root for path lookups close :1, // - close file (or pipe or socket) handle closedir :1, // - close directory handle connect :1, // - connect to a remote socket 'continue' :[1,1], // - optional trailing block in a while or foreach 'cos' :1, // - cosine function crypt :1, // - one-way passwd-style encryption dbmclose :1, // - breaks binding on a tied dbm file dbmopen :1, // - create binding on a tied dbm file 'default' :1, // defined :1, // - test whether a value, variable, or function is defined 'delete' :1, // - deletes a value from a hash die :1, // - raise an exception or bail out 'do' :1, // - turn a BLOCK into a TERM dump :1, // - create an immediate core dump each :1, // - retrieve the next key/value pair from a hash endgrent :1, // - be done using group file endhostent :1, // - be done using hosts file endnetent :1, // - be done using networks file endprotoent :1, // - be done using protocols file endpwent :1, // - be done using passwd file endservent :1, // - be done using services file eof :1, // - test a filehandle for its end 'eval' :1, // - catch exceptions or compile and run code 'exec' :1, // - abandon this program to run another exists :1, // - test whether a hash key is present exit :1, // - terminate this program 'exp' :1, // - raise I to a power fcntl :1, // - file control system call fileno :1, // - return file descriptor from filehandle flock :1, // - lock an entire file with an advisory lock fork :1, // - create a new process just like this one format :1, // - declare a picture format with use by the write() function formline :1, // - internal function used for formats getc :1, // - get the next character from the filehandle getgrent :1, // - get next group record getgrgid :1, // - get group record given group user ID getgrnam :1, // - get group record given group name gethostbyaddr :1, // - get host record given its address gethostbyname :1, // - get host record given name gethostent :1, // - get next hosts record getlogin :1, // - return who logged in at this tty getnetbyaddr :1, // - get network record given its address getnetbyname :1, // - get networks record given name getnetent :1, // - get next networks record getpeername :1, // - find the other end of a socket connection getpgrp :1, // - get process group getppid :1, // - get parent process ID getpriority :1, // - get current nice value getprotobyname :1, // - get protocol record given name getprotobynumber :1, // - get protocol record numeric protocol getprotoent :1, // - get next protocols record getpwent :1, // - get next passwd record getpwnam :1, // - get passwd record given user login name getpwuid :1, // - get passwd record given user ID getservbyname :1, // - get services record given its name getservbyport :1, // - get services record given numeric port getservent :1, // - get next services record getsockname :1, // - retrieve the sockaddr for a given socket getsockopt :1, // - get socket options on a given socket given :1, // glob :1, // - expand filenames using wildcards gmtime :1, // - convert UNIX time into record or string using Greenwich time 'goto' :1, // - create spaghetti code grep :1, // - locate elements in a list test true against a given criterion hex :1, // - convert a string to a hexadecimal number 'import' :1, // - patch a module's namespace into your own index :1, // - find a substring within a string 'int' :1, // - get the integer portion of a number ioctl :1, // - system-dependent device control system call 'join' :1, // - join a list into a string using a separator keys :1, // - retrieve list of indices from a hash kill :1, // - send a signal to a process or process group last :1, // - exit a block prematurely lc :1, // - return lower-case version of a string lcfirst :1, // - return a string with just the next letter in lower case length :1, // - return the number of bytes in a string 'link' :1, // - create a hard link in the filesytem listen :1, // - register your socket as a server local : 2, // - create a temporary value for a global variable (dynamic scoping) localtime :1, // - convert UNIX time into record or string using local time lock :1, // - get a thread lock on a variable, subroutine, or method 'log' :1, // - retrieve the natural logarithm for a number lstat :1, // - stat a symbolic link m :null, // - match a string with a regular expression pattern map :1, // - apply a change to a list to get back a new list with the changes mkdir :1, // - create a directory msgctl :1, // - SysV IPC message control operations msgget :1, // - get SysV IPC message queue msgrcv :1, // - receive a SysV IPC message from a message queue msgsnd :1, // - send a SysV IPC message to a message queue my : 2, // - declare and assign a local variable (lexical scoping) 'new' :1, // next :1, // - iterate a block prematurely no :1, // - unimport some module symbols or semantics at compile time oct :1, // - convert a string to an octal number open :1, // - open a file, pipe, or descriptor opendir :1, // - open a directory ord :1, // - find a character's numeric representation our : 2, // - declare and assign a package variable (lexical scoping) pack :1, // - convert a list into a binary representation 'package' :1, // - declare a separate global namespace pipe :1, // - open a pair of connected filehandles pop :1, // - remove the last element from an array and return it pos :1, // - find or set the offset for the last/next m//g search print :1, // - output a list to a filehandle printf :1, // - output a formatted list to a filehandle prototype :1, // - get the prototype (if any) of a subroutine push :1, // - append one or more elements to an array q :null, // - singly quote a string qq :null, // - doubly quote a string qr :null, // - Compile pattern quotemeta :null, // - quote regular expression magic characters qw :null, // - quote a list of words qx :null, // - backquote quote a string rand :1, // - retrieve the next pseudorandom number read :1, // - fixed-length buffered input from a filehandle readdir :1, // - get a directory from a directory handle readline :1, // - fetch a record from a file readlink :1, // - determine where a symbolic link is pointing readpipe :1, // - execute a system command and collect standard output recv :1, // - receive a message over a Socket redo :1, // - start this loop iteration over again ref :1, // - find out the type of thing being referenced rename :1, // - change a filename require :1, // - load in external functions from a library at runtime reset :1, // - clear all variables of a given name 'return' :1, // - get out of a function early reverse :1, // - flip a string or a list rewinddir :1, // - reset directory handle rindex :1, // - right-to-left substring search rmdir :1, // - remove a directory s :null, // - replace a pattern with a string say :1, // - print with newline scalar :1, // - force a scalar context seek :1, // - reposition file pointer for random-access I/O seekdir :1, // - reposition directory pointer select :1, // - reset default output or do I/O multiplexing semctl :1, // - SysV semaphore control operations semget :1, // - get set of SysV semaphores semop :1, // - SysV semaphore operations send :1, // - send a message over a socket setgrent :1, // - prepare group file for use sethostent :1, // - prepare hosts file for use setnetent :1, // - prepare networks file for use setpgrp :1, // - set the process group of a process setpriority :1, // - set a process's nice value setprotoent :1, // - prepare protocols file for use setpwent :1, // - prepare passwd file for use setservent :1, // - prepare services file for use setsockopt :1, // - set some socket options shift :1, // - remove the first element of an array, and return it shmctl :1, // - SysV shared memory operations shmget :1, // - get SysV shared memory segment identifier shmread :1, // - read SysV shared memory shmwrite :1, // - write SysV shared memory shutdown :1, // - close down just half of a socket connection 'sin' :1, // - return the sine of a number sleep :1, // - block for some number of seconds socket :1, // - create a socket socketpair :1, // - create a pair of sockets 'sort' :1, // - sort a list of values splice :1, // - add or remove elements anywhere in an array 'split' :1, // - split up a string using a regexp delimiter sprintf :1, // - formatted print into a string 'sqrt' :1, // - square root function srand :1, // - seed the random number generator stat :1, // - get a file's status information state :1, // - declare and assign a state variable (persistent lexical scoping) study :1, // - optimize input data for repeated searches 'sub' :1, // - declare a subroutine, possibly anonymously 'substr' :1, // - get or alter a portion of a stirng symlink :1, // - create a symbolic link to a file syscall :1, // - execute an arbitrary system call sysopen :1, // - open a file, pipe, or descriptor sysread :1, // - fixed-length unbuffered input from a filehandle sysseek :1, // - position I/O pointer on handle used with sysread and syswrite system :1, // - run a separate program syswrite :1, // - fixed-length unbuffered output to a filehandle tell :1, // - get current seekpointer on a filehandle telldir :1, // - get current seekpointer on a directory handle tie :1, // - bind a variable to an object class tied :1, // - get a reference to the object underlying a tied variable time :1, // - return number of seconds since 1970 times :1, // - return elapsed time for self and child processes tr :null, // - transliterate a string truncate :1, // - shorten a file uc :1, // - return upper-case version of a string ucfirst :1, // - return a string with just the next letter in upper case umask :1, // - set file creation mode mask undef :1, // - remove a variable or function definition unlink :1, // - remove one link to a file unpack :1, // - convert binary structure into normal perl variables unshift :1, // - prepend more elements to the beginning of a list untie :1, // - break a tie binding to a variable use :1, // - load in a module at compile time utime :1, // - set a file's last access and modify times values :1, // - return a list of the values in a hash vec :1, // - test or set particular bits in a string wait :1, // - wait for any child process to die waitpid :1, // - wait for a particular child process to die wantarray :1, // - get void vs scalar vs list context of current subroutine call warn :1, // - print debugging info when :1, // write :1, // - print a picture record y :null}; // - transliterate a string var RXstyle="string-2"; var RXmodifiers=/[goseximacplud]/; // NOTE: "m", "s", "y" and "tr" need to correct real modifiers for each regexp type function tokenChain(stream,state,chain,style,tail){ // NOTE: chain.length > 2 is not working now (it's for s[...][...]geos;) state.chain=null; // 12 3tail state.style=null; state.tail=null; state.tokenize=function(stream,state){ var e=false,c,i=0; while(c=stream.next()){ if(c===chain[i]&&!e){ if(chain[++i]!==undefined){ state.chain=chain[i]; state.style=style; state.tail=tail;} else if(tail) stream.eatWhile(tail); state.tokenize=tokenPerl; return style;} e=!e&&c=="\\";} return style;}; return state.tokenize(stream,state);} function tokenSOMETHING(stream,state,string){ state.tokenize=function(stream,state){ if(stream.string==string) state.tokenize=tokenPerl; stream.skipToEnd(); return "string";}; return state.tokenize(stream,state);} function tokenPerl(stream,state){ if(stream.eatSpace()) return null; if(state.chain) return tokenChain(stream,state,state.chain,state.style,state.tail); if(stream.match(/^\-?[\d\.]/,false)) if(stream.match(/^(\-?(\d*\.\d+(e[+-]?\d+)?|\d+\.\d*)|0x[\da-fA-F]+|0b[01]+|\d+(e[+-]?\d+)?)/)) return 'number'; if(stream.match(/^<<(?=\w)/)){ // NOTE: <"],RXstyle,RXmodifiers);} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}} else if(c=="q"){ c=look(stream, 1); if(c=="("){ eatSuffix(stream, 2); return tokenChain(stream,state,[")"],"string");} if(c=="["){ eatSuffix(stream, 2); return tokenChain(stream,state,["]"],"string");} if(c=="{"){ eatSuffix(stream, 2); return tokenChain(stream,state,["}"],"string");} if(c=="<"){ eatSuffix(stream, 2); return tokenChain(stream,state,[">"],"string");} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],"string");}} else if(c=="w"){ c=look(stream, 1); if(c=="("){ eatSuffix(stream, 2); return tokenChain(stream,state,[")"],"bracket");} if(c=="["){ eatSuffix(stream, 2); return tokenChain(stream,state,["]"],"bracket");} if(c=="{"){ eatSuffix(stream, 2); return tokenChain(stream,state,["}"],"bracket");} if(c=="<"){ eatSuffix(stream, 2); return tokenChain(stream,state,[">"],"bracket");} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],"bracket");}} else if(c=="r"){ c=look(stream, 1); if(c=="("){ eatSuffix(stream, 2); return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);} if(c=="["){ eatSuffix(stream, 2); return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);} if(c=="{"){ eatSuffix(stream, 2); return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);} if(c=="<"){ eatSuffix(stream, 2); return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);} if(/[\^'"!~\/]/.test(c)){ eatSuffix(stream, 1); return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}} else if(/[\^'"!~\/(\[{<]/.test(c)){ if(c=="("){ eatSuffix(stream, 1); return tokenChain(stream,state,[")"],"string");} if(c=="["){ eatSuffix(stream, 1); return tokenChain(stream,state,["]"],"string");} if(c=="{"){ eatSuffix(stream, 1); return tokenChain(stream,state,["}"],"string");} if(c=="<"){ eatSuffix(stream, 1); return tokenChain(stream,state,[">"],"string");} if(/[\^'"!~\/]/.test(c)){ return tokenChain(stream,state,[stream.eat(c)],"string");}}}} if(ch=="m"){ var c=look(stream, -2); if(!(c&&/\w/.test(c))){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(/[\^'"!~\/]/.test(c)){ return tokenChain(stream,state,[c],RXstyle,RXmodifiers);} if(c=="("){ return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);} if(c=="["){ return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);} if(c=="{"){ return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);} if(c=="<"){ return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);}}}} if(ch=="s"){ var c=/[\/>\]})\w]/.test(look(stream, -2)); if(!c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}} if(ch=="y"){ var c=/[\/>\]})\w]/.test(look(stream, -2)); if(!c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}} if(ch=="t"){ var c=/[\/>\]})\w]/.test(look(stream, -2)); if(!c){ c=stream.eat("r");if(c){ c=stream.eat(/[(\[{<\^'"!~\/]/); if(c){ if(c=="[") return tokenChain(stream,state,["]","]"],RXstyle,RXmodifiers); if(c=="{") return tokenChain(stream,state,["}","}"],RXstyle,RXmodifiers); if(c=="<") return tokenChain(stream,state,[">",">"],RXstyle,RXmodifiers); if(c=="(") return tokenChain(stream,state,[")",")"],RXstyle,RXmodifiers); return tokenChain(stream,state,[c,c],RXstyle,RXmodifiers);}}}} if(ch=="`"){ return tokenChain(stream,state,[ch],"variable-2");} if(ch=="/"){ if(!/~\s*$/.test(prefix(stream))) return "operator"; else return tokenChain(stream,state,[ch],RXstyle,RXmodifiers);} if(ch=="$"){ var p=stream.pos; if(stream.eatWhile(/\d/)||stream.eat("{")&&stream.eatWhile(/\d/)&&stream.eat("}")) return "variable-2"; else stream.pos=p;} if(/[$@%]/.test(ch)){ var p=stream.pos; if(stream.eat("^")&&stream.eat(/[A-Z]/)||!/[@$%&]/.test(look(stream, -2))&&stream.eat(/[=|\\\-#?@;:&`~\^!\[\]*'"$+.,\/<>()]/)){ var c=stream.current(); if(PERL[c]) return "variable-2";} stream.pos=p;} if(/[$@%&]/.test(ch)){ if(stream.eatWhile(/[\w$\[\]]/)||stream.eat("{")&&stream.eatWhile(/[\w$\[\]]/)&&stream.eat("}")){ var c=stream.current(); if(PERL[c]) return "variable-2"; else return "variable";}} if(ch=="#"){ if(look(stream, -2)!="$"){ stream.skipToEnd(); return "comment";}} if(/[:+\-\^*$&%@=<>!?|\/~\.]/.test(ch)){ var p=stream.pos; stream.eatWhile(/[:+\-\^*$&%@=<>!?|\/~\.]/); if(PERL[stream.current()]) return "operator"; else stream.pos=p;} if(ch=="_"){ if(stream.pos==1){ if(suffix(stream, 6)=="_END__"){ return tokenChain(stream,state,['\0'],"comment");} else if(suffix(stream, 7)=="_DATA__"){ return tokenChain(stream,state,['\0'],"variable-2");} else if(suffix(stream, 7)=="_C__"){ return tokenChain(stream,state,['\0'],"string");}}} if(/\w/.test(ch)){ var p=stream.pos; if(look(stream, -2)=="{"&&(look(stream, 0)=="}"||stream.eatWhile(/\w/)&&look(stream, 0)=="}")) return "string"; else stream.pos=p;} if(/[A-Z]/.test(ch)){ var l=look(stream, -2); var p=stream.pos; stream.eatWhile(/[A-Z_]/); if(/[\da-z]/.test(look(stream, 0))){ stream.pos=p;} else{ var c=PERL[stream.current()]; if(!c) return "meta"; if(c[1]) c=c[0]; if(l!=":"){ if(c==1) return "keyword"; else if(c==2) return "def"; else if(c==3) return "atom"; else if(c==4) return "operator"; else if(c==5) return "variable-2"; else return "meta";} else return "meta";}} if(/[a-zA-Z_]/.test(ch)){ var l=look(stream, -2); stream.eatWhile(/\w/); var c=PERL[stream.current()]; if(!c) return "meta"; if(c[1]) c=c[0]; if(l!=":"){ if(c==1) return "keyword"; else if(c==2) return "def"; else if(c==3) return "atom"; else if(c==4) return "operator"; else if(c==5) return "variable-2"; else return "meta";} else return "meta";} return null;} return { startState: function() { return { tokenize: tokenPerl, chain: null, style: null, tail: null }; }, token: function(stream, state) { return (state.tokenize || tokenPerl)(stream, state); }, lineComment: '#' }; }); CodeMirror.registerHelper("wordChars", "perl", /[\w$]/); CodeMirror.defineMIME("text/x-perl", "perl"); // it's like "peek", but need for look-ahead or look-behind if index < 0 function look(stream, c){ return stream.string.charAt(stream.pos+(c||0)); } // return a part of prefix of current stream from current position function prefix(stream, c){ if(c){ var x=stream.pos-c; return stream.string.substr((x>=0?x:0),c);} else{ return stream.string.substr(0,stream.pos-1); } } // return a part of suffix of current stream from current position function suffix(stream, c){ var y=stream.string.length; var x=y-stream.pos+1; return stream.string.substr(stream.pos,(c&&c=(y=stream.string.length-1)) stream.pos=y; else stream.pos=x; } }); ================================================ FILE: third_party/CodeMirror/mode/php/index.html ================================================ CodeMirror: PHP mode

PHP mode

Simple HTML/PHP mode based on the C-like mode. Depends on XML, JavaScript, CSS, HTMLMixed, and C-like modes.

MIME types defined: application/x-httpd-php (HTML with PHP code), text/x-php (plain, non-wrapped PHP code).

================================================ FILE: third_party/CodeMirror/mode/php/php.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../clike/clike")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../clike/clike"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function keywords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } // Helper for phpString function matchSequence(list, end, escapes) { if (list.length == 0) return phpString(end); return function (stream, state) { var patterns = list[0]; for (var i = 0; i < patterns.length; i++) if (stream.match(patterns[i][0])) { state.tokenize = matchSequence(list.slice(1), end); return patterns[i][1]; } state.tokenize = phpString(end, escapes); return "string"; }; } function phpString(closing, escapes) { return function(stream, state) { return phpString_(stream, state, closing, escapes); }; } function phpString_(stream, state, closing, escapes) { // "Complex" syntax if (escapes !== false && stream.match("${", false) || stream.match("{$", false)) { state.tokenize = null; return "string"; } // Simple syntax if (escapes !== false && stream.match(/^\$[a-zA-Z_][a-zA-Z0-9_]*/)) { // After the variable name there may appear array or object operator. if (stream.match("[", false)) { // Match array operator state.tokenize = matchSequence([ [["[", null]], [[/\d[\w\.]*/, "number"], [/\$[a-zA-Z_][a-zA-Z0-9_]*/, "variable-2"], [/[\w\$]+/, "variable"]], [["]", null]] ], closing, escapes); } if (stream.match(/\-\>\w/, false)) { // Match object operator state.tokenize = matchSequence([ [["->", null]], [[/[\w]+/, "variable"]] ], closing, escapes); } return "variable-2"; } var escaped = false; // Normal string while (!stream.eol() && (escaped || escapes === false || (!stream.match("{$", false) && !stream.match(/^(\$[a-zA-Z_][a-zA-Z0-9_]*|\$\{)/, false)))) { if (!escaped && stream.match(closing)) { state.tokenize = null; state.tokStack.pop(); state.tokStack.pop(); break; } escaped = stream.next() == "\\" && !escaped; } return "string"; } var phpKeywords = "abstract and array as break case catch class clone const continue declare default " + "do else elseif enddeclare endfor endforeach endif endswitch endwhile extends final " + "for foreach function global goto if implements interface instanceof namespace " + "new or private protected public static switch throw trait try use var while xor " + "die echo empty exit eval include include_once isset list require require_once return " + "print unset __halt_compiler self static parent yield insteadof finally"; var phpAtoms = "true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__ __TRAIT__"; 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"; CodeMirror.registerHelper("hintWords", "php", [phpKeywords, phpAtoms, phpBuiltin].join(" ").split(" ")); CodeMirror.registerHelper("wordChars", "php", /[\w$]/); var phpConfig = { name: "clike", helperType: "php", keywords: keywords(phpKeywords), blockKeywords: keywords("catch do else elseif for foreach if switch try while finally"), defKeywords: keywords("class function interface namespace trait"), atoms: keywords(phpAtoms), builtin: keywords(phpBuiltin), multiLineStrings: true, hooks: { "$": function(stream) { stream.eatWhile(/[\w\$_]/); return "variable-2"; }, "<": function(stream, state) { var before; if (before = stream.match(/<<\s*/)) { var quoted = stream.eat(/['"]/); stream.eatWhile(/[\w\.]/); var delim = stream.current().slice(before[0].length + (quoted ? 2 : 1)); if (quoted) stream.eat(quoted); if (delim) { (state.tokStack || (state.tokStack = [])).push(delim, 0); state.tokenize = phpString(delim, quoted != "'"); return "string"; } } return false; }, "#": function(stream) { while (!stream.eol() && !stream.match("?>", false)) stream.next(); return "comment"; }, "/": function(stream) { if (stream.eat("/")) { while (!stream.eol() && !stream.match("?>", false)) stream.next(); return "comment"; } return false; }, '"': function(_stream, state) { (state.tokStack || (state.tokStack = [])).push('"', 0); state.tokenize = phpString('"'); return "string"; }, "{": function(_stream, state) { if (state.tokStack && state.tokStack.length) state.tokStack[state.tokStack.length - 1]++; return false; }, "}": function(_stream, state) { if (state.tokStack && state.tokStack.length > 0 && !--state.tokStack[state.tokStack.length - 1]) { state.tokenize = phpString(state.tokStack[state.tokStack.length - 2]); } return false; } } }; CodeMirror.defineMode("php", function(config, parserConfig) { var htmlMode = CodeMirror.getMode(config, (parserConfig && parserConfig.htmlMode) || "text/html"); var phpMode = CodeMirror.getMode(config, phpConfig); function dispatch(stream, state) { var isPHP = state.curMode == phpMode; if (stream.sol() && state.pending && state.pending != '"' && state.pending != "'") state.pending = null; if (!isPHP) { if (stream.match(/^<\?\w*/)) { state.curMode = phpMode; if (!state.php) state.php = CodeMirror.startState(phpMode, htmlMode.indent(state.html, "", "")) state.curState = state.php; return "meta"; } if (state.pending == '"' || state.pending == "'") { while (!stream.eol() && stream.next() != state.pending) {} var style = "string"; } else if (state.pending && stream.pos < state.pending.end) { stream.pos = state.pending.end; var style = state.pending.style; } else { var style = htmlMode.token(stream, state.curState); } if (state.pending) state.pending = null; var cur = stream.current(), openPHP = cur.search(/<\?/), m; if (openPHP != -1) { if (style == "string" && (m = cur.match(/[\'\"]$/)) && !/\?>/.test(cur)) state.pending = m[0]; else state.pending = {end: stream.pos, style: style}; stream.backUp(cur.length - openPHP); } return style; } else if (isPHP && state.php.tokenize == null && stream.match("?>")) { state.curMode = htmlMode; state.curState = state.html; if (!state.php.context.prev) state.php = null; return "meta"; } else { return phpMode.token(stream, state.curState); } } return { startState: function() { var html = CodeMirror.startState(htmlMode) var php = parserConfig.startOpen ? CodeMirror.startState(phpMode) : null return {html: html, php: php, curMode: parserConfig.startOpen ? phpMode : htmlMode, curState: parserConfig.startOpen ? php : html, pending: null}; }, copyState: function(state) { var html = state.html, htmlNew = CodeMirror.copyState(htmlMode, html), php = state.php, phpNew = php && CodeMirror.copyState(phpMode, php), cur; if (state.curMode == htmlMode) cur = htmlNew; else cur = phpNew; return {html: htmlNew, php: phpNew, curMode: state.curMode, curState: cur, pending: state.pending}; }, token: dispatch, indent: function(state, textAfter, line) { if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) || (state.curMode == phpMode && /^\?>/.test(textAfter))) return htmlMode.indent(state.html, textAfter, line); return state.curMode.indent(state.curState, textAfter, line); }, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//", innerMode: function(state) { return {state: state.curState, mode: state.curMode}; } }; }, "htmlmixed", "clike"); CodeMirror.defineMIME("application/x-httpd-php", "php"); CodeMirror.defineMIME("application/x-httpd-php-open", {name: "php", startOpen: true}); CodeMirror.defineMIME("text/x-php", phpConfig); }); ================================================ FILE: third_party/CodeMirror/mode/php/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "php"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT('simple_test', '[meta ]'); MT('variable_interpolation_non_alphanumeric', '[meta $/$\\$}$\\\"$:$;$?$|$[[$]]$+$=aaa"]', '[meta ?>]'); MT('variable_interpolation_digits', '[meta ]'); MT('variable_interpolation_simple_syntax_1', '[meta ]'); MT('variable_interpolation_simple_syntax_2', '[meta ]'); MT('variable_interpolation_simple_syntax_3', '[meta [variable aaaaa][string .aaaaaa"];', '[keyword echo] [string "aaa][variable-2 $aaaa][string ->][variable-2 $aaaaa][string .aaaaaa"];', '[keyword echo] [string "aaa][variable-2 $aaaa]->[variable aaaaa][string [[2]].aaaaaa"];', '[keyword echo] [string "aaa][variable-2 $aaaa]->[variable aaaaa][string ->aaaa2.aaaaaa"];', '[meta ?>]'); MT('variable_interpolation_escaping', '[meta aaa.aaa"];', '[keyword echo] [string "aaa\\$aaaa[[2]]aaa.aaa"];', '[keyword echo] [string "aaa\\$aaaa[[asd]]aaa.aaa"];', '[keyword echo] [string "aaa{\\$aaaa->aaa.aaa"];', '[keyword echo] [string "aaa{\\$aaaa[[2]]aaa.aaa"];', '[keyword echo] [string "aaa{\\aaaaa[[asd]]aaa.aaa"];', '[keyword echo] [string "aaa\\${aaaa->aaa.aaa"];', '[keyword echo] [string "aaa\\${aaaa[[2]]aaa.aaa"];', '[keyword echo] [string "aaa\\${aaaa[[asd]]aaa.aaa"];', '[meta ?>]'); MT('variable_interpolation_complex_syntax_1', '[meta aaa.aaa"];', '[keyword echo] [string "aaa][variable-2 $]{[variable-2 $aaaa]}[string ->aaa.aaa"];', '[keyword echo] [string "aaa][variable-2 $]{[variable-2 $aaaa][[',' [number 42]',']]}[string ->aaa.aaa"];', '[keyword echo] [string "aaa][variable-2 $]{[variable aaaa][meta ?>]aaaaaa'); MT('variable_interpolation_complex_syntax_2', '[meta } $aaaaaa.aaa"];', '[keyword echo] [string "][variable-2 $]{[variable aaa][comment /*}?>*/][[',' [string "aaa][variable-2 $aaa][string {}][variable-2 $]{[variable aaa]}[string "]',']]}[string ->aaa.aaa"];', '[keyword echo] [string "][variable-2 $]{[variable aaa][comment /*} } $aaa } */]}[string ->aaa.aaa"];'); function build_recursive_monsters(nt, t, n){ var monsters = [t]; for (var i = 1; i <= n; ++i) monsters[i] = nt.join(monsters[i - 1]); return monsters; } var m1 = build_recursive_monsters( ['[string "][variable-2 $]{[variable aaa] [operator +] ', '}[string "]'], '[comment /* }?>} */] [string "aaa][variable-2 $aaa][string .aaa"]', 10 ); MT('variable_interpolation_complex_syntax_3_1', '[meta ]'); var m2 = build_recursive_monsters( ['[string "a][variable-2 $]{[variable aaa] [operator +] ', ' [operator +] ', '}[string .a"]'], '[comment /* }?>{{ */] [string "a?>}{{aa][variable-2 $aaa][string .a}a?>a"]', 5 ); MT('variable_interpolation_complex_syntax_3_2', '[meta ]'); function build_recursive_monsters_2(mf1, mf2, nt, t, n){ var monsters = [t]; for (var i = 1; i <= n; ++i) monsters[i] = nt[0] + mf1[i - 1] + nt[1] + mf2[i - 1] + nt[2] + monsters[i - 1] + nt[3]; return monsters; } var m3 = build_recursive_monsters_2( m1, m2, ['[string "a][variable-2 $]{[variable aaa] [operator +] ', ' [operator +] ', ' [operator +] ', '}[string .a"]'], '[comment /* }?>{{ */] [string "a?>}{{aa][variable-2 $aaa][string .a}a?>a"]', 4 ); MT('variable_interpolation_complex_syntax_3_3', '[meta ]'); MT("variable_interpolation_heredoc", "[meta CodeMirror: Pig Latin mode

Pig Latin mode

Simple mode that handles Pig Latin language.

MIME type defined: text/x-pig (PIG code)

================================================ FILE: third_party/CodeMirror/mode/pig/pig.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /* * Pig Latin Mode for CodeMirror 2 * @author Prasanth Jayachandran * @link https://github.com/prasanthj/pig-codemirror-2 * This implementation is adapted from PL/SQL mode in CodeMirror 2. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pig", function(_config, parserConfig) { var keywords = parserConfig.keywords, builtins = parserConfig.builtins, types = parserConfig.types, multiLineStrings = parserConfig.multiLineStrings; var isOperatorChar = /[*+\-%<>=&?:\/!|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenComment(stream, state) { var isEnd = false; var ch; while(ch = stream.next()) { if(ch == "/" && isEnd) { state.tokenize = tokenBase; break; } isEnd = (ch == "*"); } return "comment"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while((next = stream.next()) != null) { if (next == quote && !escaped) { end = true; break; } escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = tokenBase; return "error"; }; } function tokenBase(stream, state) { var ch = stream.next(); // is a start of string? if (ch == '"' || ch == "'") return chain(stream, state, tokenString(ch)); // is it one of the special chars else if(/[\[\]{}\(\),;\.]/.test(ch)) return null; // is it a number? else if(/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } // multi line comment or operator else if (ch == "/") { if (stream.eat("*")) { return chain(stream, state, tokenComment); } else { stream.eatWhile(isOperatorChar); return "operator"; } } // single line comment or operator else if (ch=="-") { if(stream.eat("-")){ stream.skipToEnd(); return "comment"; } else { stream.eatWhile(isOperatorChar); return "operator"; } } // is it an operator else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } else { // get the while word stream.eatWhile(/[\w\$_]/); // is it one of the listed keywords? if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) { //keywords can be used as variables like flatten(group), group.$0 etc.. if (!stream.eat(")") && !stream.eat(".")) return "keyword"; } // is it one of the builtin functions? if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) return "variable-2"; // is it one of the listed types? if (types && types.propertyIsEnumerable(stream.current().toUpperCase())) return "variable-3"; // default is a 'variable' return "variable"; } } // Interface return { startState: function() { return { tokenize: tokenBase, startOfLine: true }; }, token: function(stream, state) { if(stream.eatSpace()) return null; var style = state.tokenize(stream, state); return style; } }; }); (function() { function keywords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } // builtin funcs taken from trunk revision 1303237 var pBuiltins = "ABS ACOS ARITY ASIN ATAN AVG BAGSIZE BINSTORAGE BLOOM BUILDBLOOM CBRT CEIL " + "CONCAT COR COS COSH COUNT COUNT_STAR COV CONSTANTSIZE CUBEDIMENSIONS DIFF DISTINCT DOUBLEABS " + "DOUBLEAVG DOUBLEBASE DOUBLEMAX DOUBLEMIN DOUBLEROUND DOUBLESUM EXP FLOOR FLOATABS FLOATAVG " + "FLOATMAX FLOATMIN FLOATROUND FLOATSUM GENERICINVOKER INDEXOF INTABS INTAVG INTMAX INTMIN " + "INTSUM INVOKEFORDOUBLE INVOKEFORFLOAT INVOKEFORINT INVOKEFORLONG INVOKEFORSTRING INVOKER " + "ISEMPTY JSONLOADER JSONMETADATA JSONSTORAGE LAST_INDEX_OF LCFIRST LOG LOG10 LOWER LONGABS " + "LONGAVG LONGMAX LONGMIN LONGSUM MAX MIN MAPSIZE MONITOREDUDF NONDETERMINISTIC OUTPUTSCHEMA " + "PIGSTORAGE PIGSTREAMING RANDOM REGEX_EXTRACT REGEX_EXTRACT_ALL REPLACE ROUND SIN SINH SIZE " + "SQRT STRSPLIT SUBSTRING SUM STRINGCONCAT STRINGMAX STRINGMIN STRINGSIZE TAN TANH TOBAG " + "TOKENIZE TOMAP TOP TOTUPLE TRIM TEXTLOADER TUPLESIZE UCFIRST UPPER UTF8STORAGECONVERTER "; // taken from QueryLexer.g var pKeywords = "VOID IMPORT RETURNS DEFINE LOAD FILTER FOREACH ORDER CUBE DISTINCT COGROUP " + "JOIN CROSS UNION SPLIT INTO IF OTHERWISE ALL AS BY USING INNER OUTER ONSCHEMA PARALLEL " + "PARTITION GROUP AND OR NOT GENERATE FLATTEN ASC DESC IS STREAM THROUGH STORE MAPREDUCE " + "SHIP CACHE INPUT OUTPUT STDERROR STDIN STDOUT LIMIT SAMPLE LEFT RIGHT FULL EQ GT LT GTE LTE " + "NEQ MATCHES TRUE FALSE DUMP"; // data types var pTypes = "BOOLEAN INT LONG FLOAT DOUBLE CHARARRAY BYTEARRAY BAG TUPLE MAP "; CodeMirror.defineMIME("text/x-pig", { name: "pig", builtins: keywords(pBuiltins), keywords: keywords(pKeywords), types: keywords(pTypes) }); CodeMirror.registerHelper("hintWords", "pig", (pBuiltins + pTypes + pKeywords).split(" ")); }()); }); ================================================ FILE: third_party/CodeMirror/mode/powershell/index.html ================================================ CodeMirror: Powershell mode

PowerShell mode

MIME types defined: application/x-powershell.

================================================ FILE: third_party/CodeMirror/mode/powershell/powershell.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { 'use strict'; if (typeof exports == 'object' && typeof module == 'object') // CommonJS mod(require('../../lib/codemirror')); else if (typeof define == 'function' && define.amd) // AMD define(['../../lib/codemirror'], mod); else // Plain browser env mod(window.CodeMirror); })(function(CodeMirror) { 'use strict'; CodeMirror.defineMode('powershell', function() { function buildRegexp(patterns, options) { options = options || {}; var prefix = options.prefix !== undefined ? options.prefix : '^'; var suffix = options.suffix !== undefined ? options.suffix : '\\b'; for (var i = 0; i < patterns.length; i++) { if (patterns[i] instanceof RegExp) { patterns[i] = patterns[i].source; } else { patterns[i] = patterns[i].replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } } return new RegExp(prefix + '(' + patterns.join('|') + ')' + suffix, 'i'); } var notCharacterOrDash = '(?=[^A-Za-z\\d\\-_]|$)'; var varNames = /[\w\-:]/ var keywords = buildRegexp([ /begin|break|catch|continue|data|default|do|dynamicparam/, /else|elseif|end|exit|filter|finally|for|foreach|from|function|if|in/, /param|process|return|switch|throw|trap|try|until|where|while/ ], { suffix: notCharacterOrDash }); var punctuation = /[\[\]{},;`\.]|@[({]/; var wordOperators = buildRegexp([ 'f', /b?not/, /[ic]?split/, 'join', /is(not)?/, 'as', /[ic]?(eq|ne|[gl][te])/, /[ic]?(not)?(like|match|contains)/, /[ic]?replace/, /b?(and|or|xor)/ ], { prefix: '-' }); var symbolOperators = /[+\-*\/%]=|\+\+|--|\.\.|[+\-*&^%:=!|\/]|<(?!#)|(?!#)>/; var operators = buildRegexp([wordOperators, symbolOperators], { suffix: '' }); var numbers = /^((0x[\da-f]+)|((\d+\.\d+|\d\.|\.\d+|\d+)(e[\+\-]?\d+)?))[ld]?([kmgtp]b)?/i; var identifiers = /^[A-Za-z\_][A-Za-z\-\_\d]*\b/; var symbolBuiltins = /[A-Z]:|%|\?/i; var namedBuiltins = buildRegexp([ /Add-(Computer|Content|History|Member|PSSnapin|Type)/, /Checkpoint-Computer/, /Clear-(Content|EventLog|History|Host|Item(Property)?|Variable)/, /Compare-Object/, /Complete-Transaction/, /Connect-PSSession/, /ConvertFrom-(Csv|Json|SecureString|StringData)/, /Convert-Path/, /ConvertTo-(Csv|Html|Json|SecureString|Xml)/, /Copy-Item(Property)?/, /Debug-Process/, /Disable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/, /Disconnect-PSSession/, /Enable-(ComputerRestore|PSBreakpoint|PSRemoting|PSSessionConfiguration)/, /(Enter|Exit)-PSSession/, /Export-(Alias|Clixml|Console|Counter|Csv|FormatData|ModuleMember|PSSession)/, /ForEach-Object/, /Format-(Custom|List|Table|Wide)/, new RegExp('Get-(Acl|Alias|AuthenticodeSignature|ChildItem|Command|ComputerRestorePoint|Content|ControlPanelItem|Counter|Credential' + '|Culture|Date|Event|EventLog|EventSubscriber|ExecutionPolicy|FormatData|Help|History|Host|HotFix|Item|ItemProperty|Job' + '|Location|Member|Module|PfxCertificate|Process|PSBreakpoint|PSCallStack|PSDrive|PSProvider|PSSession|PSSessionConfiguration' + '|PSSnapin|Random|Service|TraceSource|Transaction|TypeData|UICulture|Unique|Variable|Verb|WinEvent|WmiObject)'), /Group-Object/, /Import-(Alias|Clixml|Counter|Csv|LocalizedData|Module|PSSession)/, /ImportSystemModules/, /Invoke-(Command|Expression|History|Item|RestMethod|WebRequest|WmiMethod)/, /Join-Path/, /Limit-EventLog/, /Measure-(Command|Object)/, /Move-Item(Property)?/, new RegExp('New-(Alias|Event|EventLog|Item(Property)?|Module|ModuleManifest|Object|PSDrive|PSSession|PSSessionConfigurationFile' + '|PSSessionOption|PSTransportOption|Service|TimeSpan|Variable|WebServiceProxy|WinEvent)'), /Out-(Default|File|GridView|Host|Null|Printer|String)/, /Pause/, /(Pop|Push)-Location/, /Read-Host/, /Receive-(Job|PSSession)/, /Register-(EngineEvent|ObjectEvent|PSSessionConfiguration|WmiEvent)/, /Remove-(Computer|Event|EventLog|Item(Property)?|Job|Module|PSBreakpoint|PSDrive|PSSession|PSSnapin|TypeData|Variable|WmiObject)/, /Rename-(Computer|Item(Property)?)/, /Reset-ComputerMachinePassword/, /Resolve-Path/, /Restart-(Computer|Service)/, /Restore-Computer/, /Resume-(Job|Service)/, /Save-Help/, /Select-(Object|String|Xml)/, /Send-MailMessage/, new RegExp('Set-(Acl|Alias|AuthenticodeSignature|Content|Date|ExecutionPolicy|Item(Property)?|Location|PSBreakpoint|PSDebug' + '|PSSessionConfiguration|Service|StrictMode|TraceSource|Variable|WmiInstance)'), /Show-(Command|ControlPanelItem|EventLog)/, /Sort-Object/, /Split-Path/, /Start-(Job|Process|Service|Sleep|Transaction|Transcript)/, /Stop-(Computer|Job|Process|Service|Transcript)/, /Suspend-(Job|Service)/, /TabExpansion2/, /Tee-Object/, /Test-(ComputerSecureChannel|Connection|ModuleManifest|Path|PSSessionConfigurationFile)/, /Trace-Command/, /Unblock-File/, /Undo-Transaction/, /Unregister-(Event|PSSessionConfiguration)/, /Update-(FormatData|Help|List|TypeData)/, /Use-Transaction/, /Wait-(Event|Job|Process)/, /Where-Object/, /Write-(Debug|Error|EventLog|Host|Output|Progress|Verbose|Warning)/, /cd|help|mkdir|more|oss|prompt/, /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/, /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/, /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/, /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/, /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/, /sort|sp|spjb|spps|spsv|start|sujb|sv|swmi|tee|trcm|type|where|wjb|write/ ], { prefix: '', suffix: '' }); var variableBuiltins = buildRegexp([ /[$?^_]|Args|ConfirmPreference|ConsoleFileName|DebugPreference|Error|ErrorActionPreference|ErrorView|ExecutionContext/, /FormatEnumerationLimit|Home|Host|Input|MaximumAliasCount|MaximumDriveCount|MaximumErrorCount|MaximumFunctionCount/, /MaximumHistoryCount|MaximumVariableCount|MyInvocation|NestedPromptLevel|OutputEncoding|Pid|Profile|ProgressPreference/, /PSBoundParameters|PSCommandPath|PSCulture|PSDefaultParameterValues|PSEmailServer|PSHome|PSScriptRoot|PSSessionApplicationName/, /PSSessionConfigurationName|PSSessionOption|PSUICulture|PSVersionTable|Pwd|ShellId|StackTrace|VerbosePreference/, /WarningPreference|WhatIfPreference/, /Event|EventArgs|EventSubscriber|Sender/, /Matches|Ofs|ForEach|LastExitCode|PSCmdlet|PSItem|PSSenderInfo|This/, /true|false|null/ ], { prefix: '\\$', suffix: '' }); var builtins = buildRegexp([symbolBuiltins, namedBuiltins, variableBuiltins], { suffix: notCharacterOrDash }); var grammar = { keyword: keywords, number: numbers, operator: operators, builtin: builtins, punctuation: punctuation, identifier: identifiers }; // tokenizers function tokenBase(stream, state) { // Handle Comments //var ch = stream.peek(); var parent = state.returnStack[state.returnStack.length - 1]; if (parent && parent.shouldReturnFrom(state)) { state.tokenize = parent.tokenize; state.returnStack.pop(); return state.tokenize(stream, state); } if (stream.eatSpace()) { return null; } if (stream.eat('(')) { state.bracketNesting += 1; return 'punctuation'; } if (stream.eat(')')) { state.bracketNesting -= 1; return 'punctuation'; } for (var key in grammar) { if (stream.match(grammar[key])) { return key; } } var ch = stream.next(); // single-quote string if (ch === "'") { return tokenSingleQuoteString(stream, state); } if (ch === '$') { return tokenVariable(stream, state); } // double-quote string if (ch === '"') { return tokenDoubleQuoteString(stream, state); } if (ch === '<' && stream.eat('#')) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (ch === '#') { stream.skipToEnd(); return 'comment'; } if (ch === '@') { var quoteMatch = stream.eat(/["']/); if (quoteMatch && stream.eol()) { state.tokenize = tokenMultiString; state.startQuote = quoteMatch[0]; return tokenMultiString(stream, state); } else if (stream.eol()) { return 'error'; } else if (stream.peek().match(/[({]/)) { return 'punctuation'; } else if (stream.peek().match(varNames)) { // splatted variable return tokenVariable(stream, state); } } return 'error'; } function tokenSingleQuoteString(stream, state) { var ch; while ((ch = stream.peek()) != null) { stream.next(); if (ch === "'" && !stream.eat("'")) { state.tokenize = tokenBase; return 'string'; } } return 'error'; } function tokenDoubleQuoteString(stream, state) { var ch; while ((ch = stream.peek()) != null) { if (ch === '$') { state.tokenize = tokenStringInterpolation; return 'string'; } stream.next(); if (ch === '`') { stream.next(); continue; } if (ch === '"' && !stream.eat('"')) { state.tokenize = tokenBase; return 'string'; } } return 'error'; } function tokenStringInterpolation(stream, state) { return tokenInterpolation(stream, state, tokenDoubleQuoteString); } function tokenMultiStringReturn(stream, state) { state.tokenize = tokenMultiString; state.startQuote = '"' return tokenMultiString(stream, state); } function tokenHereStringInterpolation(stream, state) { return tokenInterpolation(stream, state, tokenMultiStringReturn); } function tokenInterpolation(stream, state, parentTokenize) { if (stream.match('$(')) { var savedBracketNesting = state.bracketNesting; state.returnStack.push({ /*jshint loopfunc:true */ shouldReturnFrom: function(state) { return state.bracketNesting === savedBracketNesting; }, tokenize: parentTokenize }); state.tokenize = tokenBase; state.bracketNesting += 1; return 'punctuation'; } else { stream.next(); state.returnStack.push({ shouldReturnFrom: function() { return true; }, tokenize: parentTokenize }); state.tokenize = tokenVariable; return state.tokenize(stream, state); } } function tokenComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == '>') { state.tokenize = tokenBase; break; } maybeEnd = (ch === '#'); } return 'comment'; } function tokenVariable(stream, state) { var ch = stream.peek(); if (stream.eat('{')) { state.tokenize = tokenVariableWithBraces; return tokenVariableWithBraces(stream, state); } else if (ch != undefined && ch.match(varNames)) { stream.eatWhile(varNames); state.tokenize = tokenBase; return 'variable-2'; } else { state.tokenize = tokenBase; return 'error'; } } function tokenVariableWithBraces(stream, state) { var ch; while ((ch = stream.next()) != null) { if (ch === '}') { state.tokenize = tokenBase; break; } } return 'variable-2'; } function tokenMultiString(stream, state) { var quote = state.startQuote; if (stream.sol() && stream.match(new RegExp(quote + '@'))) { state.tokenize = tokenBase; } else if (quote === '"') { while (!stream.eol()) { var ch = stream.peek(); if (ch === '$') { state.tokenize = tokenHereStringInterpolation; return 'string'; } stream.next(); if (ch === '`') { stream.next(); } } } else { stream.skipToEnd(); } return 'string'; } var external = { startState: function() { return { returnStack: [], bracketNesting: 0, tokenize: tokenBase }; }, token: function(stream, state) { return state.tokenize(stream, state); }, blockCommentStart: '<#', blockCommentEnd: '#>', lineComment: '#', fold: 'brace' }; return external; }); CodeMirror.defineMIME('application/x-powershell', 'powershell'); }); ================================================ FILE: third_party/CodeMirror/mode/powershell/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "powershell"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } function forEach(arr, f) { for (var i = 0; i < arr.length; i++) f(arr[i], i) } MT('comment', '[number 1][comment # A]'); MT('comment_multiline', '[number 1][comment <#]', '[comment ABC]', '[comment #>][number 2]'); forEach([ '0', '1234', '12kb', '12mb', '12Gb', '12Tb', '12PB', '12L', '12D', '12lkb', '12dtb', '1.234', '1.234e56', '1.', '1.e2', '.2', '.2e34', '1.2MB', '1.kb', '.1dTB', '1.e1gb', '.2', '.2e34', '0x1', '0xabcdef', '0x3tb', '0xelmb' ], function(number) { MT("number_" + number, "[number " + number + "]"); }); MT('string_literal_escaping', "[string 'a''']"); MT('string_literal_variable', "[string 'a $x']"); MT('string_escaping_1', '[string "a `""]'); MT('string_escaping_2', '[string "a """]'); MT('string_variable_escaping', '[string "a `$x"]'); MT('string_variable', '[string "a ][variable-2 $x][string b"]'); MT('string_variable_spaces', '[string "a ][variable-2 ${x y}][string b"]'); MT('string_expression', '[string "a ][punctuation $(][variable-2 $x][operator +][number 3][punctuation )][string b"]'); MT('string_expression_nested', '[string "A][punctuation $(][string "a][punctuation $(][string "w"][punctuation )][string b"][punctuation )][string B"]'); MT('string_heredoc', '[string @"]', '[string abc]', '[string "@]'); MT('string_heredoc_quotes', '[string @"]', '[string abc "\']', '[string "@]'); MT('string_heredoc_variable', '[string @"]', '[string a ][variable-2 $x][string b]', '[string "@]'); MT('string_heredoc_nested_string', '[string @"]', '[string a][punctuation $(][string "w"][punctuation )][string b]', '[string "@]'); MT('string_heredoc_literal_quotes', "[string @']", '[string abc "\']', "[string '@]"); MT('array', "[punctuation @(][string 'a'][punctuation ,][string 'b'][punctuation )]"); MT('hash', "[punctuation @{][string 'key'][operator :][string 'value'][punctuation }]"); MT('variable', "[variable-2 $test]"); MT('variable_global', "[variable-2 $global:test]"); MT('variable_spaces', "[variable-2 ${test test}]"); MT('operator_splat', "[variable-2 @x]"); MT('variable_builtin', "[builtin $ErrorActionPreference]"); MT('variable_builtin_symbols', "[builtin $$]"); MT('operator', "[operator +]"); MT('operator_unary', "[operator +][number 3]"); MT('operator_long', "[operator -match]"); forEach([ '(', ')', '[[', ']]', '{', '}', ',', '`', ';', '.' ], function(punctuation) { MT("punctuation_" + punctuation.replace(/^[\[\]]/,''), "[punctuation " + punctuation + "]"); }); MT('keyword', "[keyword if]"); MT('call_builtin', "[builtin Get-ChildItem]"); })(); ================================================ FILE: third_party/CodeMirror/mode/properties/index.html ================================================ CodeMirror: Properties files mode

Properties files mode

MIME types defined: text/x-properties, text/x-ini.

================================================ FILE: third_party/CodeMirror/mode/properties/properties.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("properties", function() { return { token: function(stream, state) { var sol = stream.sol() || state.afterSection; var eol = stream.eol(); state.afterSection = false; if (sol) { if (state.nextMultiline) { state.inMultiline = true; state.nextMultiline = false; } else { state.position = "def"; } } if (eol && ! state.nextMultiline) { state.inMultiline = false; state.position = "def"; } if (sol) { while(stream.eatSpace()) {} } var ch = stream.next(); if (sol && (ch === "#" || ch === "!" || ch === ";")) { state.position = "comment"; stream.skipToEnd(); return "comment"; } else if (sol && ch === "[") { state.afterSection = true; stream.skipTo("]"); stream.eat("]"); return "header"; } else if (ch === "=" || ch === ":") { state.position = "quote"; return null; } else if (ch === "\\" && state.position === "quote") { if (stream.eol()) { // end of line? // Multiline value state.nextMultiline = true; } } return state.position; }, startState: function() { return { position : "def", // Current position, "def", "quote" or "comment" nextMultiline : false, // Is the next line multiline value inMultiline : false, // Is the current line a multiline value afterSection : false // Did we just open a section }; } }; }); CodeMirror.defineMIME("text/x-properties", "properties"); CodeMirror.defineMIME("text/x-ini", "properties"); }); ================================================ FILE: third_party/CodeMirror/mode/protobuf/index.html ================================================ CodeMirror: ProtoBuf mode

ProtoBuf mode

MIME types defined: text/x-protobuf.

================================================ FILE: third_party/CodeMirror/mode/protobuf/protobuf.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b", "i"); }; var keywordArray = [ "package", "message", "import", "syntax", "required", "optional", "repeated", "reserved", "default", "extensions", "packed", "bool", "bytes", "double", "enum", "float", "string", "int32", "int64", "uint32", "uint64", "sint32", "sint64", "fixed32", "fixed64", "sfixed32", "sfixed64", "option", "service", "rpc", "returns" ]; var keywords = wordRegexp(keywordArray); CodeMirror.registerHelper("hintWords", "protobuf", keywordArray); var identifiers = new RegExp("^[_A-Za-z\xa1-\uffff][_A-Za-z0-9\xa1-\uffff]*"); function tokenBase(stream) { // whitespaces if (stream.eatSpace()) return null; // Handle one line Comments if (stream.match("//")) { stream.skipToEnd(); return "comment"; } // Handle Number Literals if (stream.match(/^[0-9\.+-]/, false)) { if (stream.match(/^[+-]?0x[0-9a-fA-F]+/)) return "number"; if (stream.match(/^[+-]?\d*\.\d+([EeDd][+-]?\d+)?/)) return "number"; if (stream.match(/^[+-]?\d+([EeDd][+-]?\d+)?/)) return "number"; } // Handle Strings if (stream.match(/^"([^"]|(""))*"/)) { return "string"; } if (stream.match(/^'([^']|(''))*'/)) { return "string"; } // Handle words if (stream.match(keywords)) { return "keyword"; } if (stream.match(identifiers)) { return "variable"; } ; // Handle non-detected items stream.next(); return null; }; CodeMirror.defineMode("protobuf", function() { return {token: tokenBase}; }); CodeMirror.defineMIME("text/x-protobuf", "protobuf"); }); ================================================ FILE: third_party/CodeMirror/mode/pug/index.html ================================================ CodeMirror: Pug Templating Mode

Pug Templating Mode

The Pug Templating Mode

Created by Forbes Lindesay. Managed as part of a Brackets extension at https://github.com/ForbesLindesay/jade-brackets.

MIME type defined: text/x-pug, text/x-jade.

================================================ FILE: third_party/CodeMirror/mode/pug/pug.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../javascript/javascript"), require("../css/css"), require("../htmlmixed/htmlmixed")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../javascript/javascript", "../css/css", "../htmlmixed/htmlmixed"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("pug", function (config) { // token types var KEYWORD = 'keyword'; var DOCTYPE = 'meta'; var ID = 'builtin'; var CLASS = 'qualifier'; var ATTRS_NEST = { '{': '}', '(': ')', '[': ']' }; var jsMode = CodeMirror.getMode(config, 'javascript'); function State() { this.javaScriptLine = false; this.javaScriptLineExcludesColon = false; this.javaScriptArguments = false; this.javaScriptArgumentsDepth = 0; this.isInterpolating = false; this.interpolationNesting = 0; this.jsState = CodeMirror.startState(jsMode); this.restOfLine = ''; this.isIncludeFiltered = false; this.isEach = false; this.lastTag = ''; this.scriptType = ''; // Attributes Mode this.isAttrs = false; this.attrsNest = []; this.inAttributeName = true; this.attributeIsType = false; this.attrValue = ''; // Indented Mode this.indentOf = Infinity; this.indentToken = ''; this.innerMode = null; this.innerState = null; this.innerModeForLine = false; } /** * Safely copy a state * * @return {State} */ State.prototype.copy = function () { var res = new State(); res.javaScriptLine = this.javaScriptLine; res.javaScriptLineExcludesColon = this.javaScriptLineExcludesColon; res.javaScriptArguments = this.javaScriptArguments; res.javaScriptArgumentsDepth = this.javaScriptArgumentsDepth; res.isInterpolating = this.isInterpolating; res.interpolationNesting = this.interpolationNesting; res.jsState = CodeMirror.copyState(jsMode, this.jsState); res.innerMode = this.innerMode; if (this.innerMode && this.innerState) { res.innerState = CodeMirror.copyState(this.innerMode, this.innerState); } res.restOfLine = this.restOfLine; res.isIncludeFiltered = this.isIncludeFiltered; res.isEach = this.isEach; res.lastTag = this.lastTag; res.scriptType = this.scriptType; res.isAttrs = this.isAttrs; res.attrsNest = this.attrsNest.slice(); res.inAttributeName = this.inAttributeName; res.attributeIsType = this.attributeIsType; res.attrValue = this.attrValue; res.indentOf = this.indentOf; res.indentToken = this.indentToken; res.innerModeForLine = this.innerModeForLine; return res; }; function javaScript(stream, state) { if (stream.sol()) { // if javaScriptLine was set at end of line, ignore it state.javaScriptLine = false; state.javaScriptLineExcludesColon = false; } if (state.javaScriptLine) { if (state.javaScriptLineExcludesColon && stream.peek() === ':') { state.javaScriptLine = false; state.javaScriptLineExcludesColon = false; return; } var tok = jsMode.token(stream, state.jsState); if (stream.eol()) state.javaScriptLine = false; return tok || true; } } function javaScriptArguments(stream, state) { if (state.javaScriptArguments) { if (state.javaScriptArgumentsDepth === 0 && stream.peek() !== '(') { state.javaScriptArguments = false; return; } if (stream.peek() === '(') { state.javaScriptArgumentsDepth++; } else if (stream.peek() === ')') { state.javaScriptArgumentsDepth--; } if (state.javaScriptArgumentsDepth === 0) { state.javaScriptArguments = false; return; } var tok = jsMode.token(stream, state.jsState); return tok || true; } } function yieldStatement(stream) { if (stream.match(/^yield\b/)) { return 'keyword'; } } function doctype(stream) { if (stream.match(/^(?:doctype) *([^\n]+)?/)) { return DOCTYPE; } } function interpolation(stream, state) { if (stream.match('#{')) { state.isInterpolating = true; state.interpolationNesting = 0; return 'punctuation'; } } function interpolationContinued(stream, state) { if (state.isInterpolating) { if (stream.peek() === '}') { state.interpolationNesting--; if (state.interpolationNesting < 0) { stream.next(); state.isInterpolating = false; return 'punctuation'; } } else if (stream.peek() === '{') { state.interpolationNesting++; } return jsMode.token(stream, state.jsState) || true; } } function caseStatement(stream, state) { if (stream.match(/^case\b/)) { state.javaScriptLine = true; return KEYWORD; } } function when(stream, state) { if (stream.match(/^when\b/)) { state.javaScriptLine = true; state.javaScriptLineExcludesColon = true; return KEYWORD; } } function defaultStatement(stream) { if (stream.match(/^default\b/)) { return KEYWORD; } } function extendsStatement(stream, state) { if (stream.match(/^extends?\b/)) { state.restOfLine = 'string'; return KEYWORD; } } function append(stream, state) { if (stream.match(/^append\b/)) { state.restOfLine = 'variable'; return KEYWORD; } } function prepend(stream, state) { if (stream.match(/^prepend\b/)) { state.restOfLine = 'variable'; return KEYWORD; } } function block(stream, state) { if (stream.match(/^block\b *(?:(prepend|append)\b)?/)) { state.restOfLine = 'variable'; return KEYWORD; } } function include(stream, state) { if (stream.match(/^include\b/)) { state.restOfLine = 'string'; return KEYWORD; } } function includeFiltered(stream, state) { if (stream.match(/^include:([a-zA-Z0-9\-]+)/, false) && stream.match('include')) { state.isIncludeFiltered = true; return KEYWORD; } } function includeFilteredContinued(stream, state) { if (state.isIncludeFiltered) { var tok = filter(stream, state); state.isIncludeFiltered = false; state.restOfLine = 'string'; return tok; } } function mixin(stream, state) { if (stream.match(/^mixin\b/)) { state.javaScriptLine = true; return KEYWORD; } } function call(stream, state) { if (stream.match(/^\+([-\w]+)/)) { if (!stream.match(/^\( *[-\w]+ *=/, false)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; } return 'variable'; } if (stream.match(/^\+#{/, false)) { stream.next(); state.mixinCallAfter = true; return interpolation(stream, state); } } function callArguments(stream, state) { if (state.mixinCallAfter) { state.mixinCallAfter = false; if (!stream.match(/^\( *[-\w]+ *=/, false)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; } return true; } } function conditional(stream, state) { if (stream.match(/^(if|unless|else if|else)\b/)) { state.javaScriptLine = true; return KEYWORD; } } function each(stream, state) { if (stream.match(/^(- *)?(each|for)\b/)) { state.isEach = true; return KEYWORD; } } function eachContinued(stream, state) { if (state.isEach) { if (stream.match(/^ in\b/)) { state.javaScriptLine = true; state.isEach = false; return KEYWORD; } else if (stream.sol() || stream.eol()) { state.isEach = false; } else if (stream.next()) { while (!stream.match(/^ in\b/, false) && stream.next()); return 'variable'; } } } function whileStatement(stream, state) { if (stream.match(/^while\b/)) { state.javaScriptLine = true; return KEYWORD; } } function tag(stream, state) { var captures; if (captures = stream.match(/^(\w(?:[-:\w]*\w)?)\/?/)) { state.lastTag = captures[1].toLowerCase(); if (state.lastTag === 'script') { state.scriptType = 'application/javascript'; } return 'tag'; } } function filter(stream, state) { if (stream.match(/^:([\w\-]+)/)) { var innerMode; if (config && config.innerModes) { innerMode = config.innerModes(stream.current().substring(1)); } if (!innerMode) { innerMode = stream.current().substring(1); } if (typeof innerMode === 'string') { innerMode = CodeMirror.getMode(config, innerMode); } setInnerMode(stream, state, innerMode); return 'atom'; } } function code(stream, state) { if (stream.match(/^(!?=|-)/)) { state.javaScriptLine = true; return 'punctuation'; } } function id(stream) { if (stream.match(/^#([\w-]+)/)) { return ID; } } function className(stream) { if (stream.match(/^\.([\w-]+)/)) { return CLASS; } } function attrs(stream, state) { if (stream.peek() == '(') { stream.next(); state.isAttrs = true; state.attrsNest = []; state.inAttributeName = true; state.attrValue = ''; state.attributeIsType = false; return 'punctuation'; } } function attrsContinued(stream, state) { if (state.isAttrs) { if (ATTRS_NEST[stream.peek()]) { state.attrsNest.push(ATTRS_NEST[stream.peek()]); } if (state.attrsNest[state.attrsNest.length - 1] === stream.peek()) { state.attrsNest.pop(); } else if (stream.eat(')')) { state.isAttrs = false; return 'punctuation'; } if (state.inAttributeName && stream.match(/^[^=,\)!]+/)) { if (stream.peek() === '=' || stream.peek() === '!') { state.inAttributeName = false; state.jsState = CodeMirror.startState(jsMode); if (state.lastTag === 'script' && stream.current().trim().toLowerCase() === 'type') { state.attributeIsType = true; } else { state.attributeIsType = false; } } return 'attribute'; } var tok = jsMode.token(stream, state.jsState); if (state.attributeIsType && tok === 'string') { state.scriptType = stream.current().toString(); } if (state.attrsNest.length === 0 && (tok === 'string' || tok === 'variable' || tok === 'keyword')) { try { Function('', 'var x ' + state.attrValue.replace(/,\s*$/, '').replace(/^!/, '')); state.inAttributeName = true; state.attrValue = ''; stream.backUp(stream.current().length); return attrsContinued(stream, state); } catch (ex) { //not the end of an attribute } } state.attrValue += stream.current(); return tok || true; } } function attributesBlock(stream, state) { if (stream.match(/^&attributes\b/)) { state.javaScriptArguments = true; state.javaScriptArgumentsDepth = 0; return 'keyword'; } } function indent(stream) { if (stream.sol() && stream.eatSpace()) { return 'indent'; } } function comment(stream, state) { if (stream.match(/^ *\/\/(-)?([^\n]*)/)) { state.indentOf = stream.indentation(); state.indentToken = 'comment'; return 'comment'; } } function colon(stream) { if (stream.match(/^: */)) { return 'colon'; } } function text(stream, state) { if (stream.match(/^(?:\| ?| )([^\n]+)/)) { return 'string'; } if (stream.match(/^(<[^\n]*)/, false)) { // html string setInnerMode(stream, state, 'htmlmixed'); state.innerModeForLine = true; return innerMode(stream, state, true); } } function dot(stream, state) { if (stream.eat('.')) { var innerMode = null; if (state.lastTag === 'script' && state.scriptType.toLowerCase().indexOf('javascript') != -1) { innerMode = state.scriptType.toLowerCase().replace(/"|'/g, ''); } else if (state.lastTag === 'style') { innerMode = 'css'; } setInnerMode(stream, state, innerMode); return 'dot'; } } function fail(stream) { stream.next(); return null; } function setInnerMode(stream, state, mode) { mode = CodeMirror.mimeModes[mode] || mode; mode = config.innerModes ? config.innerModes(mode) || mode : mode; mode = CodeMirror.mimeModes[mode] || mode; mode = CodeMirror.getMode(config, mode); state.indentOf = stream.indentation(); if (mode && mode.name !== 'null') { state.innerMode = mode; } else { state.indentToken = 'string'; } } function innerMode(stream, state, force) { if (stream.indentation() > state.indentOf || (state.innerModeForLine && !stream.sol()) || force) { if (state.innerMode) { if (!state.innerState) { state.innerState = state.innerMode.startState ? CodeMirror.startState(state.innerMode, stream.indentation()) : {}; } return stream.hideFirstChars(state.indentOf + 2, function () { return state.innerMode.token(stream, state.innerState) || true; }); } else { stream.skipToEnd(); return state.indentToken; } } else if (stream.sol()) { state.indentOf = Infinity; state.indentToken = null; state.innerMode = null; state.innerState = null; } } function restOfLine(stream, state) { if (stream.sol()) { // if restOfLine was set at end of line, ignore it state.restOfLine = ''; } if (state.restOfLine) { stream.skipToEnd(); var tok = state.restOfLine; state.restOfLine = ''; return tok; } } function startState() { return new State(); } function copyState(state) { return state.copy(); } /** * Get the next token in the stream * * @param {Stream} stream * @param {State} state */ function nextToken(stream, state) { var tok = innerMode(stream, state) || restOfLine(stream, state) || interpolationContinued(stream, state) || includeFilteredContinued(stream, state) || eachContinued(stream, state) || attrsContinued(stream, state) || javaScript(stream, state) || javaScriptArguments(stream, state) || callArguments(stream, state) || yieldStatement(stream, state) || doctype(stream, state) || interpolation(stream, state) || caseStatement(stream, state) || when(stream, state) || defaultStatement(stream, state) || extendsStatement(stream, state) || append(stream, state) || prepend(stream, state) || block(stream, state) || include(stream, state) || includeFiltered(stream, state) || mixin(stream, state) || call(stream, state) || conditional(stream, state) || each(stream, state) || whileStatement(stream, state) || tag(stream, state) || filter(stream, state) || code(stream, state) || id(stream, state) || className(stream, state) || attrs(stream, state) || attributesBlock(stream, state) || indent(stream, state) || text(stream, state) || comment(stream, state) || colon(stream, state) || dot(stream, state) || fail(stream, state); return tok === true ? null : tok; } return { startState: startState, copyState: copyState, token: nextToken }; }, 'javascript', 'css', 'htmlmixed'); CodeMirror.defineMIME('text/x-pug', 'pug'); CodeMirror.defineMIME('text/x-jade', 'pug'); }); ================================================ FILE: third_party/CodeMirror/mode/puppet/index.html ================================================ CodeMirror: Puppet mode

Puppet mode

MIME types defined: text/x-puppet.

================================================ FILE: third_party/CodeMirror/mode/puppet/puppet.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("puppet", function () { // Stores the words from the define method var words = {}; // Taken, mostly, from the Puppet official variable standards regex var variable_regex = /({)?([a-z][a-z0-9_]*)?((::[a-z][a-z0-9_]*)*::)?[a-zA-Z0-9_]+(})?/; // Takes a string of words separated by spaces and adds them as // keys with the value of the first argument 'style' function define(style, string) { var split = string.split(' '); for (var i = 0; i < split.length; i++) { words[split[i]] = style; } } // Takes commonly known puppet types/words and classifies them to a style define('keyword', 'class define site node include import inherits'); define('keyword', 'case if else in and elsif default or'); define('atom', 'false true running present absent file directory undef'); define('builtin', 'action augeas burst chain computer cron destination dport exec ' + 'file filebucket group host icmp iniface interface jump k5login limit log_level ' + 'log_prefix macauthorization mailalias maillist mcx mount nagios_command ' + 'nagios_contact nagios_contactgroup nagios_host nagios_hostdependency ' + 'nagios_hostescalation nagios_hostextinfo nagios_hostgroup nagios_service ' + 'nagios_servicedependency nagios_serviceescalation nagios_serviceextinfo ' + 'nagios_servicegroup nagios_timeperiod name notify outiface package proto reject ' + 'resources router schedule scheduled_task selboolean selmodule service source ' + 'sport ssh_authorized_key sshkey stage state table tidy todest toports tosource ' + 'user vlan yumrepo zfs zone zpool'); // After finding a start of a string ('|") this function attempts to find the end; // If a variable is encountered along the way, we display it differently when it // is encapsulated in a double-quoted string. function tokenString(stream, state) { var current, prev, found_var = false; while (!stream.eol() && (current = stream.next()) != state.pending) { if (current === '$' && prev != '\\' && state.pending == '"') { found_var = true; break; } prev = current; } if (found_var) { stream.backUp(1); } if (current == state.pending) { state.continueString = false; } else { state.continueString = true; } return "string"; } // Main function function tokenize(stream, state) { // Matches one whole word var word = stream.match(/[\w]+/, false); // Matches attributes (i.e. ensure => present ; 'ensure' would be matched) var attribute = stream.match(/(\s+)?\w+\s+=>.*/, false); // Matches non-builtin resource declarations // (i.e. "apache::vhost {" or "mycustomclasss {" would be matched) var resource = stream.match(/(\s+)?[\w:_]+(\s+)?{/, false); // Matches virtual and exported resources (i.e. @@user { ; and the like) var special_resource = stream.match(/(\s+)?[@]{1,2}[\w:_]+(\s+)?{/, false); // Finally advance the stream var ch = stream.next(); // Have we found a variable? if (ch === '$') { if (stream.match(variable_regex)) { // If so, and its in a string, assign it a different color return state.continueString ? 'variable-2' : 'variable'; } // Otherwise return an invalid variable return "error"; } // Should we still be looking for the end of a string? if (state.continueString) { // If so, go through the loop again stream.backUp(1); return tokenString(stream, state); } // Are we in a definition (class, node, define)? if (state.inDefinition) { // If so, return def (i.e. for 'class myclass {' ; 'myclass' would be matched) if (stream.match(/(\s+)?[\w:_]+(\s+)?/)) { return 'def'; } // Match the rest it the next time around stream.match(/\s+{/); state.inDefinition = false; } // Are we in an 'include' statement? if (state.inInclude) { // Match and return the included class stream.match(/(\s+)?\S+(\s+)?/); state.inInclude = false; return 'def'; } // Do we just have a function on our hands? // In 'ensure_resource("myclass")', 'ensure_resource' is matched if (stream.match(/(\s+)?\w+\(/)) { stream.backUp(1); return 'def'; } // Have we matched the prior attribute regex? if (attribute) { stream.match(/(\s+)?\w+/); return 'tag'; } // Do we have Puppet specific words? if (word && words.hasOwnProperty(word)) { // Negates the initial next() stream.backUp(1); // rs move the stream stream.match(/[\w]+/); // We want to process these words differently // do to the importance they have in Puppet if (stream.match(/\s+\S+\s+{/, false)) { state.inDefinition = true; } if (word == 'include') { state.inInclude = true; } // Returns their value as state in the prior define methods return words[word]; } // Is there a match on a reference? if (/(^|\s+)[A-Z][\w:_]+/.test(word)) { // Negate the next() stream.backUp(1); // Match the full reference stream.match(/(^|\s+)[A-Z][\w:_]+/); return 'def'; } // Have we matched the prior resource regex? if (resource) { stream.match(/(\s+)?[\w:_]+/); return 'def'; } // Have we matched the prior special_resource regex? if (special_resource) { stream.match(/(\s+)?[@]{1,2}/); return 'special'; } // Match all the comments. All of them. if (ch == "#") { stream.skipToEnd(); return "comment"; } // Have we found a string? if (ch == "'" || ch == '"') { // Store the type (single or double) state.pending = ch; // Perform the looping function to find the end return tokenString(stream, state); } // Match all the brackets if (ch == '{' || ch == '}') { return 'bracket'; } // Match characters that we are going to assume // are trying to be regex if (ch == '/') { stream.match(/.*?\//); return 'variable-3'; } // Match all the numbers if (ch.match(/[0-9]/)) { stream.eatWhile(/[0-9]+/); return 'number'; } // Match the '=' and '=>' operators if (ch == '=') { if (stream.peek() == '>') { stream.next(); } return "operator"; } // Keep advancing through all the rest stream.eatWhile(/[\w-]/); // Return a blank line for everything else return null; } // Start it all return { startState: function () { var state = {}; state.inDefinition = false; state.inInclude = false; state.continueString = false; state.pending = false; return state; }, token: function (stream, state) { // Strip the spaces, but regex will account for them eitherway if (stream.eatSpace()) return null; // Go through the main process return tokenize(stream, state); } }; }); CodeMirror.defineMIME("text/x-puppet", "puppet"); }); ================================================ FILE: third_party/CodeMirror/mode/python/index.html ================================================ CodeMirror: Python mode

Python mode

Cython mode

Configuration Options for Python mode:

  • version - 2/3 - The version of Python to recognize. Default is 3.
  • 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.
  • 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.

Advanced Configuration Options:

Usefull for superset of python syntax like Enthought enaml, IPython magics and questionmark help

  • singleOperators - RegEx - Regular Expression for single operator matching, default :
    ^[\\+\\-\\*/%&|\\^~<>!]
    including
    @
    on Python 3
  • singleDelimiters - RegEx - Regular Expression for single delimiter matching, default :
    ^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]
  • doubleOperators - RegEx - Regular Expression for double operators matching, default :
    ^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))
  • doubleDelimiters - RegEx - Regular Expression for double delimiters matching, default :
    ^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))
  • tripleDelimiters - RegEx - Regular Expression for triple delimiters matching, default :
    ^((//=)|(>>=)|(<<=)|(\\*\\*=))
  • identifiers - RegEx - Regular Expression for identifier, default :
    ^[_A-Za-z][_A-Za-z0-9]*
    on Python 2 and
    ^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*
    on Python 3.
  • extra_keywords - list of string - List of extra words ton consider as keywords
  • extra_builtins - list of string - List of extra words ton consider as builtins

MIME types defined: text/x-python and text/x-cython.

================================================ FILE: third_party/CodeMirror/mode/python/python.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); } var wordOperators = wordRegexp(["and", "or", "not", "is"]); var commonKeywords = ["as", "assert", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "lambda", "pass", "raise", "return", "try", "while", "with", "yield", "in"]; var commonBuiltins = ["abs", "all", "any", "bin", "bool", "bytearray", "callable", "chr", "classmethod", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr", "hash", "help", "hex", "id", "input", "int", "isinstance", "issubclass", "iter", "len", "list", "locals", "map", "max", "memoryview", "min", "next", "object", "oct", "open", "ord", "pow", "property", "range", "repr", "reversed", "round", "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super", "tuple", "type", "vars", "zip", "__import__", "NotImplemented", "Ellipsis", "__debug__"]; CodeMirror.registerHelper("hintWords", "python", commonKeywords.concat(commonBuiltins)); function top(state) { return state.scopes[state.scopes.length - 1]; } CodeMirror.defineMode("python", function(conf, parserConf) { var ERRORCLASS = "error"; var delimiters = parserConf.delimiters || parserConf.singleDelimiters || /^[\(\)\[\]\{\}@,:`=;\.\\]/; // (Backwards-compatiblity with old, cumbersome config system) var operators = [parserConf.singleOperators, parserConf.doubleOperators, parserConf.doubleDelimiters, parserConf.tripleDelimiters, parserConf.operators || /^([-+*/%\/&|^]=?|[<>=]+|\/\/=?|\*\*=?|!=|[~!@])/] for (var i = 0; i < operators.length; i++) if (!operators[i]) operators.splice(i--, 1) var hangingIndent = parserConf.hangingIndent || conf.indentUnit; var myKeywords = commonKeywords, myBuiltins = commonBuiltins; if (parserConf.extra_keywords != undefined) myKeywords = myKeywords.concat(parserConf.extra_keywords); if (parserConf.extra_builtins != undefined) myBuiltins = myBuiltins.concat(parserConf.extra_builtins); var py3 = !(parserConf.version && Number(parserConf.version) < 3) if (py3) { // since http://legacy.python.org/dev/peps/pep-0465/ @ is also an operator var identifiers = parserConf.identifiers|| /^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*/; myKeywords = myKeywords.concat(["nonlocal", "False", "True", "None", "async", "await"]); myBuiltins = myBuiltins.concat(["ascii", "bytes", "exec", "print"]); var stringPrefixes = new RegExp("^(([rbuf]|(br)|(fr))?('{3}|\"{3}|['\"]))", "i"); } else { var identifiers = parserConf.identifiers|| /^[_A-Za-z][_A-Za-z0-9]*/; myKeywords = myKeywords.concat(["exec", "print"]); myBuiltins = myBuiltins.concat(["apply", "basestring", "buffer", "cmp", "coerce", "execfile", "file", "intern", "long", "raw_input", "reduce", "reload", "unichr", "unicode", "xrange", "False", "True", "None"]); var stringPrefixes = new RegExp("^(([rubf]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); } var keywords = wordRegexp(myKeywords); var builtins = wordRegexp(myBuiltins); // tokenizers function tokenBase(stream, state) { var sol = stream.sol() && state.lastToken != "\\" if (sol) state.indent = stream.indentation() // Handle scope changes if (sol && top(state).type == "py") { var scopeOffset = top(state).offset; if (stream.eatSpace()) { var lineOffset = stream.indentation(); if (lineOffset > scopeOffset) pushPyScope(state); else if (lineOffset < scopeOffset && dedent(stream, state) && stream.peek() != "#") state.errorToken = true; return null; } else { var style = tokenBaseInner(stream, state); if (scopeOffset > 0 && dedent(stream, state)) style += " " + ERRORCLASS; return style; } } return tokenBaseInner(stream, state); } function tokenBaseInner(stream, state) { if (stream.eatSpace()) return null; // Handle Comments if (stream.match(/^#.*/)) return "comment"; // Handle Number Literals if (stream.match(/^[0-9\.]/, false)) { var floatLiteral = false; // Floats if (stream.match(/^[\d_]*\.\d+(e[\+\-]?\d+)?/i)) { floatLiteral = true; } if (stream.match(/^[\d_]+\.\d*/)) { floatLiteral = true; } if (stream.match(/^\.\d+/)) { floatLiteral = true; } if (floatLiteral) { // Float literals may be "imaginary" stream.eat(/J/i); return "number"; } // Integers var intLiteral = false; // Hex if (stream.match(/^0x[0-9a-f_]+/i)) intLiteral = true; // Binary if (stream.match(/^0b[01_]+/i)) intLiteral = true; // Octal if (stream.match(/^0o[0-7_]+/i)) intLiteral = true; // Decimal if (stream.match(/^[1-9][\d_]*(e[\+\-]?[\d_]+)?/)) { // Decimal literals may be "imaginary" stream.eat(/J/i); // TODO - Can you have imaginary longs? intLiteral = true; } // Zero by itself with no other piece of number. if (stream.match(/^0(?![\dx])/i)) intLiteral = true; if (intLiteral) { // Integer literals may be "long" stream.eat(/L/i); return "number"; } } // Handle Strings if (stream.match(stringPrefixes)) { var isFmtString = stream.current().toLowerCase().indexOf('f') !== -1; if (!isFmtString) { state.tokenize = tokenStringFactory(stream.current(), state.tokenize); return state.tokenize(stream, state); } else { state.tokenize = formatStringFactory(stream.current(), state.tokenize); return state.tokenize(stream, state); } } for (var i = 0; i < operators.length; i++) if (stream.match(operators[i])) return "operator" if (stream.match(delimiters)) return "punctuation"; if (state.lastToken == "." && stream.match(identifiers)) return "property"; if (stream.match(keywords) || stream.match(wordOperators)) return "keyword"; if (stream.match(builtins)) return "builtin"; if (stream.match(/^(self|cls)\b/)) return "variable-2"; if (stream.match(identifiers)) { if (state.lastToken == "def" || state.lastToken == "class") return "def"; return "variable"; } // Handle non-detected items stream.next(); return ERRORCLASS; } function formatStringFactory(delimiter, tokenOuter) { while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) delimiter = delimiter.substr(1); var singleline = delimiter.length == 1; var OUTCLASS = "string"; function tokenNestedExpr(depth) { return function(stream, state) { var inner = tokenBaseInner(stream, state) if (inner == "punctuation") { if (stream.current() == "{") { state.tokenize = tokenNestedExpr(depth + 1) } else if (stream.current() == "}") { if (depth > 1) state.tokenize = tokenNestedExpr(depth - 1) else state.tokenize = tokenString } } return inner } } function tokenString(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^'"\{\}\\]/); if (stream.eat("\\")) { stream.next(); if (singleline && stream.eol()) return OUTCLASS; } else if (stream.match(delimiter)) { state.tokenize = tokenOuter; return OUTCLASS; } else if (stream.match('{{')) { // ignore {{ in f-str return OUTCLASS; } else if (stream.match('{', false)) { // switch to nested mode state.tokenize = tokenNestedExpr(0) if (stream.current()) return OUTCLASS; else return state.tokenize(stream, state) } else if (stream.match('}}')) { return OUTCLASS; } else if (stream.match('}')) { // single } in f-string is an error return ERRORCLASS; } else { stream.eat(/['"]/); } } if (singleline) { if (parserConf.singleLineStringErrors) return ERRORCLASS; else state.tokenize = tokenOuter; } return OUTCLASS; } tokenString.isString = true; return tokenString; } function tokenStringFactory(delimiter, tokenOuter) { while ("rubf".indexOf(delimiter.charAt(0).toLowerCase()) >= 0) delimiter = delimiter.substr(1); var singleline = delimiter.length == 1; var OUTCLASS = "string"; function tokenString(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^'"\\]/); if (stream.eat("\\")) { stream.next(); if (singleline && stream.eol()) return OUTCLASS; } else if (stream.match(delimiter)) { state.tokenize = tokenOuter; return OUTCLASS; } else { stream.eat(/['"]/); } } if (singleline) { if (parserConf.singleLineStringErrors) return ERRORCLASS; else state.tokenize = tokenOuter; } return OUTCLASS; } tokenString.isString = true; return tokenString; } function pushPyScope(state) { while (top(state).type != "py") state.scopes.pop() state.scopes.push({offset: top(state).offset + conf.indentUnit, type: "py", align: null}) } function pushBracketScope(stream, state, type) { var align = stream.match(/^([\s\[\{\(]|#.*)*$/, false) ? null : stream.column() + 1 state.scopes.push({offset: state.indent + hangingIndent, type: type, align: align}) } function dedent(stream, state) { var indented = stream.indentation(); while (state.scopes.length > 1 && top(state).offset > indented) { if (top(state).type != "py") return true; state.scopes.pop(); } return top(state).offset != indented; } function tokenLexer(stream, state) { if (stream.sol()) state.beginningOfLine = true; var style = state.tokenize(stream, state); var current = stream.current(); // Handle decorators if (state.beginningOfLine && current == "@") return stream.match(identifiers, false) ? "meta" : py3 ? "operator" : ERRORCLASS; if (/\S/.test(current)) state.beginningOfLine = false; if ((style == "variable" || style == "builtin") && state.lastToken == "meta") style = "meta"; // Handle scope changes. if (current == "pass" || current == "return") state.dedent += 1; if (current == "lambda") state.lambda = true; if (current == ":" && !state.lambda && top(state).type == "py") pushPyScope(state); if (current.length == 1 && !/string|comment/.test(style)) { var delimiter_index = "[({".indexOf(current); if (delimiter_index != -1) pushBracketScope(stream, state, "])}".slice(delimiter_index, delimiter_index+1)); delimiter_index = "])}".indexOf(current); if (delimiter_index != -1) { if (top(state).type == current) state.indent = state.scopes.pop().offset - hangingIndent else return ERRORCLASS; } } if (state.dedent > 0 && stream.eol() && top(state).type == "py") { if (state.scopes.length > 1) state.scopes.pop(); state.dedent -= 1; } return style; } var external = { startState: function(basecolumn) { return { tokenize: tokenBase, scopes: [{offset: basecolumn || 0, type: "py", align: null}], indent: basecolumn || 0, lastToken: null, lambda: false, dedent: 0 }; }, token: function(stream, state) { var addErr = state.errorToken; if (addErr) state.errorToken = false; var style = tokenLexer(stream, state); if (style && style != "comment") state.lastToken = (style == "keyword" || style == "punctuation") ? stream.current() : style; if (style == "punctuation") style = null; if (stream.eol() && state.lambda) state.lambda = false; return addErr ? style + " " + ERRORCLASS : style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase) return state.tokenize.isString ? CodeMirror.Pass : 0; var scope = top(state), closing = scope.type == textAfter.charAt(0) if (scope.align != null) return scope.align - (closing ? 1 : 0) else return scope.offset - (closing ? hangingIndent : 0) }, electricInput: /^\s*[\}\]\)]$/, closeBrackets: {triples: "'\""}, lineComment: "#", fold: "indent" }; return external; }); CodeMirror.defineMIME("text/x-python", "python"); var words = function(str) { return str.split(" "); }; CodeMirror.defineMIME("text/x-cython", { name: "python", extra_keywords: words("by cdef cimport cpdef ctypedef enum except "+ "extern gil include nogil property public "+ "readonly struct union DEF IF ELIF ELSE") }); }); ================================================ FILE: third_party/CodeMirror/mode/python/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 4}, {name: "python", version: 3, singleLineStringErrors: false}); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Error, because "foobarhello" is neither a known type or property, but // property was expected (after "and"), and it should be in parentheses. MT("decoratorStartOfLine", "[meta @dec]", "[keyword def] [def function]():", " [keyword pass]"); MT("decoratorIndented", "[keyword class] [def Foo]:", " [meta @dec]", " [keyword def] [def function]():", " [keyword pass]"); MT("matmulWithSpace:", "[variable a] [operator @] [variable b]"); MT("matmulWithoutSpace:", "[variable a][operator @][variable b]"); MT("matmulSpaceBefore:", "[variable a] [operator @][variable b]"); var before_equal_sign = ["+", "-", "*", "/", "=", "!", ">", "<"]; for (var i = 0; i < before_equal_sign.length; ++i) { var c = before_equal_sign[i] MT("before_equal_sign_" + c, "[variable a] [operator " + c + "=] [variable b]"); } MT("fValidStringPrefix", "[string f'this is a]{[variable formatted]}[string string']"); MT("fValidExpressioninFString", "[string f'expression ]{[number 100][operator *][number 5]}[string string']"); MT("fInvalidFString", "[error f'this is wrong}]"); MT("fNestedFString", "[string f'expression ]{[number 100] [operator +] [string f'inner]{[number 5]}[string ']}[string string']"); MT("uValidStringPrefix", "[string u'this is an unicode string']"); MT("nestedString", "[string f']{[variable b][[ [string \"c\"] ]]}[string f'] [comment # oops]") MT("bracesInFString", "[string f']{[variable x] [operator +] {}}[string !']") MT("nestedFString", "[string f']{[variable b][[ [string f\"c\"] ]]}[string f'] [comment # oops]") })(); ================================================ FILE: third_party/CodeMirror/mode/q/index.html ================================================ CodeMirror: Q mode

Q mode

MIME type defined: text/x-q.

================================================ FILE: third_party/CodeMirror/mode/q/q.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("q",function(config){ var indentUnit=config.indentUnit, curPunc, 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"]), E=/[|/&^!+:\\\-*%$=~#;@><,?_\'\"\[\(\]\)\s{}]/; function buildRE(w){return new RegExp("^("+w.join("|")+")$");} function tokenBase(stream,state){ var sol=stream.sol(),c=stream.next(); curPunc=null; if(sol) if(c=="/") return(state.tokenize=tokenLineComment)(stream,state); else if(c=="\\"){ if(stream.eol()||/\s/.test(stream.peek())) return stream.skipToEnd(),/^\\\s*$/.test(stream.current())?(state.tokenize=tokenCommentToEOF)(stream):state.tokenize=tokenBase,"comment"; else return state.tokenize=tokenBase,"builtin"; } if(/\s/.test(c)) return stream.peek()=="/"?(stream.skipToEnd(),"comment"):"whitespace"; if(c=='"') return(state.tokenize=tokenString)(stream,state); if(c=='`') return stream.eatWhile(/[A-Za-z\d_:\/.]/),"symbol"; if(("."==c&&/\d/.test(stream.peek()))||/\d/.test(c)){ var t=null; stream.backUp(1); if(stream.match(/^\d{4}\.\d{2}(m|\.\d{2}([DT](\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)?)?)/) || stream.match(/^\d+D(\d{2}(:\d{2}(:\d{2}(\.\d{1,9})?)?)?)/) || stream.match(/^\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?/) || stream.match(/^\d+[ptuv]{1}/)) t="temporal"; else if(stream.match(/^0[NwW]{1}/) || stream.match(/^0x[\da-fA-F]*/) || stream.match(/^[01]+[b]{1}/) || stream.match(/^\d+[chijn]{1}/) || stream.match(/-?\d*(\.\d*)?(e[+\-]?\d+)?(e|f)?/)) t="number"; return(t&&(!(c=stream.peek())||E.test(c)))?t:(stream.next(),"error"); } if(/[A-Za-z]|\./.test(c)) return stream.eatWhile(/[A-Za-z._\d]/),keywords.test(stream.current())?"keyword":"variable"; if(/[|/&^!+:\\\-*%$=~#;@><\.,?_\']/.test(c)) return null; if(/[{}\(\[\]\)]/.test(c)) return null; return"error"; } function tokenLineComment(stream,state){ return stream.skipToEnd(),/\/\s*$/.test(stream.current())?(state.tokenize=tokenBlockComment)(stream,state):(state.tokenize=tokenBase),"comment"; } function tokenBlockComment(stream,state){ var f=stream.sol()&&stream.peek()=="\\"; stream.skipToEnd(); if(f&&/^\\\s*$/.test(stream.current())) state.tokenize=tokenBase; return"comment"; } function tokenCommentToEOF(stream){return stream.skipToEnd(),"comment";} function tokenString(stream,state){ var escaped=false,next,end=false; while((next=stream.next())){ if(next=="\""&&!escaped){end=true;break;} escaped=!escaped&&next=="\\"; } if(end)state.tokenize=tokenBase; return"string"; } function pushContext(state,type,col){state.context={prev:state.context,indent:state.indent,col:col,type:type};} function popContext(state){state.indent=state.context.indent;state.context=state.context.prev;} return{ startState:function(){ return{tokenize:tokenBase, context:null, indent:0, col:0}; }, token:function(stream,state){ if(stream.sol()){ if(state.context&&state.context.align==null) state.context.align=false; state.indent=stream.indentation(); } //if (stream.eatSpace()) return null; var style=state.tokenize(stream,state); if(style!="comment"&&state.context&&state.context.align==null&&state.context.type!="pattern"){ state.context.align=true; } if(curPunc=="(")pushContext(state,")",stream.column()); else if(curPunc=="[")pushContext(state,"]",stream.column()); else if(curPunc=="{")pushContext(state,"}",stream.column()); else if(/[\]\}\)]/.test(curPunc)){ while(state.context&&state.context.type=="pattern")popContext(state); if(state.context&&curPunc==state.context.type)popContext(state); } else if(curPunc=="."&&state.context&&state.context.type=="pattern")popContext(state); else if(/atom|string|variable/.test(style)&&state.context){ if(/[\}\]]/.test(state.context.type)) pushContext(state,"pattern",stream.column()); else if(state.context.type=="pattern"&&!state.context.align){ state.context.align=true; state.context.col=stream.column(); } } return style; }, indent:function(state,textAfter){ var firstChar=textAfter&&textAfter.charAt(0); var context=state.context; if(/[\]\}]/.test(firstChar)) while (context&&context.type=="pattern")context=context.prev; var closing=context&&firstChar==context.type; if(!context) return 0; else if(context.type=="pattern") return context.col; else if(context.align) return context.col+(closing?0:1); else return context.indent+(closing?0:indentUnit); } }; }); CodeMirror.defineMIME("text/x-q","q"); }); ================================================ FILE: third_party/CodeMirror/mode/r/index.html ================================================ CodeMirror: R mode

R mode

MIME types defined: text/x-rsrc.

Development of the CodeMirror R mode was kindly sponsored by Ubalo.

================================================ FILE: third_party/CodeMirror/mode/r/r.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.registerHelper("wordChars", "r", /[\w.]/); CodeMirror.defineMode("r", function(config) { function wordObj(words) { var res = {}; for (var i = 0; i < words.length; ++i) res[words[i]] = true; return res; } var commonAtoms = ["NULL", "NA", "Inf", "NaN", "NA_integer_", "NA_real_", "NA_complex_", "NA_character_", "TRUE", "FALSE"]; var commonBuiltins = ["list", "quote", "bquote", "eval", "return", "call", "parse", "deparse"]; var commonKeywords = ["if", "else", "repeat", "while", "function", "for", "in", "next", "break"]; var commonBlockKeywords = ["if", "else", "repeat", "while", "function", "for"]; CodeMirror.registerHelper("hintWords", "r", commonAtoms.concat(commonBuiltins, commonKeywords)); var atoms = wordObj(commonAtoms); var builtins = wordObj(commonBuiltins); var keywords = wordObj(commonKeywords); var blockkeywords = wordObj(commonBlockKeywords); var opChars = /[+\-*\/^<>=!&|~$:]/; var curPunc; function tokenBase(stream, state) { curPunc = null; var ch = stream.next(); if (ch == "#") { stream.skipToEnd(); return "comment"; } else if (ch == "0" && stream.eat("x")) { stream.eatWhile(/[\da-f]/i); return "number"; } else if (ch == "." && stream.eat(/\d/)) { stream.match(/\d*(?:e[+\-]?\d+)?/); return "number"; } else if (/\d/.test(ch)) { stream.match(/\d*(?:\.\d+)?(?:e[+\-]\d+)?L?/); return "number"; } else if (ch == "'" || ch == '"') { state.tokenize = tokenString(ch); return "string"; } else if (ch == "`") { stream.match(/[^`]+`/); return "variable-3"; } else if (ch == "." && stream.match(/.[.\d]+/)) { return "keyword"; } else if (/[\w\.]/.test(ch) && ch != "_") { stream.eatWhile(/[\w\.]/); var word = stream.current(); if (atoms.propertyIsEnumerable(word)) return "atom"; if (keywords.propertyIsEnumerable(word)) { // Block keywords start new blocks, except 'else if', which only starts // one new block for the 'if', no block for the 'else'. if (blockkeywords.propertyIsEnumerable(word) && !stream.match(/\s*if(\s+|$)/, false)) curPunc = "block"; return "keyword"; } if (builtins.propertyIsEnumerable(word)) return "builtin"; return "variable"; } else if (ch == "%") { if (stream.skipTo("%")) stream.next(); return "operator variable-2"; } else if ( (ch == "<" && stream.eat("-")) || (ch == "<" && stream.match("<-")) || (ch == "-" && stream.match(/>>?/)) ) { return "operator arrow"; } else if (ch == "=" && state.ctx.argList) { return "arg-is"; } else if (opChars.test(ch)) { if (ch == "$") return "operator dollar"; stream.eatWhile(opChars); return "operator"; } else if (/[\(\){}\[\];]/.test(ch)) { curPunc = ch; if (ch == ";") return "semi"; return null; } else { return null; } } function tokenString(quote) { return function(stream, state) { if (stream.eat("\\")) { var ch = stream.next(); if (ch == "x") stream.match(/^[a-f0-9]{2}/i); else if ((ch == "u" || ch == "U") && stream.eat("{") && stream.skipTo("}")) stream.next(); else if (ch == "u") stream.match(/^[a-f0-9]{4}/i); else if (ch == "U") stream.match(/^[a-f0-9]{8}/i); else if (/[0-7]/.test(ch)) stream.match(/^[0-7]{1,2}/); return "string-2"; } else { var next; while ((next = stream.next()) != null) { if (next == quote) { state.tokenize = tokenBase; break; } if (next == "\\") { stream.backUp(1); break; } } return "string"; } }; } var ALIGN_YES = 1, ALIGN_NO = 2, BRACELESS = 4 function push(state, type, stream) { state.ctx = {type: type, indent: state.indent, flags: 0, column: stream.column(), prev: state.ctx}; } function setFlag(state, flag) { var ctx = state.ctx state.ctx = {type: ctx.type, indent: ctx.indent, flags: ctx.flags | flag, column: ctx.column, prev: ctx.prev} } function pop(state) { state.indent = state.ctx.indent; state.ctx = state.ctx.prev; } return { startState: function() { return {tokenize: tokenBase, ctx: {type: "top", indent: -config.indentUnit, flags: ALIGN_NO}, indent: 0, afterIdent: false}; }, token: function(stream, state) { if (stream.sol()) { if ((state.ctx.flags & 3) == 0) state.ctx.flags |= ALIGN_NO if (state.ctx.flags & BRACELESS) pop(state) state.indent = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style != "comment" && (state.ctx.flags & ALIGN_NO) == 0) setFlag(state, ALIGN_YES) if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && state.ctx.type == "block") pop(state); if (curPunc == "{") push(state, "}", stream); else if (curPunc == "(") { push(state, ")", stream); if (state.afterIdent) state.ctx.argList = true; } else if (curPunc == "[") push(state, "]", stream); else if (curPunc == "block") push(state, "block", stream); else if (curPunc == state.ctx.type) pop(state); else if (state.ctx.type == "block" && style != "comment") setFlag(state, BRACELESS) state.afterIdent = style == "variable" || style == "keyword"; return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), ctx = state.ctx, closing = firstChar == ctx.type; if (ctx.flags & BRACELESS) ctx = ctx.prev if (ctx.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit); else if (ctx.flags & ALIGN_YES) return ctx.column + (closing ? 0 : 1); else return ctx.indent + (closing ? 0 : config.indentUnit); }, lineComment: "#" }; }); CodeMirror.defineMIME("text/x-rsrc", "r"); }); ================================================ FILE: third_party/CodeMirror/mode/rpm/changes/index.html ================================================ CodeMirror: RPM changes mode

RPM changes mode

MIME types defined: text/x-rpm-changes.

================================================ FILE: third_party/CodeMirror/mode/rpm/index.html ================================================ CodeMirror: RPM changes mode

RPM changes mode

RPM spec mode

MIME types defined: text/x-rpm-spec, text/x-rpm-changes.

================================================ FILE: third_party/CodeMirror/mode/rpm/rpm.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("rpm-changes", function() { var headerSeperator = /^-+$/; 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} - /; var simpleEmail = /^[\w+.-]+@[\w.-]+/; return { token: function(stream) { if (stream.sol()) { if (stream.match(headerSeperator)) { return 'tag'; } if (stream.match(headerLine)) { return 'tag'; } } if (stream.match(simpleEmail)) { return 'string'; } stream.next(); return null; } }; }); CodeMirror.defineMIME("text/x-rpm-changes", "rpm-changes"); // Quick and dirty spec file highlighting CodeMirror.defineMode("rpm-spec", function() { var arch = /^(i386|i586|i686|x86_64|ppc64le|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/; var preamble = /^[a-zA-Z0-9()]+:/; 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)/; var control_flow_complex = /^%(ifnarch|ifarch|if)/; // rpm control flow macros var control_flow_simple = /^%(else|endif)/; // rpm control flow macros var operators = /^(\!|\?|\<\=|\<|\>\=|\>|\=\=|\&\&|\|\|)/; // operators in control flow macros return { startState: function () { return { controlFlow: false, macroParameters: false, section: false }; }, token: function (stream, state) { var ch = stream.peek(); if (ch == "#") { stream.skipToEnd(); return "comment"; } if (stream.sol()) { if (stream.match(preamble)) { return "header"; } if (stream.match(section)) { return "atom"; } } if (stream.match(/^\$\w+/)) { return "def"; } // Variables like '$RPM_BUILD_ROOT' if (stream.match(/^\$\{\w+\}/)) { return "def"; } // Variables like '${RPM_BUILD_ROOT}' if (stream.match(control_flow_simple)) { return "keyword"; } if (stream.match(control_flow_complex)) { state.controlFlow = true; return "keyword"; } if (state.controlFlow) { if (stream.match(operators)) { return "operator"; } if (stream.match(/^(\d+)/)) { return "number"; } if (stream.eol()) { state.controlFlow = false; } } if (stream.match(arch)) { if (stream.eol()) { state.controlFlow = false; } return "number"; } // Macros like '%make_install' or '%attr(0775,root,root)' if (stream.match(/^%[\w]+/)) { if (stream.match(/^\(/)) { state.macroParameters = true; } return "keyword"; } if (state.macroParameters) { if (stream.match(/^\d+/)) { return "number";} if (stream.match(/^\)/)) { state.macroParameters = false; return "keyword"; } } // Macros like '%{defined fedora}' if (stream.match(/^%\{\??[\w \-\:\!]+\}/)) { if (stream.eol()) { state.controlFlow = false; } return "def"; } //TODO: Include bash script sub-parser (CodeMirror supports that) stream.next(); return null; } }; }); CodeMirror.defineMIME("text/x-rpm-spec", "rpm-spec"); }); ================================================ FILE: third_party/CodeMirror/mode/rst/index.html ================================================ CodeMirror: reStructuredText mode

reStructuredText mode

The python mode will be used for highlighting blocks containing Python/IPython terminal sessions: blocks starting with >>> (for Python) or In [num]: (for IPython). Further, the stex mode will be used for highlighting blocks containing LaTex code.

MIME types defined: text/x-rst.

================================================ FILE: third_party/CodeMirror/mode/rst/rst.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../python/python"), require("../stex/stex"), require("../../addon/mode/overlay")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../python/python", "../stex/stex", "../../addon/mode/overlay"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('rst', function (config, options) { var rx_strong = /^\*\*[^\*\s](?:[^\*]*[^\*\s])?\*\*/; var rx_emphasis = /^\*[^\*\s](?:[^\*]*[^\*\s])?\*/; var rx_literal = /^``[^`\s](?:[^`]*[^`\s])``/; var rx_number = /^(?:[\d]+(?:[\.,]\d+)*)/; var rx_positive = /^(?:\s\+[\d]+(?:[\.,]\d+)*)/; var rx_negative = /^(?:\s\-[\d]+(?:[\.,]\d+)*)/; var rx_uri_protocol = "[Hh][Tt][Tt][Pp][Ss]?://"; var rx_uri_domain = "(?:[\\d\\w.-]+)\\.(?:\\w{2,6})"; var rx_uri_path = "(?:/[\\d\\w\\#\\%\\&\\-\\.\\,\\/\\:\\=\\?\\~]+)*"; var rx_uri = new RegExp("^" + rx_uri_protocol + rx_uri_domain + rx_uri_path); var overlay = { token: function (stream) { if (stream.match(rx_strong) && stream.match (/\W+|$/, false)) return 'strong'; if (stream.match(rx_emphasis) && stream.match (/\W+|$/, false)) return 'em'; if (stream.match(rx_literal) && stream.match (/\W+|$/, false)) return 'string-2'; if (stream.match(rx_number)) return 'number'; if (stream.match(rx_positive)) return 'positive'; if (stream.match(rx_negative)) return 'negative'; if (stream.match(rx_uri)) return 'link'; while (stream.next() != null) { if (stream.match(rx_strong, false)) break; if (stream.match(rx_emphasis, false)) break; if (stream.match(rx_literal, false)) break; if (stream.match(rx_number, false)) break; if (stream.match(rx_positive, false)) break; if (stream.match(rx_negative, false)) break; if (stream.match(rx_uri, false)) break; } return null; } }; var mode = CodeMirror.getMode( config, options.backdrop || 'rst-base' ); return CodeMirror.overlayMode(mode, overlay, true); // combine }, 'python', 'stex'); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// CodeMirror.defineMode('rst-base', function (config) { /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function format(string) { var args = Array.prototype.slice.call(arguments, 1); return string.replace(/{(\d+)}/g, function (match, n) { return typeof args[n] != 'undefined' ? args[n] : match; }); } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// var mode_python = CodeMirror.getMode(config, 'python'); var mode_stex = CodeMirror.getMode(config, 'stex'); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// var SEPA = "\\s+"; var TAIL = "(?:\\s*|\\W|$)", rx_TAIL = new RegExp(format('^{0}', TAIL)); var NAME = "(?:[^\\W\\d_](?:[\\w!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)", rx_NAME = new RegExp(format('^{0}', NAME)); var NAME_WWS = "(?:[^\\W\\d_](?:[\\w\\s!\"#$%&'()\\*\\+,\\-\\.\/:;<=>\\?]*[^\\W_])?)"; var REF_NAME = format('(?:{0}|`{1}`)', NAME, NAME_WWS); var TEXT1 = "(?:[^\\s\\|](?:[^\\|]*[^\\s\\|])?)"; var TEXT2 = "(?:[^\\`]+)", rx_TEXT2 = new RegExp(format('^{0}', TEXT2)); var rx_section = new RegExp( "^([!'#$%&\"()*+,-./:;<=>?@\\[\\\\\\]^_`{|}~])\\1{3,}\\s*$"); var rx_explicit = new RegExp( format('^\\.\\.{0}', SEPA)); var rx_link = new RegExp( format('^_{0}:{1}|^__:{1}', REF_NAME, TAIL)); var rx_directive = new RegExp( format('^{0}::{1}', REF_NAME, TAIL)); var rx_substitution = new RegExp( format('^\\|{0}\\|{1}{2}::{3}', TEXT1, SEPA, REF_NAME, TAIL)); var rx_footnote = new RegExp( format('^\\[(?:\\d+|#{0}?|\\*)]{1}', REF_NAME, TAIL)); var rx_citation = new RegExp( format('^\\[{0}\\]{1}', REF_NAME, TAIL)); var rx_substitution_ref = new RegExp( format('^\\|{0}\\|', TEXT1)); var rx_footnote_ref = new RegExp( format('^\\[(?:\\d+|#{0}?|\\*)]_', REF_NAME)); var rx_citation_ref = new RegExp( format('^\\[{0}\\]_', REF_NAME)); var rx_link_ref1 = new RegExp( format('^{0}__?', REF_NAME)); var rx_link_ref2 = new RegExp( format('^`{0}`_', TEXT2)); var rx_role_pre = new RegExp( format('^:{0}:`{1}`{2}', NAME, TEXT2, TAIL)); var rx_role_suf = new RegExp( format('^`{1}`:{0}:{2}', NAME, TEXT2, TAIL)); var rx_role = new RegExp( format('^:{0}:{1}', NAME, TAIL)); var rx_directive_name = new RegExp(format('^{0}', REF_NAME)); var rx_directive_tail = new RegExp(format('^::{0}', TAIL)); var rx_substitution_text = new RegExp(format('^\\|{0}\\|', TEXT1)); var rx_substitution_sepa = new RegExp(format('^{0}', SEPA)); var rx_substitution_name = new RegExp(format('^{0}', REF_NAME)); var rx_substitution_tail = new RegExp(format('^::{0}', TAIL)); var rx_link_head = new RegExp("^_"); var rx_link_name = new RegExp(format('^{0}|_', REF_NAME)); var rx_link_tail = new RegExp(format('^:{0}', TAIL)); var rx_verbatim = new RegExp('^::\\s*$'); var rx_examples = new RegExp('^\\s+(?:>>>|In \\[\\d+\\]:)\\s'); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_normal(stream, state) { var token = null; if (stream.sol() && stream.match(rx_examples, false)) { change(state, to_mode, { mode: mode_python, local: CodeMirror.startState(mode_python) }); } else if (stream.sol() && stream.match(rx_explicit)) { change(state, to_explicit); token = 'meta'; } else if (stream.sol() && stream.match(rx_section)) { change(state, to_normal); token = 'header'; } else if (phase(state) == rx_role_pre || stream.match(rx_role_pre, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_role_pre, 1)); stream.match(/^:/); token = 'meta'; break; case 1: change(state, to_normal, context(rx_role_pre, 2)); stream.match(rx_NAME); token = 'keyword'; if (stream.current().match(/^(?:math|latex)/)) { state.tmp_stex = true; } break; case 2: change(state, to_normal, context(rx_role_pre, 3)); stream.match(/^:`/); token = 'meta'; break; case 3: if (state.tmp_stex) { state.tmp_stex = undefined; state.tmp = { mode: mode_stex, local: CodeMirror.startState(mode_stex) }; } if (state.tmp) { if (stream.peek() == '`') { change(state, to_normal, context(rx_role_pre, 4)); state.tmp = undefined; break; } token = state.tmp.mode.token(stream, state.tmp.local); break; } change(state, to_normal, context(rx_role_pre, 4)); stream.match(rx_TEXT2); token = 'string'; break; case 4: change(state, to_normal, context(rx_role_pre, 5)); stream.match(/^`/); token = 'meta'; break; case 5: change(state, to_normal, context(rx_role_pre, 6)); stream.match(rx_TAIL); break; default: change(state, to_normal); } } else if (phase(state) == rx_role_suf || stream.match(rx_role_suf, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_role_suf, 1)); stream.match(/^`/); token = 'meta'; break; case 1: change(state, to_normal, context(rx_role_suf, 2)); stream.match(rx_TEXT2); token = 'string'; break; case 2: change(state, to_normal, context(rx_role_suf, 3)); stream.match(/^`:/); token = 'meta'; break; case 3: change(state, to_normal, context(rx_role_suf, 4)); stream.match(rx_NAME); token = 'keyword'; break; case 4: change(state, to_normal, context(rx_role_suf, 5)); stream.match(/^:/); token = 'meta'; break; case 5: change(state, to_normal, context(rx_role_suf, 6)); stream.match(rx_TAIL); break; default: change(state, to_normal); } } else if (phase(state) == rx_role || stream.match(rx_role, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_role, 1)); stream.match(/^:/); token = 'meta'; break; case 1: change(state, to_normal, context(rx_role, 2)); stream.match(rx_NAME); token = 'keyword'; break; case 2: change(state, to_normal, context(rx_role, 3)); stream.match(/^:/); token = 'meta'; break; case 3: change(state, to_normal, context(rx_role, 4)); stream.match(rx_TAIL); break; default: change(state, to_normal); } } else if (phase(state) == rx_substitution_ref || stream.match(rx_substitution_ref, false)) { switch (stage(state)) { case 0: change(state, to_normal, context(rx_substitution_ref, 1)); stream.match(rx_substitution_text); token = 'variable-2'; break; case 1: change(state, to_normal, context(rx_substitution_ref, 2)); if (stream.match(/^_?_?/)) token = 'link'; break; default: change(state, to_normal); } } else if (stream.match(rx_footnote_ref)) { change(state, to_normal); token = 'quote'; } else if (stream.match(rx_citation_ref)) { change(state, to_normal); token = 'quote'; } else if (stream.match(rx_link_ref1)) { change(state, to_normal); if (!stream.peek() || stream.peek().match(/^\W$/)) { token = 'link'; } } else if (phase(state) == rx_link_ref2 || stream.match(rx_link_ref2, false)) { switch (stage(state)) { case 0: if (!stream.peek() || stream.peek().match(/^\W$/)) { change(state, to_normal, context(rx_link_ref2, 1)); } else { stream.match(rx_link_ref2); } break; case 1: change(state, to_normal, context(rx_link_ref2, 2)); stream.match(/^`/); token = 'link'; break; case 2: change(state, to_normal, context(rx_link_ref2, 3)); stream.match(rx_TEXT2); break; case 3: change(state, to_normal, context(rx_link_ref2, 4)); stream.match(/^`_/); token = 'link'; break; default: change(state, to_normal); } } else if (stream.match(rx_verbatim)) { change(state, to_verbatim); } else { if (stream.next()) change(state, to_normal); } return token; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_explicit(stream, state) { var token = null; if (phase(state) == rx_substitution || stream.match(rx_substitution, false)) { switch (stage(state)) { case 0: change(state, to_explicit, context(rx_substitution, 1)); stream.match(rx_substitution_text); token = 'variable-2'; break; case 1: change(state, to_explicit, context(rx_substitution, 2)); stream.match(rx_substitution_sepa); break; case 2: change(state, to_explicit, context(rx_substitution, 3)); stream.match(rx_substitution_name); token = 'keyword'; break; case 3: change(state, to_explicit, context(rx_substitution, 4)); stream.match(rx_substitution_tail); token = 'meta'; break; default: change(state, to_normal); } } else if (phase(state) == rx_directive || stream.match(rx_directive, false)) { switch (stage(state)) { case 0: change(state, to_explicit, context(rx_directive, 1)); stream.match(rx_directive_name); token = 'keyword'; if (stream.current().match(/^(?:math|latex)/)) state.tmp_stex = true; else if (stream.current().match(/^python/)) state.tmp_py = true; break; case 1: change(state, to_explicit, context(rx_directive, 2)); stream.match(rx_directive_tail); token = 'meta'; if (stream.match(/^latex\s*$/) || state.tmp_stex) { state.tmp_stex = undefined; change(state, to_mode, { mode: mode_stex, local: CodeMirror.startState(mode_stex) }); } break; case 2: change(state, to_explicit, context(rx_directive, 3)); if (stream.match(/^python\s*$/) || state.tmp_py) { state.tmp_py = undefined; change(state, to_mode, { mode: mode_python, local: CodeMirror.startState(mode_python) }); } break; default: change(state, to_normal); } } else if (phase(state) == rx_link || stream.match(rx_link, false)) { switch (stage(state)) { case 0: change(state, to_explicit, context(rx_link, 1)); stream.match(rx_link_head); stream.match(rx_link_name); token = 'link'; break; case 1: change(state, to_explicit, context(rx_link, 2)); stream.match(rx_link_tail); token = 'meta'; break; default: change(state, to_normal); } } else if (stream.match(rx_footnote)) { change(state, to_normal); token = 'quote'; } else if (stream.match(rx_citation)) { change(state, to_normal); token = 'quote'; } else { stream.eatSpace(); if (stream.eol()) { change(state, to_normal); } else { stream.skipToEnd(); change(state, to_comment); token = 'comment'; } } return token; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_comment(stream, state) { return as_block(stream, state, 'comment'); } function to_verbatim(stream, state) { return as_block(stream, state, 'meta'); } function as_block(stream, state, token) { if (stream.eol() || stream.eatSpace()) { stream.skipToEnd(); return token; } else { change(state, to_normal); return null; } } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function to_mode(stream, state) { if (state.ctx.mode && state.ctx.local) { if (stream.sol()) { if (!stream.eatSpace()) change(state, to_normal); return null; } return state.ctx.mode.token(stream, state.ctx.local); } change(state, to_normal); return null; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// function context(phase, stage, mode, local) { return {phase: phase, stage: stage, mode: mode, local: local}; } function change(state, tok, ctx) { state.tok = tok; state.ctx = ctx || {}; } function stage(state) { return state.ctx.stage || 0; } function phase(state) { return state.ctx.phase; } /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// return { startState: function () { return {tok: to_normal, ctx: context(undefined, 0)}; }, copyState: function (state) { var ctx = state.ctx, tmp = state.tmp; if (ctx.local) ctx = {mode: ctx.mode, local: CodeMirror.copyState(ctx.mode, ctx.local)}; if (tmp) tmp = {mode: tmp.mode, local: CodeMirror.copyState(tmp.mode, tmp.local)}; return {tok: state.tok, ctx: ctx, tmp: tmp}; }, innerMode: function (state) { return state.tmp ? {state: state.tmp.local, mode: state.tmp.mode} : state.ctx.mode ? {state: state.ctx.local, mode: state.ctx.mode} : null; }, token: function (stream, state) { return state.tok(stream, state); } }; }, 'python', 'stex'); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// CodeMirror.defineMIME('text/x-rst', 'rst'); /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// }); ================================================ FILE: third_party/CodeMirror/mode/ruby/index.html ================================================ CodeMirror: Ruby mode

Ruby mode

MIME types defined: text/x-ruby.

Development of the CodeMirror Ruby mode was kindly sponsored by Ubalo.

================================================ FILE: third_party/CodeMirror/mode/ruby/ruby.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("ruby", function(config) { function wordObj(words) { var o = {}; for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; return o; } var keywords = wordObj([ "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else", "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or", "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless", "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc", "caller", "lambda", "proc", "public", "protected", "private", "require", "load", "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__" ]); var indentWords = wordObj(["def", "class", "case", "for", "while", "until", "module", "then", "catch", "loop", "proc", "begin"]); var dedentWords = wordObj(["end", "until"]); var matching = {"[": "]", "{": "}", "(": ")"}; var curPunc; function chain(newtok, stream, state) { state.tokenize.push(newtok); return newtok(stream, state); } function tokenBase(stream, state) { if (stream.sol() && stream.match("=begin") && stream.eol()) { state.tokenize.push(readBlockComment); return "comment"; } if (stream.eatSpace()) return null; var ch = stream.next(), m; if (ch == "`" || ch == "'" || ch == '"') { return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state); } else if (ch == "/") { if (regexpAhead(stream)) return chain(readQuoted(ch, "string-2", true), stream, state); else return "operator"; } else if (ch == "%") { var style = "string", embed = true; if (stream.eat("s")) style = "atom"; else if (stream.eat(/[WQ]/)) style = "string"; else if (stream.eat(/[r]/)) style = "string-2"; else if (stream.eat(/[wxq]/)) { style = "string"; embed = false; } var delim = stream.eat(/[^\w\s=]/); if (!delim) return "operator"; if (matching.propertyIsEnumerable(delim)) delim = matching[delim]; return chain(readQuoted(delim, style, embed, true), stream, state); } else if (ch == "#") { stream.skipToEnd(); return "comment"; } else if (ch == "<" && (m = stream.match(/^<(-)?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) { return chain(readHereDoc(m[2], m[1]), stream, state); } else if (ch == "0") { if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/); else if (stream.eat("b")) stream.eatWhile(/[01]/); else stream.eatWhile(/[0-7]/); return "number"; } else if (/\d/.test(ch)) { stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/); return "number"; } else if (ch == "?") { while (stream.match(/^\\[CM]-/)) {} if (stream.eat("\\")) stream.eatWhile(/\w/); else stream.next(); return "string"; } else if (ch == ":") { if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state); if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state); // :> :>> :< :<< are valid symbols if (stream.eat(/[\<\>]/)) { stream.eat(/[\<\>]/); return "atom"; } // :+ :- :/ :* :| :& :! are valid symbols if (stream.eat(/[\+\-\*\/\&\|\:\!]/)) { return "atom"; } // Symbols can't start by a digit if (stream.eat(/[a-zA-Z$@_\xa1-\uffff]/)) { stream.eatWhile(/[\w$\xa1-\uffff]/); // Only one ? ! = is allowed and only as the last character stream.eat(/[\?\!\=]/); return "atom"; } return "operator"; } else if (ch == "@" && stream.match(/^@?[a-zA-Z_\xa1-\uffff]/)) { stream.eat("@"); stream.eatWhile(/[\w\xa1-\uffff]/); return "variable-2"; } else if (ch == "$") { if (stream.eat(/[a-zA-Z_]/)) { stream.eatWhile(/[\w]/); } else if (stream.eat(/\d/)) { stream.eat(/\d/); } else { stream.next(); // Must be a special global like $: or $! } return "variable-3"; } else if (/[a-zA-Z_\xa1-\uffff]/.test(ch)) { stream.eatWhile(/[\w\xa1-\uffff]/); stream.eat(/[\?\!]/); if (stream.eat(":")) return "atom"; return "ident"; } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) { curPunc = "|"; return null; } else if (/[\(\)\[\]{}\\;]/.test(ch)) { curPunc = ch; return null; } else if (ch == "-" && stream.eat(">")) { return "arrow"; } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) { var more = stream.eatWhile(/[=+\-\/*:\.^%<>~|]/); if (ch == "." && !more) curPunc = "."; return "operator"; } else { return null; } } function regexpAhead(stream) { var start = stream.pos, depth = 0, next, found = false, escaped = false while ((next = stream.next()) != null) { if (!escaped) { if ("[{(".indexOf(next) > -1) { depth++ } else if ("]})".indexOf(next) > -1) { depth-- if (depth < 0) break } else if (next == "/" && depth == 0) { found = true break } escaped = next == "\\" } else { escaped = false } } stream.backUp(stream.pos - start) return found } function tokenBaseUntilBrace(depth) { if (!depth) depth = 1; return function(stream, state) { if (stream.peek() == "}") { if (depth == 1) { state.tokenize.pop(); return state.tokenize[state.tokenize.length-1](stream, state); } else { state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth - 1); } } else if (stream.peek() == "{") { state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth + 1); } return tokenBase(stream, state); }; } function tokenBaseOnce() { var alreadyCalled = false; return function(stream, state) { if (alreadyCalled) { state.tokenize.pop(); return state.tokenize[state.tokenize.length-1](stream, state); } alreadyCalled = true; return tokenBase(stream, state); }; } function readQuoted(quote, style, embed, unescaped) { return function(stream, state) { var escaped = false, ch; if (state.context.type === 'read-quoted-paused') { state.context = state.context.prev; stream.eat("}"); } while ((ch = stream.next()) != null) { if (ch == quote && (unescaped || !escaped)) { state.tokenize.pop(); break; } if (embed && ch == "#" && !escaped) { if (stream.eat("{")) { if (quote == "}") { state.context = {prev: state.context, type: 'read-quoted-paused'}; } state.tokenize.push(tokenBaseUntilBrace()); break; } else if (/[@\$]/.test(stream.peek())) { state.tokenize.push(tokenBaseOnce()); break; } } escaped = !escaped && ch == "\\"; } return style; }; } function readHereDoc(phrase, mayIndent) { return function(stream, state) { if (mayIndent) stream.eatSpace() if (stream.match(phrase)) state.tokenize.pop(); else stream.skipToEnd(); return "string"; }; } function readBlockComment(stream, state) { if (stream.sol() && stream.match("=end") && stream.eol()) state.tokenize.pop(); stream.skipToEnd(); return "comment"; } return { startState: function() { return {tokenize: [tokenBase], indented: 0, context: {type: "top", indented: -config.indentUnit}, continuedLine: false, lastTok: null, varList: false}; }, token: function(stream, state) { curPunc = null; if (stream.sol()) state.indented = stream.indentation(); var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype; var thisTok = curPunc; if (style == "ident") { var word = stream.current(); style = state.lastTok == "." ? "property" : keywords.propertyIsEnumerable(stream.current()) ? "keyword" : /^[A-Z]/.test(word) ? "tag" : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def" : "variable"; if (style == "keyword") { thisTok = word; if (indentWords.propertyIsEnumerable(word)) kwtype = "indent"; else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent"; else if ((word == "if" || word == "unless") && stream.column() == stream.indentation()) kwtype = "indent"; else if (word == "do" && state.context.indented < state.indented) kwtype = "indent"; } } if (curPunc || (style && style != "comment")) state.lastTok = thisTok; if (curPunc == "|") state.varList = !state.varList; if (kwtype == "indent" || /[\(\[\{]/.test(curPunc)) state.context = {prev: state.context, type: curPunc || style, indented: state.indented}; else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev) state.context = state.context.prev; if (stream.eol()) state.continuedLine = (curPunc == "\\" || style == "operator"); return style; }, indent: function(state, textAfter) { if (state.tokenize[state.tokenize.length-1] != tokenBase) return CodeMirror.Pass; var firstChar = textAfter && textAfter.charAt(0); var ct = state.context; var closing = ct.type == matching[firstChar] || ct.type == "keyword" && /^(?:end|until|else|elsif|when|rescue)\b/.test(textAfter); return ct.indented + (closing ? 0 : config.indentUnit) + (state.continuedLine ? config.indentUnit : 0); }, electricInput: /^\s*(?:end|rescue|elsif|else|\})$/, lineComment: "#", fold: "indent" }; }); CodeMirror.defineMIME("text/x-ruby", "ruby"); }); ================================================ FILE: third_party/CodeMirror/mode/ruby/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "ruby"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("divide_equal_operator", "[variable bar] [operator /=] [variable foo]"); MT("divide_equal_operator_no_spacing", "[variable foo][operator /=][number 42]"); MT("complex_regexp", "[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]") MT("indented_heredoc", "[keyword def] [def x]", " [variable y] [operator =] [string <<-FOO]", "[string bar]", "[string FOO]", "[keyword end]") })(); ================================================ FILE: third_party/CodeMirror/mode/rust/index.html ================================================ CodeMirror: Rust mode

Rust mode

MIME types defined: text/x-rustsrc.

================================================ FILE: third_party/CodeMirror/mode/rust/rust.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/simple")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../addon/mode/simple"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineSimpleMode("rust",{ start: [ // string and byte string {regex: /b?"/, token: "string", next: "string"}, // raw string and raw byte string {regex: /b?r"/, token: "string", next: "string_raw"}, {regex: /b?r#+"/, token: "string", next: "string_raw_hash"}, // character {regex: /'(?:[^'\\]|\\(?:[nrt0'"]|x[\da-fA-F]{2}|u\{[\da-fA-F]{6}\}))'/, token: "string-2"}, // byte {regex: /b'(?:[^']|\\(?:['\\nrt0]|x[\da-fA-F]{2}))'/, token: "string-2"}, {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)?/, token: "number"}, {regex: /(let(?:\s+mut)?|fn|enum|mod|struct|type)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/, token: ["keyword", null, "def"]}, {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"}, {regex: /\b(?:Self|isize|usize|char|bool|u8|u16|u32|u64|f16|f32|f64|i8|i16|i32|i64|str|Option)\b/, token: "atom"}, {regex: /\b(?:true|false|Some|None|Ok|Err)\b/, token: "builtin"}, {regex: /\b(fn)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/, token: ["keyword", null ,"def"]}, {regex: /#!?\[.*\]/, token: "meta"}, {regex: /\/\/.*/, token: "comment"}, {regex: /\/\*/, token: "comment", next: "comment"}, {regex: /[-+\/*=<>!]+/, token: "operator"}, {regex: /[a-zA-Z_]\w*!/,token: "variable-3"}, {regex: /[a-zA-Z_]\w*/, token: "variable"}, {regex: /[\{\[\(]/, indent: true}, {regex: /[\}\]\)]/, dedent: true} ], string: [ {regex: /"/, token: "string", next: "start"}, {regex: /(?:[^\\"]|\\(?:.|$))*/, token: "string"} ], string_raw: [ {regex: /"/, token: "string", next: "start"}, {regex: /[^"]*/, token: "string"} ], string_raw_hash: [ {regex: /"#+/, token: "string", next: "start"}, {regex: /(?:[^"]|"(?!#))*/, token: "string"} ], comment: [ {regex: /.*?\*\//, token: "comment", next: "start"}, {regex: /.*/, token: "comment"} ], meta: { dontIndentStates: ["comment"], electricInput: /^\s*\}$/, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//", fold: "brace" } }); CodeMirror.defineMIME("text/x-rustsrc", "rust"); CodeMirror.defineMIME("text/rust", "rust"); }); ================================================ FILE: third_party/CodeMirror/mode/rust/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 4}, "rust"); function MT(name) {test.mode(name, mode, Array.prototype.slice.call(arguments, 1));} MT('integer_test', '[number 123i32]', '[number 123u32]', '[number 123_u32]', '[number 0xff_u8]', '[number 0o70_i16]', '[number 0b1111_1111_1001_0000_i32]', '[number 0usize]'); MT('float_test', '[number 123.0f64]', '[number 0.1f64]', '[number 0.1f32]', '[number 12E+99_f64]'); MT('string-literals-test', '[string "foo"]', '[string r"foo"]', '[string "\\"foo\\""]', '[string r#""foo""#]', '[string "foo #\\"# bar"]', '[string b"foo"]', '[string br"foo"]', '[string b"\\"foo\\""]', '[string br#""foo""#]', '[string br##"foo #" bar"##]', "[string-2 'h']", "[string-2 b'h']"); })(); ================================================ FILE: third_party/CodeMirror/mode/sas/index.html ================================================ CodeMirror: SAS mode

SAS mode

MIME types defined: text/x-sas.

================================================ FILE: third_party/CodeMirror/mode/sas/sas.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // SAS mode copyright (c) 2016 Jared Dean, SAS Institute // Created by Jared Dean // TODO // indent and de-indent // identify macro variables //Definitions // comment -- text within * ; or /* */ // keyword -- SAS language variable // variable -- macro variables starts with '&' or variable formats // variable-2 -- DATA Step, proc, or macro names // string -- text within ' ' or " " // operator -- numeric operator + / - * ** le eq ge ... and so on // builtin -- proc %macro data run mend // atom // def (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sas", function () { var words = {}; var isDoubleOperatorSym = { eq: 'operator', lt: 'operator', le: 'operator', gt: 'operator', ge: 'operator', "in": 'operator', ne: 'operator', or: 'operator' }; var isDoubleOperatorChar = /(<=|>=|!=|<>)/; var isSingleOperatorChar = /[=\(:\),{}.*<>+\-\/^\[\]]/; // Takes a string of words separated by spaces and adds them as // keys with the value of the first argument 'style' function define(style, string, context) { if (context) { var split = string.split(' '); for (var i = 0; i < split.length; i++) { words[split[i]] = {style: style, state: context}; } } } //datastep define('def', 'stack pgm view source debug nesting nolist', ['inDataStep']); define('def', 'if while until for do do; end end; then else cancel', ['inDataStep']); define('def', 'label format _n_ _error_', ['inDataStep']); 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']); define('def', 'filevar finfo finv fipname fipnamel fipstate first firstobs floor', ['inDataStep']); 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']); define('def', 'zipfips zipname zipnamel zipstate', ['inDataStep']); define('def', 'put putc putn', ['inDataStep']); define('builtin', 'data run', ['inDataStep']); //proc define('def', 'data', ['inProc']); // flow control for macros define('def', '%if %end %end; %else %else; %do %do; %then', ['inMacro']); //everywhere define('builtin', 'proc run; quit; libname filename %macro %mend option options', ['ALL']); define('def', 'footnote title libname ods', ['ALL']); define('def', '%let %put %global %sysfunc %eval ', ['ALL']); // automatic macro variables http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a003167023.htm 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']); //footnote[1-9]? title[1-9]? //options statement define('def', 'source2 nosource2 page pageno pagesize', ['ALL']); //proc and datastep 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']); define('operator', 'and not ', ['inDataStep', 'inProc']); // Main function function tokenize(stream, state) { // Finally advance the stream var ch = stream.next(); // BLOCKCOMMENT if (ch === '/' && stream.eat('*')) { state.continueComment = true; return "comment"; } else if (state.continueComment === true) { // in comment block //comment ends at the beginning of the line if (ch === '*' && stream.peek() === '/') { stream.next(); state.continueComment = false; } else if (stream.skipTo('*')) { //comment is potentially later in line stream.skipTo('*'); stream.next(); if (stream.eat('/')) state.continueComment = false; } else { stream.skipToEnd(); } return "comment"; } if (ch == "*" && stream.column() == stream.indentation()) { stream.skipToEnd() return "comment" } // DoubleOperator match var doubleOperator = ch + stream.peek(); if ((ch === '"' || ch === "'") && !state.continueString) { state.continueString = ch return "string" } else if (state.continueString) { if (state.continueString == ch) { state.continueString = null; } else if (stream.skipTo(state.continueString)) { // quote found on this line stream.next(); state.continueString = null; } else { stream.skipToEnd(); } return "string"; } else if (state.continueString !== null && stream.eol()) { stream.skipTo(state.continueString) || stream.skipToEnd(); return "string"; } else if (/[\d\.]/.test(ch)) { //find numbers if (ch === ".") stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/); else if (ch === "0") stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/); else stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/); return "number"; } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS stream.next(); return "operator"; } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) { stream.next(); if (stream.peek() === ' ') return isDoubleOperatorSym[doubleOperator.toLowerCase()]; } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS return "operator"; } // Matches one whole word -- even if the word is a character var word; if (stream.match(/[%&;\w]+/, false) != null) { word = ch + stream.match(/[%&;\w]+/, true); if (/&/.test(word)) return 'variable' } else { word = ch; } // the word after DATA PROC or MACRO if (state.nextword) { stream.match(/[\w]+/); // match memname.libname if (stream.peek() === '.') stream.skipTo(' '); state.nextword = false; return 'variable-2'; } word = word.toLowerCase() // Are we in a DATA Step? if (state.inDataStep) { if (word === 'run;' || stream.match(/run\s;/)) { state.inDataStep = false; return 'builtin'; } // variable formats if ((word) && stream.next() === '.') { //either a format or libname.memname if (/\w/.test(stream.peek())) return 'variable-2'; else return 'variable'; } // do we have a DATA Step keyword if (word && words.hasOwnProperty(word) && (words[word].state.indexOf("inDataStep") !== -1 || words[word].state.indexOf("ALL") !== -1)) { //backup to the start of the word if (stream.start < stream.pos) stream.backUp(stream.pos - stream.start); //advance the length of the word and return for (var i = 0; i < word.length; ++i) stream.next(); return words[word].style; } } // Are we in an Proc statement? if (state.inProc) { if (word === 'run;' || word === 'quit;') { state.inProc = false; return 'builtin'; } // do we have a proc keyword if (word && words.hasOwnProperty(word) && (words[word].state.indexOf("inProc") !== -1 || words[word].state.indexOf("ALL") !== -1)) { stream.match(/[\w]+/); return words[word].style; } } // Are we in a Macro statement? if (state.inMacro) { if (word === '%mend') { if (stream.peek() === ';') stream.next(); state.inMacro = false; return 'builtin'; } if (word && words.hasOwnProperty(word) && (words[word].state.indexOf("inMacro") !== -1 || words[word].state.indexOf("ALL") !== -1)) { stream.match(/[\w]+/); return words[word].style; } return 'atom'; } // Do we have Keywords specific words? if (word && words.hasOwnProperty(word)) { // Negates the initial next() stream.backUp(1); // Actually move the stream stream.match(/[\w]+/); if (word === 'data' && /=/.test(stream.peek()) === false) { state.inDataStep = true; state.nextword = true; return 'builtin'; } if (word === 'proc') { state.inProc = true; state.nextword = true; return 'builtin'; } if (word === '%macro') { state.inMacro = true; state.nextword = true; return 'builtin'; } if (/title[1-9]/.test(word)) return 'def'; if (word === 'footnote') { stream.eat(/[1-9]/); return 'def'; } // Returns their value as state in the prior define methods if (state.inDataStep === true && words[word].state.indexOf("inDataStep") !== -1) return words[word].style; if (state.inProc === true && words[word].state.indexOf("inProc") !== -1) return words[word].style; if (state.inMacro === true && words[word].state.indexOf("inMacro") !== -1) return words[word].style; if (words[word].state.indexOf("ALL") !== -1) return words[word].style; return null; } // Unrecognized syntax return null; } return { startState: function () { return { inDataStep: false, inProc: false, inMacro: false, nextword: false, continueString: null, continueComment: false }; }, token: function (stream, state) { // Strip the spaces, but regex will account for them either way if (stream.eatSpace()) return null; // Go through the main process return tokenize(stream, state); }, blockCommentStart: "/*", blockCommentEnd: "*/" }; }); CodeMirror.defineMIME("text/x-sas", "sas"); }); ================================================ FILE: third_party/CodeMirror/mode/sass/index.html ================================================ CodeMirror: Sass mode

Sass mode

MIME types defined: text/x-sass.

================================================ FILE: third_party/CodeMirror/mode/sass/sass.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../css/css")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../css/css"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sass", function(config) { var cssMode = CodeMirror.mimeModes["text/css"]; var propertyKeywords = cssMode.propertyKeywords || {}, colorKeywords = cssMode.colorKeywords || {}, valueKeywords = cssMode.valueKeywords || {}, fontProperties = cssMode.fontProperties || {}; function tokenRegexp(words) { return new RegExp("^" + words.join("|")); } var keywords = ["true", "false", "null", "auto"]; var keywordsRegexp = new RegExp("^" + keywords.join("|")); var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", "\\!=", "/", "\\*", "%", "and", "or", "not", ";","\\{","\\}",":"]; var opRegexp = tokenRegexp(operators); var pseudoElementsRegexp = /^::?[a-zA-Z_][\w\-]*/; var word; function isEndLine(stream) { return !stream.peek() || stream.match(/\s+$/, false); } function urlTokens(stream, state) { var ch = stream.peek(); if (ch === ")") { stream.next(); state.tokenizer = tokenBase; return "operator"; } else if (ch === "(") { stream.next(); stream.eatSpace(); return "operator"; } else if (ch === "'" || ch === '"') { state.tokenizer = buildStringTokenizer(stream.next()); return "string"; } else { state.tokenizer = buildStringTokenizer(")", false); return "string"; } } function comment(indentation, multiLine) { return function(stream, state) { if (stream.sol() && stream.indentation() <= indentation) { state.tokenizer = tokenBase; return tokenBase(stream, state); } if (multiLine && stream.skipTo("*/")) { stream.next(); stream.next(); state.tokenizer = tokenBase; } else { stream.skipToEnd(); } return "comment"; }; } function buildStringTokenizer(quote, greedy) { if (greedy == null) { greedy = true; } function stringTokenizer(stream, state) { var nextChar = stream.next(); var peekChar = stream.peek(); var previousChar = stream.string.charAt(stream.pos-2); var endingString = ((nextChar !== "\\" && peekChar === quote) || (nextChar === quote && previousChar !== "\\")); if (endingString) { if (nextChar !== quote && greedy) { stream.next(); } if (isEndLine(stream)) { state.cursorHalf = 0; } state.tokenizer = tokenBase; return "string"; } else if (nextChar === "#" && peekChar === "{") { state.tokenizer = buildInterpolationTokenizer(stringTokenizer); stream.next(); return "operator"; } else { return "string"; } } return stringTokenizer; } function buildInterpolationTokenizer(currentTokenizer) { return function(stream, state) { if (stream.peek() === "}") { stream.next(); state.tokenizer = currentTokenizer; return "operator"; } else { return tokenBase(stream, state); } }; } function indent(state) { if (state.indentCount == 0) { state.indentCount++; var lastScopeOffset = state.scopes[0].offset; var currentOffset = lastScopeOffset + config.indentUnit; state.scopes.unshift({ offset:currentOffset }); } } function dedent(state) { if (state.scopes.length == 1) return; state.scopes.shift(); } function tokenBase(stream, state) { var ch = stream.peek(); // Comment if (stream.match("/*")) { state.tokenizer = comment(stream.indentation(), true); return state.tokenizer(stream, state); } if (stream.match("//")) { state.tokenizer = comment(stream.indentation(), false); return state.tokenizer(stream, state); } // Interpolation if (stream.match("#{")) { state.tokenizer = buildInterpolationTokenizer(tokenBase); return "operator"; } // Strings if (ch === '"' || ch === "'") { stream.next(); state.tokenizer = buildStringTokenizer(ch); return "string"; } if(!state.cursorHalf){// state.cursorHalf === 0 // first half i.e. before : for key-value pairs // including selectors if (ch === "-") { if (stream.match(/^-\w+-/)) { return "meta"; } } if (ch === ".") { stream.next(); if (stream.match(/^[\w-]+/)) { indent(state); return "qualifier"; } else if (stream.peek() === "#") { indent(state); return "tag"; } } if (ch === "#") { stream.next(); // ID selectors if (stream.match(/^[\w-]+/)) { indent(state); return "builtin"; } if (stream.peek() === "#") { indent(state); return "tag"; } } // Variables if (ch === "$") { stream.next(); stream.eatWhile(/[\w-]/); return "variable-2"; } // Numbers if (stream.match(/^-?[0-9\.]+/)) return "number"; // Units if (stream.match(/^(px|em|in)\b/)) return "unit"; if (stream.match(keywordsRegexp)) return "keyword"; if (stream.match(/^url/) && stream.peek() === "(") { state.tokenizer = urlTokens; return "atom"; } if (ch === "=") { // Match shortcut mixin definition if (stream.match(/^=[\w-]+/)) { indent(state); return "meta"; } } if (ch === "+") { // Match shortcut mixin definition if (stream.match(/^\+[\w-]+/)){ return "variable-3"; } } if(ch === "@"){ if(stream.match(/@extend/)){ if(!stream.match(/\s*[\w]/)) dedent(state); } } // Indent Directives if (stream.match(/^@(else if|if|media|else|for|each|while|mixin|function)/)) { indent(state); return "def"; } // Other Directives if (ch === "@") { stream.next(); stream.eatWhile(/[\w-]/); return "def"; } if (stream.eatWhile(/[\w-]/)){ if(stream.match(/ *: *[\w-\+\$#!\("']/,false)){ word = stream.current().toLowerCase(); var prop = state.prevProp + "-" + word; if (propertyKeywords.hasOwnProperty(prop)) { return "property"; } else if (propertyKeywords.hasOwnProperty(word)) { state.prevProp = word; return "property"; } else if (fontProperties.hasOwnProperty(word)) { return "property"; } return "tag"; } else if(stream.match(/ *:/,false)){ indent(state); state.cursorHalf = 1; state.prevProp = stream.current().toLowerCase(); return "property"; } else if(stream.match(/ *,/,false)){ return "tag"; } else{ indent(state); return "tag"; } } if(ch === ":"){ if (stream.match(pseudoElementsRegexp)){ // could be a pseudo-element return "variable-3"; } stream.next(); state.cursorHalf=1; return "operator"; } } // cursorHalf===0 ends here else{ if (ch === "#") { stream.next(); // Hex numbers if (stream.match(/[0-9a-fA-F]{6}|[0-9a-fA-F]{3}/)){ if (isEndLine(stream)) { state.cursorHalf = 0; } return "number"; } } // Numbers if (stream.match(/^-?[0-9\.]+/)){ if (isEndLine(stream)) { state.cursorHalf = 0; } return "number"; } // Units if (stream.match(/^(px|em|in)\b/)){ if (isEndLine(stream)) { state.cursorHalf = 0; } return "unit"; } if (stream.match(keywordsRegexp)){ if (isEndLine(stream)) { state.cursorHalf = 0; } return "keyword"; } if (stream.match(/^url/) && stream.peek() === "(") { state.tokenizer = urlTokens; if (isEndLine(stream)) { state.cursorHalf = 0; } return "atom"; } // Variables if (ch === "$") { stream.next(); stream.eatWhile(/[\w-]/); if (isEndLine(stream)) { state.cursorHalf = 0; } return "variable-2"; } // bang character for !important, !default, etc. if (ch === "!") { stream.next(); state.cursorHalf = 0; return stream.match(/^[\w]+/) ? "keyword": "operator"; } if (stream.match(opRegexp)){ if (isEndLine(stream)) { state.cursorHalf = 0; } return "operator"; } // attributes if (stream.eatWhile(/[\w-]/)) { if (isEndLine(stream)) { state.cursorHalf = 0; } word = stream.current().toLowerCase(); if (valueKeywords.hasOwnProperty(word)) { return "atom"; } else if (colorKeywords.hasOwnProperty(word)) { return "keyword"; } else if (propertyKeywords.hasOwnProperty(word)) { state.prevProp = stream.current().toLowerCase(); return "property"; } else { return "tag"; } } //stream.eatSpace(); if (isEndLine(stream)) { state.cursorHalf = 0; return null; } } // else ends here if (stream.match(opRegexp)) return "operator"; // If we haven't returned by now, we move 1 character // and return an error stream.next(); return null; } function tokenLexer(stream, state) { if (stream.sol()) state.indentCount = 0; var style = state.tokenizer(stream, state); var current = stream.current(); if (current === "@return" || current === "}"){ dedent(state); } if (style !== null) { var startOfToken = stream.pos - current.length; var withCurrentIndent = startOfToken + (config.indentUnit * state.indentCount); var newScopes = []; for (var i = 0; i < state.scopes.length; i++) { var scope = state.scopes[i]; if (scope.offset <= withCurrentIndent) newScopes.push(scope); } state.scopes = newScopes; } return style; } return { startState: function() { return { tokenizer: tokenBase, scopes: [{offset: 0, type: "sass"}], indentCount: 0, cursorHalf: 0, // cursor half tells us if cursor lies after (1) // or before (0) colon (well... more or less) definedVars: [], definedMixins: [] }; }, token: function(stream, state) { var style = tokenLexer(stream, state); state.lastToken = { style: style, content: stream.current() }; return style; }, indent: function(state) { return state.scopes[0].offset; } }; }, "css"); CodeMirror.defineMIME("text/x-sass", "sass"); }); ================================================ FILE: third_party/CodeMirror/mode/sass/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "sass"); // Since Sass has an indent-based syntax, is almost impossible to test correctly the indentation in all cases. // So disable it for tests. mode.indent = undefined; function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("comment", "[comment // this is a comment]", "[comment also this is a comment]") MT("comment_multiline", "[comment /* this is a comment]", "[comment also this is a comment]") MT("variable", "[variable-2 $page-width][operator :] [number 800][unit px]") MT("global_attributes", "[tag body]", " [property font][operator :]", " [property family][operator :] [atom sans-serif]", " [property size][operator :] [number 30][unit em]", " [property weight][operator :] [atom bold]") MT("scoped_styles", "[builtin #contents]", " [property width][operator :] [variable-2 $page-width]", " [builtin #sidebar]", " [property float][operator :] [atom right]", " [property width][operator :] [variable-2 $sidebar-width]", " [builtin #main]", " [property width][operator :] [variable-2 $page-width] [operator -] [variable-2 $sidebar-width]", " [property background][operator :] [variable-2 $primary-color]", " [tag h2]", " [property color][operator :] [keyword blue]") // Sass allows to write the colon as first char instead of a "separator". // :color red // Not supported // MT("property_syntax", // "[qualifier .foo]", // " [operator :][property color] [keyword red]") MT("import", "[def @import] [string \"sass/variables\"]", // Probably it should parsed as above: as a string even without the " or ' // "[def @import] [string sass/baz]" "[def @import] [tag sass][operator /][tag baz]") MT("def", "[def @if] [variable-2 $foo] [def @else]") MT("tag_on_more_lines", "[tag td],", "[tag th]", " [property font-family][operator :] [string \"Arial\"], [atom serif]") MT("important", "[qualifier .foo]", " [property text-decoration][operator :] [atom none] [keyword !important]", "[tag h1]", " [property font-size][operator :] [number 2.5][unit em]") MT("selector", // SCSS doesn't highlight the : // "[tag h1]:[variable-3 before],", // "[tag h2]:[variable-3 before]", "[tag h1][variable-3 :before],", "[tag h2][variable-3 :before]", " [property content][operator :] [string \"::\"]") MT("definition_mixin_equal", "[variable-2 $defined-bs-type][operator :] [atom border-box] [keyword !default]", "[meta =bs][operator (][variable-2 $bs-type][operator :] [variable-2 $defined-bs-type][operator )]", " [meta -webkit-][property box-sizing][operator :] [variable-2 $bs-type]", " [property box-sizing][operator :] [variable-2 $bs-type]") MT("definition_mixin_with_space", "[variable-2 $defined-bs-type][operator :] [atom border-box] [keyword !default]", "[def @mixin] [tag bs][operator (][variable-2 $bs-type][operator :] [variable-2 $defined-bs-type][operator )] ", " [meta -moz-][property box-sizing][operator :] [variable-2 $bs-type]", " [property box-sizing][operator :] [variable-2 $bs-type]") MT("numbers_start_dot_include_plus", // The % is not highlighted correctly // "[meta =button-links][operator (][variable-2 $button-base][operator :] [atom darken][operator (][variable-2 $color11], [number 10][unit %][operator )][operator )]", "[meta =button-links][operator (][variable-2 $button-base][operator :] [atom darken][operator (][variable-2 $color11], [number 10][operator %))]", " [property padding][operator :] [number .3][unit em] [number .6][unit em]", " [variable-3 +border-radius][operator (][number 8][unit px][operator )]", " [property background-color][operator :] [variable-2 $button-base]") MT("include", "[qualifier .bar]", " [def @include] [tag border-radius][operator (][number 8][unit px][operator )]") MT("reference_parent", "[qualifier .col]", " [property clear][operator :] [atom both]", // SCSS doesn't highlight the : // " &:[variable-3 after]", " &[variable-3 :after]", " [property content][operator :] [string '']", " [property clear][operator :] [atom both]") MT("reference_parent_with_spaces", "[tag section]", " [property border-left][operator :] [number 20][unit px] [atom transparent] [atom solid] ", " &[qualifier .section3]", " [qualifier .title]", " [property color][operator :] [keyword white] ", " [qualifier .vermas]", " [property display][operator :] [atom none]") MT("font_face", "[def @font-face]", " [property font-family][operator :] [string 'icomoon']", " [property src][operator :] [atom url][operator (][string fonts/icomoon.ttf][operator )]") })(); ================================================ FILE: third_party/CodeMirror/mode/scheme/index.html ================================================ CodeMirror: Scheme mode

Scheme mode

MIME types defined: text/x-scheme.

================================================ FILE: third_party/CodeMirror/mode/scheme/scheme.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /** * Author: Koh Zi Han, based on implementation by Koh Zi Chun */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("scheme", function () { var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", ATOM = "atom", NUMBER = "number", BRACKET = "bracket"; var INDENT_WORD_SKIP = 2; function makeKeywords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } 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-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? 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-copy string-fill! string-length string-ref string-set! 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?"); var indentKeys = makeKeywords("define let letrec let* lambda"); function stateStack(indent, type, prev) { // represents a state stack object this.indent = indent; this.type = type; this.prev = prev; } function pushStack(state, indent, type) { state.indentStack = new stateStack(indent, type, state.indentStack); } function popStack(state) { state.indentStack = state.indentStack.prev; } var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i); 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); 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); 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); function isBinaryNumber (stream) { return stream.match(binaryMatcher); } function isOctalNumber (stream) { return stream.match(octalMatcher); } function isDecimalNumber (stream, backup) { if (backup === true) { stream.backUp(1); } return stream.match(decimalMatcher); } function isHexNumber (stream) { return stream.match(hexMatcher); } return { startState: function () { return { indentStack: null, indentation: 0, mode: false, sExprComment: false, sExprQuote: false }; }, token: function (stream, state) { if (state.indentStack == null && stream.sol()) { // update indentation, but only if indentStack is empty state.indentation = stream.indentation(); } // skip spaces if (stream.eatSpace()) { return null; } var returnType = null; switch(state.mode){ case "string": // multi-line string parsing mode var next, escaped = false; while ((next = stream.next()) != null) { if (next == "\"" && !escaped) { state.mode = false; break; } escaped = !escaped && next == "\\"; } returnType = STRING; // continue on in scheme-string mode break; case "comment": // comment parsing mode var next, maybeEnd = false; while ((next = stream.next()) != null) { if (next == "#" && maybeEnd) { state.mode = false; break; } maybeEnd = (next == "|"); } returnType = COMMENT; break; case "s-expr-comment": // s-expr commenting mode state.mode = false; if(stream.peek() == "(" || stream.peek() == "["){ // actually start scheme s-expr commenting mode state.sExprComment = 0; }else{ // if not we just comment the entire of the next token stream.eatWhile(/[^\s\(\)\[\]]/); // eat symbol atom returnType = COMMENT; break; } default: // default parsing mode var ch = stream.next(); if (ch == "\"") { state.mode = "string"; returnType = STRING; } else if (ch == "'") { if (stream.peek() == "(" || stream.peek() == "["){ if (typeof state.sExprQuote != "number") { state.sExprQuote = 0; } // else already in a quoted expression returnType = ATOM; } else { stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/); returnType = ATOM; } } else if (ch == '#') { if (stream.eat("|")) { // Multi-line comment state.mode = "comment"; // toggle to comment mode returnType = COMMENT; } else if (stream.eat(/[tf]/i)) { // #t/#f (atom) returnType = ATOM; } else if (stream.eat(';')) { // S-Expr comment state.mode = "s-expr-comment"; returnType = COMMENT; } else { var numTest = null, hasExactness = false, hasRadix = true; if (stream.eat(/[ei]/i)) { hasExactness = true; } else { stream.backUp(1); // must be radix specifier } if (stream.match(/^#b/i)) { numTest = isBinaryNumber; } else if (stream.match(/^#o/i)) { numTest = isOctalNumber; } else if (stream.match(/^#x/i)) { numTest = isHexNumber; } else if (stream.match(/^#d/i)) { numTest = isDecimalNumber; } else if (stream.match(/^[-+0-9.]/, false)) { hasRadix = false; numTest = isDecimalNumber; // re-consume the intial # if all matches failed } else if (!hasExactness) { stream.eat('#'); } if (numTest != null) { if (hasRadix && !hasExactness) { // consume optional exactness after radix stream.match(/^#[ei]/i); } if (numTest(stream)) returnType = NUMBER; } } } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal returnType = NUMBER; } else if (ch == ";") { // comment stream.skipToEnd(); // rest of the line is a comment returnType = COMMENT; } else if (ch == "(" || ch == "[") { var keyWord = ''; var indentTemp = stream.column(), letter; /** Either (indent-word .. (non-indent-word .. (;something else, bracket, etc. */ while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) { keyWord += letter; } if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word pushStack(state, indentTemp + INDENT_WORD_SKIP, ch); } else { // non-indent word // we continue eating the spaces stream.eatSpace(); if (stream.eol() || stream.peek() == ";") { // nothing significant after // we restart indentation 1 space after pushStack(state, indentTemp + 1, ch); } else { pushStack(state, indentTemp + stream.current().length, ch); // else we match } } stream.backUp(stream.current().length - 1); // undo all the eating if(typeof state.sExprComment == "number") state.sExprComment++; if(typeof state.sExprQuote == "number") state.sExprQuote++; returnType = BRACKET; } else if (ch == ")" || ch == "]") { returnType = BRACKET; if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) { popStack(state); if(typeof state.sExprComment == "number"){ if(--state.sExprComment == 0){ returnType = COMMENT; // final closing bracket state.sExprComment = false; // turn off s-expr commenting mode } } if(typeof state.sExprQuote == "number"){ if(--state.sExprQuote == 0){ returnType = ATOM; // final closing bracket state.sExprQuote = false; // turn off s-expr quote mode } } } } else { stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/); if (keywords && keywords.propertyIsEnumerable(stream.current())) { returnType = BUILTIN; } else returnType = "variable"; } } return (typeof state.sExprComment == "number") ? COMMENT : ((typeof state.sExprQuote == "number") ? ATOM : returnType); }, indent: function (state) { if (state.indentStack == null) return state.indentation; return state.indentStack.indent; }, closeBrackets: {pairs: "()[]{}\"\""}, lineComment: ";;" }; }); CodeMirror.defineMIME("text/x-scheme", "scheme"); }); ================================================ FILE: third_party/CodeMirror/mode/shell/index.html ================================================ CodeMirror: Shell mode

Shell mode

MIME types defined: text/x-sh, application/x-sh.

================================================ FILE: third_party/CodeMirror/mode/shell/shell.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('shell', function() { var words = {}; function define(style, dict) { for(var i = 0; i < dict.length; i++) { words[dict[i]] = style; } }; var commonAtoms = ["true", "false"]; var commonKeywords = ["if", "then", "do", "else", "elif", "while", "until", "for", "in", "esac", "fi", "fin", "fil", "done", "exit", "set", "unset", "export", "function"]; var commonCommands = ["ab", "awk", "bash", "beep", "cat", "cc", "cd", "chown", "chmod", "chroot", "clear", "cp", "curl", "cut", "diff", "echo", "find", "gawk", "gcc", "get", "git", "grep", "hg", "kill", "killall", "ln", "ls", "make", "mkdir", "openssl", "mv", "nc", "nl", "node", "npm", "ping", "ps", "restart", "rm", "rmdir", "sed", "service", "sh", "shopt", "shred", "source", "sort", "sleep", "ssh", "start", "stop", "su", "sudo", "svn", "tee", "telnet", "top", "touch", "vi", "vim", "wall", "wc", "wget", "who", "write", "yes", "zsh"]; CodeMirror.registerHelper("hintWords", "shell", commonAtoms.concat(commonKeywords, commonCommands)); define('atom', commonAtoms); define('keyword', commonKeywords); define('builtin', commonCommands); function tokenBase(stream, state) { if (stream.eatSpace()) return null; var sol = stream.sol(); var ch = stream.next(); if (ch === '\\') { stream.next(); return null; } if (ch === '\'' || ch === '"' || ch === '`') { state.tokens.unshift(tokenString(ch, ch === "`" ? "quote" : "string")); return tokenize(stream, state); } if (ch === '#') { if (sol && stream.eat('!')) { stream.skipToEnd(); return 'meta'; // 'comment'? } stream.skipToEnd(); return 'comment'; } if (ch === '$') { state.tokens.unshift(tokenDollar); return tokenize(stream, state); } if (ch === '+' || ch === '=') { return 'operator'; } if (ch === '-') { stream.eat('-'); stream.eatWhile(/\w/); return 'attribute'; } if (/\d/.test(ch)) { stream.eatWhile(/\d/); if(stream.eol() || !/\w/.test(stream.peek())) { return 'number'; } } stream.eatWhile(/[\w-]/); var cur = stream.current(); if (stream.peek() === '=' && /\w+/.test(cur)) return 'def'; return words.hasOwnProperty(cur) ? words[cur] : null; } function tokenString(quote, style) { var close = quote == "(" ? ")" : quote == "{" ? "}" : quote return function(stream, state) { var next, escaped = false; while ((next = stream.next()) != null) { if (next === close && !escaped) { state.tokens.shift(); break; } else if (next === '$' && !escaped && quote !== "'" && stream.peek() != close) { escaped = true; stream.backUp(1); state.tokens.unshift(tokenDollar); break; } else if (!escaped && quote !== close && next === quote) { state.tokens.unshift(tokenString(quote, style)) return tokenize(stream, state) } else if (!escaped && /['"]/.test(next) && !/['"]/.test(quote)) { state.tokens.unshift(tokenStringStart(next, "string")); stream.backUp(1); break; } escaped = !escaped && next === '\\'; } return style; }; }; function tokenStringStart(quote, style) { return function(stream, state) { state.tokens[0] = tokenString(quote, style) stream.next() return tokenize(stream, state) } } var tokenDollar = function(stream, state) { if (state.tokens.length > 1) stream.eat('$'); var ch = stream.next() if (/['"({]/.test(ch)) { state.tokens[0] = tokenString(ch, ch == "(" ? "quote" : ch == "{" ? "def" : "string"); return tokenize(stream, state); } if (!/\d/.test(ch)) stream.eatWhile(/\w/); state.tokens.shift(); return 'def'; }; function tokenize(stream, state) { return (state.tokens[0] || tokenBase) (stream, state); }; return { startState: function() {return {tokens:[]};}, token: function(stream, state) { return tokenize(stream, state); }, closeBrackets: "()[]{}''\"\"``", lineComment: '#', fold: "brace" }; }); CodeMirror.defineMIME('text/x-sh', 'shell'); // Apache uses a slightly different Media Type for Shell scripts // http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types CodeMirror.defineMIME('application/x-sh', 'shell'); }); ================================================ FILE: third_party/CodeMirror/mode/shell/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({}, "shell"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("var", "text [def $var] text"); MT("varBraces", "text[def ${var}]text"); MT("varVar", "text [def $a$b] text"); MT("varBracesVarBraces", "text[def ${a}${b}]text"); MT("singleQuotedVar", "[string 'text $var text']"); MT("singleQuotedVarBraces", "[string 'text ${var} text']"); MT("doubleQuotedVar", '[string "text ][def $var][string text"]'); MT("doubleQuotedVarBraces", '[string "text][def ${var}][string text"]'); MT("doubleQuotedVarPunct", '[string "text ][def $@][string text"]'); MT("doubleQuotedVarVar", '[string "][def $a$b][string "]'); MT("doubleQuotedVarBracesVarBraces", '[string "][def ${a}${b}][string "]'); MT("notAString", "text\\'text"); MT("escapes", "outside\\'\\\"\\`\\\\[string \"inside\\`\\'\\\"\\\\`\\$notAVar\"]outside\\$\\(notASubShell\\)"); MT("subshell", "[builtin echo] [quote $(whoami)] s log, stardate [quote `date`]."); MT("doubleQuotedSubshell", "[builtin echo] [string \"][quote $(whoami)][string 's log, stardate `date`.\"]"); MT("hashbang", "[meta #!/bin/bash]"); MT("comment", "text [comment # Blurb]"); MT("numbers", "[number 0] [number 1] [number 2]"); MT("keywords", "[keyword while] [atom true]; [keyword do]", " [builtin sleep] [number 3]", "[keyword done]"); MT("options", "[builtin ls] [attribute -l] [attribute --human-readable]"); MT("operator", "[def var][operator =]value"); MT("doubleParens", "foo [quote $((bar))]") MT("nested braces", "[builtin echo] [def ${A[${B}]]}]") MT("strings in parens", "[def FOO][operator =]([quote $(<][string \"][def $MYDIR][string \"][quote /myfile grep ][string 'hello$'][quote )])") MT ("string ending in dollar", '[def a][operator =][string "xyz$"]; [def b][operator =][string "y"]') MT ("quote ending in dollar", "[quote $(echo a$)]") })(); ================================================ FILE: third_party/CodeMirror/mode/sieve/index.html ================================================ CodeMirror: Sieve (RFC5228) mode

Sieve (RFC5228) mode

MIME types defined: application/sieve.

================================================ FILE: third_party/CodeMirror/mode/sieve/sieve.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sieve", function(config) { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = words("if elsif else stop require"); var atoms = words("true false not"); var indentUnit = config.indentUnit; function tokenBase(stream, state) { var ch = stream.next(); if (ch == "/" && stream.eat("*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } if (ch === '#') { stream.skipToEnd(); return "comment"; } if (ch == "\"") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (ch == "(") { state._indent.push("("); // add virtual angel wings so that editor behaves... // ...more sane incase of broken brackets state._indent.push("{"); return null; } if (ch === "{") { state._indent.push("{"); return null; } if (ch == ")") { state._indent.pop(); state._indent.pop(); } if (ch === "}") { state._indent.pop(); return null; } if (ch == ",") return null; if (ch == ";") return null; if (/[{}\(\),;]/.test(ch)) return null; // 1*DIGIT "K" / "M" / "G" if (/\d/.test(ch)) { stream.eatWhile(/[\d]/); stream.eat(/[KkMmGg]/); return "number"; } // ":" (ALPHA / "_") *(ALPHA / DIGIT / "_") if (ch == ":") { stream.eatWhile(/[a-zA-Z_]/); stream.eatWhile(/[a-zA-Z0-9_]/); return "operator"; } stream.eatWhile(/\w/); var cur = stream.current(); // "text:" *(SP / HTAB) (hash-comment / CRLF) // *(multiline-literal / multiline-dotstart) // "." CRLF if ((cur == "text") && stream.eat(":")) { state.tokenize = tokenMultiLineString; return "string"; } if (keywords.propertyIsEnumerable(cur)) return "keyword"; if (atoms.propertyIsEnumerable(cur)) return "atom"; return null; } function tokenMultiLineString(stream, state) { state._multiLineString = true; // the first line is special it may contain a comment if (!stream.sol()) { stream.eatSpace(); if (stream.peek() == "#") { stream.skipToEnd(); return "comment"; } stream.skipToEnd(); return "string"; } if ((stream.next() == ".") && (stream.eol())) { state._multiLineString = false; state.tokenize = tokenBase; } return "string"; } function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) break; escaped = !escaped && ch == "\\"; } if (!escaped) state.tokenize = tokenBase; return "string"; }; } return { startState: function(base) { return {tokenize: tokenBase, baseIndent: base || 0, _indent: []}; }, token: function(stream, state) { if (stream.eatSpace()) return null; return (state.tokenize || tokenBase)(stream, state); }, indent: function(state, _textAfter) { var length = state._indent.length; if (_textAfter && (_textAfter[0] == "}")) length--; if (length <0) length = 0; return length * indentUnit; }, electricChars: "}" }; }); CodeMirror.defineMIME("application/sieve", "sieve"); }); ================================================ FILE: third_party/CodeMirror/mode/slim/index.html ================================================ CodeMirror: SLIM mode

SLIM mode

MIME types defined: application/x-slim.

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/slim/slim.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Slim Highlighting for CodeMirror copyright (c) HicknHack Software Gmbh (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../ruby/ruby")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../ruby/ruby"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("slim", function(config) { var htmlMode = CodeMirror.getMode(config, {name: "htmlmixed"}); var rubyMode = CodeMirror.getMode(config, "ruby"); var modes = { html: htmlMode, ruby: rubyMode }; var embedded = { ruby: "ruby", javascript: "javascript", css: "text/css", sass: "text/x-sass", scss: "text/x-scss", less: "text/x-less", styl: "text/x-styl", // no highlighting so far coffee: "coffeescript", asciidoc: "text/x-asciidoc", markdown: "text/x-markdown", textile: "text/x-textile", // no highlighting so far creole: "text/x-creole", // no highlighting so far wiki: "text/x-wiki", // no highlighting so far mediawiki: "text/x-mediawiki", // no highlighting so far rdoc: "text/x-rdoc", // no highlighting so far builder: "text/x-builder", // no highlighting so far nokogiri: "text/x-nokogiri", // no highlighting so far erb: "application/x-erb" }; var embeddedRegexp = function(map){ var arr = []; for(var key in map) arr.push(key); return new RegExp("^("+arr.join('|')+"):"); }(embedded); var styleMap = { "commentLine": "comment", "slimSwitch": "operator special", "slimTag": "tag", "slimId": "attribute def", "slimClass": "attribute qualifier", "slimAttribute": "attribute", "slimSubmode": "keyword special", "closeAttributeTag": null, "slimDoctype": null, "lineContinuation": null }; var closing = { "{": "}", "[": "]", "(": ")" }; 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"; var nameChar = nameStartChar + "\\-0-9\xB7\u0300-\u036F\u203F-\u2040"; var nameRegexp = new RegExp("^[:"+nameStartChar+"](?::["+nameChar+"]|["+nameChar+"]*)"); var attributeNameRegexp = new RegExp("^[:"+nameStartChar+"][:\\."+nameChar+"]*(?=\\s*=)"); var wrappedAttributeNameRegexp = new RegExp("^[:"+nameStartChar+"][:\\."+nameChar+"]*"); var classNameRegexp = /^\.-?[_a-zA-Z]+[\w\-]*/; var classIdRegexp = /^#[_a-zA-Z]+[\w\-]*/; function backup(pos, tokenize, style) { var restore = function(stream, state) { state.tokenize = tokenize; if (stream.pos < pos) { stream.pos = pos; return style; } return state.tokenize(stream, state); }; return function(stream, state) { state.tokenize = restore; return tokenize(stream, state); }; } function maybeBackup(stream, state, pat, offset, style) { var cur = stream.current(); var idx = cur.search(pat); if (idx > -1) { state.tokenize = backup(stream.pos, state.tokenize, style); stream.backUp(cur.length - idx - offset); } return style; } function continueLine(state, column) { state.stack = { parent: state.stack, style: "continuation", indented: column, tokenize: state.line }; state.line = state.tokenize; } function finishContinue(state) { if (state.line == state.tokenize) { state.line = state.stack.tokenize; state.stack = state.stack.parent; } } function lineContinuable(column, tokenize) { return function(stream, state) { finishContinue(state); if (stream.match(/^\\$/)) { continueLine(state, column); return "lineContinuation"; } var style = tokenize(stream, state); if (stream.eol() && stream.current().match(/(?:^|[^\\])(?:\\\\)*\\$/)) { stream.backUp(1); } return style; }; } function commaContinuable(column, tokenize) { return function(stream, state) { finishContinue(state); var style = tokenize(stream, state); if (stream.eol() && stream.current().match(/,$/)) { continueLine(state, column); } return style; }; } function rubyInQuote(endQuote, tokenize) { // TODO: add multi line support return function(stream, state) { var ch = stream.peek(); if (ch == endQuote && state.rubyState.tokenize.length == 1) { // step out of ruby context as it seems to complete processing all the braces stream.next(); state.tokenize = tokenize; return "closeAttributeTag"; } else { return ruby(stream, state); } }; } function startRubySplat(tokenize) { var rubyState; var runSplat = function(stream, state) { if (state.rubyState.tokenize.length == 1 && !state.rubyState.context.prev) { stream.backUp(1); if (stream.eatSpace()) { state.rubyState = rubyState; state.tokenize = tokenize; return tokenize(stream, state); } stream.next(); } return ruby(stream, state); }; return function(stream, state) { rubyState = state.rubyState; state.rubyState = CodeMirror.startState(rubyMode); state.tokenize = runSplat; return ruby(stream, state); }; } function ruby(stream, state) { return rubyMode.token(stream, state.rubyState); } function htmlLine(stream, state) { if (stream.match(/^\\$/)) { return "lineContinuation"; } return html(stream, state); } function html(stream, state) { if (stream.match(/^#\{/)) { state.tokenize = rubyInQuote("}", state.tokenize); return null; } return maybeBackup(stream, state, /[^\\]#\{/, 1, htmlMode.token(stream, state.htmlState)); } function startHtmlLine(lastTokenize) { return function(stream, state) { var style = htmlLine(stream, state); if (stream.eol()) state.tokenize = lastTokenize; return style; }; } function startHtmlMode(stream, state, offset) { state.stack = { parent: state.stack, style: "html", indented: stream.column() + offset, // pipe + space tokenize: state.line }; state.line = state.tokenize = html; return null; } function comment(stream, state) { stream.skipToEnd(); return state.stack.style; } function commentMode(stream, state) { state.stack = { parent: state.stack, style: "comment", indented: state.indented + 1, tokenize: state.line }; state.line = comment; return comment(stream, state); } function attributeWrapper(stream, state) { if (stream.eat(state.stack.endQuote)) { state.line = state.stack.line; state.tokenize = state.stack.tokenize; state.stack = state.stack.parent; return null; } if (stream.match(wrappedAttributeNameRegexp)) { state.tokenize = attributeWrapperAssign; return "slimAttribute"; } stream.next(); return null; } function attributeWrapperAssign(stream, state) { if (stream.match(/^==?/)) { state.tokenize = attributeWrapperValue; return null; } return attributeWrapper(stream, state); } function attributeWrapperValue(stream, state) { var ch = stream.peek(); if (ch == '"' || ch == "\'") { state.tokenize = readQuoted(ch, "string", true, false, attributeWrapper); stream.next(); return state.tokenize(stream, state); } if (ch == '[') { return startRubySplat(attributeWrapper)(stream, state); } if (stream.match(/^(true|false|nil)\b/)) { state.tokenize = attributeWrapper; return "keyword"; } return startRubySplat(attributeWrapper)(stream, state); } function startAttributeWrapperMode(state, endQuote, tokenize) { state.stack = { parent: state.stack, style: "wrapper", indented: state.indented + 1, tokenize: tokenize, line: state.line, endQuote: endQuote }; state.line = state.tokenize = attributeWrapper; return null; } function sub(stream, state) { if (stream.match(/^#\{/)) { state.tokenize = rubyInQuote("}", state.tokenize); return null; } var subStream = new CodeMirror.StringStream(stream.string.slice(state.stack.indented), stream.tabSize); subStream.pos = stream.pos - state.stack.indented; subStream.start = stream.start - state.stack.indented; subStream.lastColumnPos = stream.lastColumnPos - state.stack.indented; subStream.lastColumnValue = stream.lastColumnValue - state.stack.indented; var style = state.subMode.token(subStream, state.subState); stream.pos = subStream.pos + state.stack.indented; return style; } function firstSub(stream, state) { state.stack.indented = stream.column(); state.line = state.tokenize = sub; return state.tokenize(stream, state); } function createMode(mode) { var query = embedded[mode]; var spec = CodeMirror.mimeModes[query]; if (spec) { return CodeMirror.getMode(config, spec); } var factory = CodeMirror.modes[query]; if (factory) { return factory(config, {name: query}); } return CodeMirror.getMode(config, "null"); } function getMode(mode) { if (!modes.hasOwnProperty(mode)) { return modes[mode] = createMode(mode); } return modes[mode]; } function startSubMode(mode, state) { var subMode = getMode(mode); var subState = CodeMirror.startState(subMode); state.subMode = subMode; state.subState = subState; state.stack = { parent: state.stack, style: "sub", indented: state.indented + 1, tokenize: state.line }; state.line = state.tokenize = firstSub; return "slimSubmode"; } function doctypeLine(stream, _state) { stream.skipToEnd(); return "slimDoctype"; } function startLine(stream, state) { var ch = stream.peek(); if (ch == '<') { return (state.tokenize = startHtmlLine(state.tokenize))(stream, state); } if (stream.match(/^[|']/)) { return startHtmlMode(stream, state, 1); } if (stream.match(/^\/(!|\[\w+])?/)) { return commentMode(stream, state); } if (stream.match(/^(-|==?[<>]?)/)) { state.tokenize = lineContinuable(stream.column(), commaContinuable(stream.column(), ruby)); return "slimSwitch"; } if (stream.match(/^doctype\b/)) { state.tokenize = doctypeLine; return "keyword"; } var m = stream.match(embeddedRegexp); if (m) { return startSubMode(m[1], state); } return slimTag(stream, state); } function slim(stream, state) { if (state.startOfLine) { return startLine(stream, state); } return slimTag(stream, state); } function slimTag(stream, state) { if (stream.eat('*')) { state.tokenize = startRubySplat(slimTagExtras); return null; } if (stream.match(nameRegexp)) { state.tokenize = slimTagExtras; return "slimTag"; } return slimClass(stream, state); } function slimTagExtras(stream, state) { if (stream.match(/^(<>?|> state.indented && state.last != "slimSubmode") { state.line = state.tokenize = state.stack.tokenize; state.stack = state.stack.parent; state.subMode = null; state.subState = null; } } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); state.startOfLine = false; if (style) state.last = style; return styleMap.hasOwnProperty(style) ? styleMap[style] : style; }, blankLine: function(state) { if (state.subMode && state.subMode.blankLine) { return state.subMode.blankLine(state.subState); } }, innerMode: function(state) { if (state.subMode) return {state: state.subState, mode: state.subMode}; return {state: state, mode: mode}; } //indent: function(state) { // return state.indented; //} }; return mode; }, "htmlmixed", "ruby"); CodeMirror.defineMIME("text/x-slim", "slim"); CodeMirror.defineMIME("application/x-slim", "slim"); }); ================================================ FILE: third_party/CodeMirror/mode/slim/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Slim Highlighting for CodeMirror copyright (c) HicknHack Software Gmbh (function() { var mode = CodeMirror.getMode({tabSize: 4, indentUnit: 2}, "slim"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Requires at least one media query MT("elementName", "[tag h1] Hey There"); MT("oneElementPerLine", "[tag h1] Hey There .h2"); MT("idShortcut", "[attribute&def #test] Hey There"); MT("tagWithIdShortcuts", "[tag h1][attribute&def #test] Hey There"); MT("classShortcut", "[attribute&qualifier .hello] Hey There"); MT("tagWithIdAndClassShortcuts", "[tag h1][attribute&def #test][attribute&qualifier .hello] Hey There"); MT("docType", "[keyword doctype] xml"); MT("comment", "[comment / Hello WORLD]"); MT("notComment", "[tag h1] This is not a / comment "); MT("attributes", "[tag a]([attribute title]=[string \"test\"]) [attribute href]=[string \"link\"]}"); MT("multiLineAttributes", "[tag a]([attribute title]=[string \"test\"]", " ) [attribute href]=[string \"link\"]}"); MT("htmlCode", "[tag&bracket <][tag h1][tag&bracket >]Title[tag&bracket ]"); MT("rubyBlock", "[operator&special =][variable-2 @item]"); MT("selectorRubyBlock", "[tag a][attribute&qualifier .test][operator&special =] [variable-2 @item]"); MT("nestedRubyBlock", "[tag a]", " [operator&special =][variable puts] [string \"test\"]"); MT("multilinePlaintext", "[tag p]", " | Hello,", " World"); MT("multilineRuby", "[tag p]", " [comment /# this is a comment]", " [comment and this is a comment too]", " | Date/Time", " [operator&special -] [variable now] [operator =] [tag DateTime][operator .][property now]", " [tag strong][operator&special =] [variable now]", " [operator&special -] [keyword if] [variable now] [operator >] [tag DateTime][operator .][property parse]([string \"December 31, 2006\"])", " [operator&special =][string \"Happy\"]", " [operator&special =][string \"Belated\"]", " [operator&special =][string \"Birthday\"]"); MT("multilineComment", "[comment /]", " [comment Multiline]", " [comment Comment]"); MT("hamlAfterRubyTag", "[attribute&qualifier .block]", " [tag strong][operator&special =] [variable now]", " [attribute&qualifier .test]", " [operator&special =][variable now]", " [attribute&qualifier .right]"); MT("stretchedRuby", "[operator&special =] [variable puts] [string \"Hello\"],", " [string \"World\"]"); MT("interpolationInHashAttribute", "[tag div]{[attribute id] = [string \"]#{[variable test]}[string _]#{[variable ting]}[string \"]} test"); MT("interpolationInHTMLAttribute", "[tag div]([attribute title]=[string \"]#{[variable test]}[string _]#{[variable ting]()}[string \"]) Test"); })(); ================================================ FILE: third_party/CodeMirror/mode/smalltalk/index.html ================================================ CodeMirror: Smalltalk mode

Smalltalk mode

Simple Smalltalk mode.

MIME types defined: text/x-stsrc.

================================================ FILE: third_party/CodeMirror/mode/smalltalk/smalltalk.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('smalltalk', function(config) { var specialChars = /[+\-\/\\*~<>=@%|&?!.,:;^]/; var keywords = /true|false|nil|self|super|thisContext/; var Context = function(tokenizer, parent) { this.next = tokenizer; this.parent = parent; }; var Token = function(name, context, eos) { this.name = name; this.context = context; this.eos = eos; }; var State = function() { this.context = new Context(next, null); this.expectVariable = true; this.indentation = 0; this.userIndentationDelta = 0; }; State.prototype.userIndent = function(indentation) { this.userIndentationDelta = indentation > 0 ? (indentation / config.indentUnit - this.indentation) : 0; }; var next = function(stream, context, state) { var token = new Token(null, context, false); var aChar = stream.next(); if (aChar === '"') { token = nextComment(stream, new Context(nextComment, context)); } else if (aChar === '\'') { token = nextString(stream, new Context(nextString, context)); } else if (aChar === '#') { if (stream.peek() === '\'') { stream.next(); token = nextSymbol(stream, new Context(nextSymbol, context)); } else { if (stream.eatWhile(/[^\s.{}\[\]()]/)) token.name = 'string-2'; else token.name = 'meta'; } } else if (aChar === '$') { if (stream.next() === '<') { stream.eatWhile(/[^\s>]/); stream.next(); } token.name = 'string-2'; } else if (aChar === '|' && state.expectVariable) { token.context = new Context(nextTemporaries, context); } else if (/[\[\]{}()]/.test(aChar)) { token.name = 'bracket'; token.eos = /[\[{(]/.test(aChar); if (aChar === '[') { state.indentation++; } else if (aChar === ']') { state.indentation = Math.max(0, state.indentation - 1); } } else if (specialChars.test(aChar)) { stream.eatWhile(specialChars); token.name = 'operator'; token.eos = aChar !== ';'; // ; cascaded message expression } else if (/\d/.test(aChar)) { stream.eatWhile(/[\w\d]/); token.name = 'number'; } else if (/[\w_]/.test(aChar)) { stream.eatWhile(/[\w\d_]/); token.name = state.expectVariable ? (keywords.test(stream.current()) ? 'keyword' : 'variable') : null; } else { token.eos = state.expectVariable; } return token; }; var nextComment = function(stream, context) { stream.eatWhile(/[^"]/); return new Token('comment', stream.eat('"') ? context.parent : context, true); }; var nextString = function(stream, context) { stream.eatWhile(/[^']/); return new Token('string', stream.eat('\'') ? context.parent : context, false); }; var nextSymbol = function(stream, context) { stream.eatWhile(/[^']/); return new Token('string-2', stream.eat('\'') ? context.parent : context, false); }; var nextTemporaries = function(stream, context) { var token = new Token(null, context, false); var aChar = stream.next(); if (aChar === '|') { token.context = context.parent; token.eos = true; } else { stream.eatWhile(/[^|]/); token.name = 'variable'; } return token; }; return { startState: function() { return new State; }, token: function(stream, state) { state.userIndent(stream.indentation()); if (stream.eatSpace()) { return null; } var token = state.context.next(stream, state.context, state); state.context = token.context; state.expectVariable = token.eos; return token.name; }, blankLine: function(state) { state.userIndent(0); }, indent: function(state, textAfter) { var i = state.context.next === next && textAfter && textAfter.charAt(0) === ']' ? -1 : state.userIndentationDelta; return (state.indentation + i) * config.indentUnit; }, electricChars: ']' }; }); CodeMirror.defineMIME('text/x-stsrc', {name: 'smalltalk'}); }); ================================================ FILE: third_party/CodeMirror/mode/smarty/index.html ================================================ CodeMirror: Smarty mode

Smarty mode

Mode for Smarty version 2 or 3, which allows for custom delimiter tags.

Several configuration parameters are supported:

  • leftDelimiter and rightDelimiter, which should be strings that determine where the Smarty syntax starts and ends.
  • version, which should be 2 or 3.
  • baseMode, which can be a mode spec like "text/html" to set a different background mode.

MIME types defined: text/x-smarty

Smarty 2, custom delimiters

Smarty 3

================================================ FILE: third_party/CodeMirror/mode/smarty/smarty.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /** * Smarty 2 and 3 mode. */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("smarty", function(config, parserConf) { var rightDelimiter = parserConf.rightDelimiter || "}"; var leftDelimiter = parserConf.leftDelimiter || "{"; var version = parserConf.version || 2; var baseMode = CodeMirror.getMode(config, parserConf.baseMode || "null"); var keyFunctions = ["debug", "extends", "function", "include", "literal"]; var regs = { operatorChars: /[+\-*&%=<>!?]/, validIdentifier: /[a-zA-Z0-9_]/, stringChar: /['"]/ }; var last; function cont(style, lastType) { last = lastType; return style; } function chain(stream, state, parser) { state.tokenize = parser; return parser(stream, state); } // Smarty 3 allows { and } surrounded by whitespace to NOT slip into Smarty mode function doesNotCount(stream, pos) { if (pos == null) pos = stream.pos; return version === 3 && leftDelimiter == "{" && (pos == stream.string.length || /\s/.test(stream.string.charAt(pos))); } function tokenTop(stream, state) { var string = stream.string; for (var scan = stream.pos;;) { var nextMatch = string.indexOf(leftDelimiter, scan); scan = nextMatch + leftDelimiter.length; if (nextMatch == -1 || !doesNotCount(stream, nextMatch + leftDelimiter.length)) break; } if (nextMatch == stream.pos) { stream.match(leftDelimiter); if (stream.eat("*")) { return chain(stream, state, tokenBlock("comment", "*" + rightDelimiter)); } else { state.depth++; state.tokenize = tokenSmarty; last = "startTag"; return "tag"; } } if (nextMatch > -1) stream.string = string.slice(0, nextMatch); var token = baseMode.token(stream, state.base); if (nextMatch > -1) stream.string = string; return token; } // parsing Smarty content function tokenSmarty(stream, state) { if (stream.match(rightDelimiter, true)) { if (version === 3) { state.depth--; if (state.depth <= 0) { state.tokenize = tokenTop; } } else { state.tokenize = tokenTop; } return cont("tag", null); } if (stream.match(leftDelimiter, true)) { state.depth++; return cont("tag", "startTag"); } var ch = stream.next(); if (ch == "$") { stream.eatWhile(regs.validIdentifier); return cont("variable-2", "variable"); } else if (ch == "|") { return cont("operator", "pipe"); } else if (ch == ".") { return cont("operator", "property"); } else if (regs.stringChar.test(ch)) { state.tokenize = tokenAttribute(ch); return cont("string", "string"); } else if (regs.operatorChars.test(ch)) { stream.eatWhile(regs.operatorChars); return cont("operator", "operator"); } else if (ch == "[" || ch == "]") { return cont("bracket", "bracket"); } else if (ch == "(" || ch == ")") { return cont("bracket", "operator"); } else if (/\d/.test(ch)) { stream.eatWhile(/\d/); return cont("number", "number"); } else { if (state.last == "variable") { if (ch == "@") { stream.eatWhile(regs.validIdentifier); return cont("property", "property"); } else if (ch == "|") { stream.eatWhile(regs.validIdentifier); return cont("qualifier", "modifier"); } } else if (state.last == "pipe") { stream.eatWhile(regs.validIdentifier); return cont("qualifier", "modifier"); } else if (state.last == "whitespace") { stream.eatWhile(regs.validIdentifier); return cont("attribute", "modifier"); } if (state.last == "property") { stream.eatWhile(regs.validIdentifier); return cont("property", null); } else if (/\s/.test(ch)) { last = "whitespace"; return null; } var str = ""; if (ch != "/") { str += ch; } var c = null; while (c = stream.eat(regs.validIdentifier)) { str += c; } for (var i=0, j=keyFunctions.length; i CodeMirror: Solr mode

Solr mode

MIME types defined: text/x-solr.

================================================ FILE: third_party/CodeMirror/mode/solr/solr.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("solr", function() { "use strict"; var isStringChar = /[^\s\|\!\+\-\*\?\~\^\&\:\(\)\[\]\{\}\"\\]/; var isOperatorChar = /[\|\!\+\-\*\?\~\^\&]/; var isOperatorString = /^(OR|AND|NOT|TO)$/i; function isNumber(word) { return parseFloat(word).toString() === word; } function tokenString(quote) { return function(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return "string"; }; } function tokenOperator(operator) { return function(stream, state) { var style = "operator"; if (operator == "+") style += " positive"; else if (operator == "-") style += " negative"; else if (operator == "|") stream.eat(/\|/); else if (operator == "&") stream.eat(/\&/); else if (operator == "^") style += " boost"; state.tokenize = tokenBase; return style; }; } function tokenWord(ch) { return function(stream, state) { var word = ch; while ((ch = stream.peek()) && ch.match(isStringChar) != null) { word += stream.next(); } state.tokenize = tokenBase; if (isOperatorString.test(word)) return "operator"; else if (isNumber(word)) return "number"; else if (stream.peek() == ":") return "field"; else return "string"; }; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"') state.tokenize = tokenString(ch); else if (isOperatorChar.test(ch)) state.tokenize = tokenOperator(ch); else if (isStringChar.test(ch)) state.tokenize = tokenWord(ch); return (state.tokenize != tokenBase) ? state.tokenize(stream, state) : null; } return { startState: function() { return { tokenize: tokenBase }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); } }; }); CodeMirror.defineMIME("text/x-solr", "solr"); }); ================================================ FILE: third_party/CodeMirror/mode/soy/index.html ================================================ CodeMirror: Soy (Closure Template) mode

Soy (Closure Template) mode

A mode for Closure Templates (Soy).

MIME type defined: text/x-soy.

================================================ FILE: third_party/CodeMirror/mode/soy/soy.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var indentingTags = ["template", "literal", "msg", "fallbackmsg", "let", "if", "elseif", "else", "switch", "case", "default", "foreach", "ifempty", "for", "call", "param", "deltemplate", "delcall", "log"]; CodeMirror.defineMode("soy", function(config) { var textMode = CodeMirror.getMode(config, "text/plain"); var modes = { html: CodeMirror.getMode(config, {name: "text/html", multilineTagIndentFactor: 2, multilineTagIndentPastTag: false}), attributes: textMode, text: textMode, uri: textMode, trusted_resource_uri: textMode, css: CodeMirror.getMode(config, "text/css"), js: CodeMirror.getMode(config, {name: "text/javascript", statementIndent: 2 * config.indentUnit}) }; function last(array) { return array[array.length - 1]; } function tokenUntil(stream, state, untilRegExp) { if (stream.sol()) { for (var indent = 0; indent < state.indent; indent++) { if (!stream.eat(/\s/)) break; } if (indent) return null; } var oldString = stream.string; var match = untilRegExp.exec(oldString.substr(stream.pos)); if (match) { // We don't use backUp because it backs up just the position, not the state. // This uses an undocumented API. stream.string = oldString.substr(0, stream.pos + match.index); } var result = stream.hideFirstChars(state.indent, function() { var localState = last(state.localStates); return localState.mode.token(stream, localState.state); }); stream.string = oldString; return result; } function contains(list, element) { while (list) { if (list.element === element) return true; list = list.next; } return false; } function prepend(list, element) { return { element: element, next: list }; } // Reference a variable `name` in `list`. // Let `loose` be truthy to ignore missing identifiers. function ref(list, name, loose) { return contains(list, name) ? "variable-2" : (loose ? "variable" : "variable-2 error"); } function popscope(state) { if (state.scopes) { state.variables = state.scopes.element; state.scopes = state.scopes.next; } } return { startState: function() { return { kind: [], kindTag: [], soyState: [], templates: null, variables: prepend(null, 'ij'), scopes: null, indent: 0, quoteKind: null, localStates: [{ mode: modes.html, state: CodeMirror.startState(modes.html) }] }; }, copyState: function(state) { return { tag: state.tag, // Last seen Soy tag. kind: state.kind.concat([]), // Values of kind="" attributes. kindTag: state.kindTag.concat([]), // Opened tags with kind="" attributes. soyState: state.soyState.concat([]), templates: state.templates, variables: state.variables, scopes: state.scopes, indent: state.indent, // Indentation of the following line. quoteKind: state.quoteKind, localStates: state.localStates.map(function(localState) { return { mode: localState.mode, state: CodeMirror.copyState(localState.mode, localState.state) }; }) }; }, token: function(stream, state) { var match; switch (last(state.soyState)) { case "comment": if (stream.match(/^.*?\*\//)) { state.soyState.pop(); } else { stream.skipToEnd(); } if (!state.scopes) { var paramRe = /@param\??\s+(\S+)/g; var current = stream.current(); for (var match; (match = paramRe.exec(current)); ) { state.variables = prepend(state.variables, match[1]); } } return "comment"; case "string": var match = stream.match(/^.*?(["']|\\[\s\S])/); if (!match) { stream.skipToEnd(); } else if (match[1] == state.quoteKind) { state.quoteKind = null; state.soyState.pop(); } return "string"; } if (!state.soyState.length || last(state.soyState) != "literal") { if (stream.match(/^\/\*/)) { state.soyState.push("comment"); return "comment"; } else if (stream.match(stream.sol() ? /^\s*\/\/.*/ : /^\s+\/\/.*/)) { return "comment"; } } switch (last(state.soyState)) { case "templ-def": if (match = stream.match(/^\.?([\w]+(?!\.[\w]+)*)/)) { state.templates = prepend(state.templates, match[1]); state.scopes = prepend(state.scopes, state.variables); state.soyState.pop(); return "def"; } stream.next(); return null; case "templ-ref": if (match = stream.match(/(\.?[a-zA-Z_][a-zA-Z_0-9]+)+/)) { state.soyState.pop(); // If the first character is '.', it can only be a local template. if (match[0][0] == '.') { return "variable-2" } // Otherwise return "variable"; } stream.next(); return null; case "namespace-def": if (match = stream.match(/^\.?([\w\.]+)/)) { state.soyState.pop(); return "variable"; } stream.next(); return null; case "param-def": if (match = stream.match(/^\w+/)) { state.variables = prepend(state.variables, match[0]); state.soyState.pop(); state.soyState.push("param-type"); return "def"; } stream.next(); return null; case "param-ref": if (match = stream.match(/^\w+/)) { state.soyState.pop(); return "property"; } stream.next(); return null; case "param-type": if (stream.peek() == "}") { state.soyState.pop(); return null; } if (stream.eatWhile(/^([\w]+|[?])/)) { return "type"; } stream.next(); return null; case "var-def": if (match = stream.match(/^\$([\w]+)/)) { state.variables = prepend(state.variables, match[1]); state.soyState.pop(); return "def"; } stream.next(); return null; case "tag": if (stream.match(/^\/?}/)) { if (state.tag == "/template" || state.tag == "/deltemplate") { popscope(state); state.variables = prepend(null, 'ij'); state.indent = 0; } else { if (state.tag == "/for" || state.tag == "/foreach") { popscope(state); } state.indent -= config.indentUnit * (stream.current() == "/}" || indentingTags.indexOf(state.tag) == -1 ? 2 : 1); } state.soyState.pop(); return "keyword"; } else if (stream.match(/^([\w?]+)(?==)/)) { if (stream.current() == "kind" && (match = stream.match(/^="([^"]+)/, false))) { var kind = match[1]; state.kind.push(kind); state.kindTag.push(state.tag); var mode = modes[kind] || modes.html; var localState = last(state.localStates); if (localState.mode.indent) { state.indent += localState.mode.indent(localState.state, "", ""); } state.localStates.push({ mode: mode, state: CodeMirror.startState(mode) }); } return "attribute"; } else if (match = stream.match(/([\w]+)(?=\()/)) { return "variable callee"; } else if (match = stream.match(/^["']/)) { state.soyState.push("string"); state.quoteKind = match; return "string"; } if (stream.match(/(null|true|false)(?!\w)/) || stream.match(/0x([0-9a-fA-F]{2,})/) || stream.match(/-?([0-9]*[.])?[0-9]+(e[0-9]*)?/)) { return "atom"; } if (stream.match(/(\||[+\-*\/%]|[=!]=|\?:|[<>]=?)/)) { // Tokenize filter, binary, null propagator, and equality operators. return "operator"; } if (match = stream.match(/^\$([\w]+)/)) { return ref(state.variables, match[1]); } if (match = stream.match(/^\w+/)) { return /^(?:as|and|or|not|in)$/.test(match[0]) ? "keyword" : null; } stream.next(); return null; case "literal": if (stream.match(/^(?=\{\/literal})/)) { state.indent -= config.indentUnit; state.soyState.pop(); return this.token(stream, state); } return tokenUntil(stream, state, /\{\/literal}/); } if (stream.match(/^\{literal}/)) { state.indent += config.indentUnit; state.soyState.push("literal"); return "keyword"; // A tag-keyword must be followed by whitespace, comment or a closing tag. } else if (match = stream.match(/^\{([/@\\]?\w+\??)(?=$|[\s}]|\/[/*])/)) { if (match[1] != "/switch") state.indent += (/^(\/|(else|elseif|ifempty|case|fallbackmsg|default)$)/.test(match[1]) && state.tag != "switch" ? 1 : 2) * config.indentUnit; state.tag = match[1]; if (state.tag == "/" + last(state.kindTag)) { // We found the tag that opened the current kind="". state.kind.pop(); state.kindTag.pop(); state.localStates.pop(); var localState = last(state.localStates); if (localState.mode.indent) { state.indent -= localState.mode.indent(localState.state, "", ""); } } state.soyState.push("tag"); if (state.tag == "template" || state.tag == "deltemplate") { state.soyState.push("templ-def"); } else if (state.tag == "call" || state.tag == "delcall") { state.soyState.push("templ-ref"); } else if (state.tag == "let") { state.soyState.push("var-def"); } else if (state.tag == "for" || state.tag == "foreach") { state.scopes = prepend(state.scopes, state.variables); state.soyState.push("var-def"); } else if (state.tag == "namespace") { state.soyState.push("namespace-def"); if (!state.scopes) { state.variables = prepend(null, 'ij'); } } else if (state.tag.match(/^@(?:param\??|inject|prop)/)) { state.soyState.push("param-def"); } else if (state.tag.match(/^(?:param)/)) { state.soyState.push("param-ref"); } return "keyword"; // Not a tag-keyword; it's an implicit print tag. } else if (stream.eat('{')) { state.tag = "print"; state.indent += 2 * config.indentUnit; state.soyState.push("tag"); return "keyword"; } return tokenUntil(stream, state, /\{|\s+\/\/|\/\*/); }, indent: function(state, textAfter, line) { var indent = state.indent, top = last(state.soyState); if (top == "comment") return CodeMirror.Pass; if (top == "literal") { if (/^\{\/literal}/.test(textAfter)) indent -= config.indentUnit; } else { if (/^\s*\{\/(template|deltemplate)\b/.test(textAfter)) return 0; if (/^\{(\/|(fallbackmsg|elseif|else|ifempty)\b)/.test(textAfter)) indent -= config.indentUnit; if (state.tag != "switch" && /^\{(case|default)\b/.test(textAfter)) indent -= config.indentUnit; if (/^\{\/switch\b/.test(textAfter)) indent -= config.indentUnit; } var localState = last(state.localStates); if (indent && localState.mode.indent) { indent += localState.mode.indent(localState.state, textAfter, line); } return indent; }, innerMode: function(state) { if (state.soyState.length && last(state.soyState) != "literal") return null; else return last(state.localStates); }, electricInput: /^\s*\{(\/|\/template|\/deltemplate|\/switch|fallbackmsg|elseif|else|case|default|ifempty|\/literal\})$/, lineComment: "//", blockCommentStart: "/*", blockCommentEnd: "*/", blockCommentContinue: " * ", useInnerComments: false, fold: "indent" }; }, "htmlmixed"); CodeMirror.registerHelper("wordChars", "soy", /[\w$]/); CodeMirror.registerHelper("hintWords", "soy", indentingTags.concat( ["delpackage", "namespace", "alias", "print", "css", "debugger"])); CodeMirror.defineMIME("text/x-soy", "soy"); }); ================================================ FILE: third_party/CodeMirror/mode/soy/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "soy"); function MT(name) {test.mode(name, mode, Array.prototype.slice.call(arguments, 1));} // Test of small keywords and words containing them. MT('keywords-test', '[keyword {] [keyword as] worrying [keyword and] notorious [keyword as]', ' the Fandor[operator -]alias assassin, [keyword or]', ' Corcand cannot fit [keyword in] [keyword }]'); MT('let-test', '[keyword {template] [def .name][keyword }]', ' [keyword {let] [def $name]: [string "world"][keyword /}]', ' [tag&bracket <][tag h1][tag&bracket >]', ' Hello, [keyword {][variable-2 $name][keyword }]', ' [tag&bracket ]', '[keyword {/template}]', ''); MT('function-test', '[keyword {] [callee&variable css]([string "MyClass"])[keyword }]', '[tag&bracket <][tag input] [attribute value]=[string "]' + '[keyword {] [callee&variable index]([variable-2&error $list])[keyword }]' + '[string "][tag&bracket />]'); MT('namespace-test', '[keyword {namespace] [variable namespace][keyword }]') MT('namespace-with-attribute-test', '[keyword {namespace] [variable my.namespace.templates] ' + '[attribute requirecss]=[string "my.namespace"][keyword }]'); MT('operators-test', '[keyword {] [atom 1] [operator ==] [atom 1] [keyword }]', '[keyword {] [atom 1] [operator !=] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator +] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator -] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator *] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator /] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator %] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator <=] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator >=] [atom 2] [keyword }]', '[keyword {] [atom 3] [operator >] [atom 2] [keyword }]', '[keyword {] [atom 2] [operator >] [atom 3] [keyword }]', '[keyword {] [atom null] [operator ?:] [string ""] [keyword }]', '[keyword {] [variable-2&error $variable] [operator |] safeHtml [keyword }]') MT('primitive-test', '[keyword {] [atom true] [keyword }]', '[keyword {] [atom false] [keyword }]', '[keyword {] truethy [keyword }]', '[keyword {] falsey [keyword }]', '[keyword {] [atom 42] [keyword }]', '[keyword {] [atom .42] [keyword }]', '[keyword {] [atom 0.42] [keyword }]', '[keyword {] [atom -0.42] [keyword }]', '[keyword {] [atom -.2] [keyword }]', '[keyword {] [atom 6.03e23] [keyword }]', '[keyword {] [atom -0.03e0] [keyword }]', '[keyword {] [atom 0x1F] [keyword }]', '[keyword {] [atom 0x1F00BBEA] [keyword }]'); MT('param-type-test', '[keyword {@param] [def a]: ' + '[type list]<[[[type a]: [type int], ' + '[type b]: [type map]<[type string], ' + '[type bool]>]]>][keyword }]', '[keyword {@param] [def unknown]: [type ?][keyword }]', '[keyword {@param] [def list]: [type list]<[type ?]>[keyword }]'); MT('undefined-var', '[keyword {][variable-2&error $var]'); MT('param-scope-test', '[keyword {template] [def .a][keyword }]', ' [keyword {@param] [def x]: [type string][keyword }]', ' [keyword {][variable-2 $x][keyword }]', '[keyword {/template}]', '', '[keyword {template] [def .b][keyword }]', ' [keyword {][variable-2&error $x][keyword }]', '[keyword {/template}]', ''); MT('if-variable-test', '[keyword {if] [variable-2&error $showThing][keyword }]', ' Yo!', '[keyword {/if}]', ''); MT('defined-if-variable-test', '[keyword {template] [def .foo][keyword }]', ' [keyword {@param?] [def showThing]: [type bool][keyword }]', ' [keyword {if] [variable-2 $showThing][keyword }]', ' Yo!', ' [keyword {/if}]', '[keyword {/template}]', ''); MT('template-calls-test', '[keyword {call] [variable-2 .foo][keyword /}]', '[keyword {call] [variable foo][keyword /}]', '[keyword {call] [variable foo][keyword }] [keyword {/call}]', '[keyword {call] [variable first1.second.third_3][keyword /}]', '[keyword {call] [variable first1.second.third_3] [keyword }] [keyword {/call}]', ''); MT('foreach-scope-test', '[keyword {@param] [def bar]: [type string][keyword }]', '[keyword {foreach] [def $foo] [keyword in] [variable-2&error $foos][keyword }]', ' [keyword {][variable-2 $foo][keyword }]', '[keyword {/foreach}]', '[keyword {][variable-2&error $foo][keyword }]', '[keyword {][variable-2 $bar][keyword }]'); MT('foreach-ifempty-indent-test', '[keyword {foreach] [def $foo] [keyword in] [variable-2&error $foos][keyword }]', ' something', '[keyword {ifempty}]', ' nothing', '[keyword {/foreach}]', ''); MT('nested-kind-test', '[keyword {template] [def .foo] [attribute kind]=[string "html"][keyword }]', ' [tag&bracket <][tag div][tag&bracket >]', ' [keyword {call] [variable-2 .bar][keyword }]', ' [keyword {param] [property propertyName] [attribute kind]=[string "js"][keyword }]', ' [keyword var] [def bar] [operator =] [number 5];', ' [keyword {/param}]', ' [keyword {/call}]', ' [tag&bracket ]', '[keyword {/template}]', ''); MT('tag-starting-with-function-call-is-not-a-keyword', '[keyword {][callee&variable index]([variable-2&error $foo])[keyword }]', '[keyword {css] [string "some-class"][keyword }]', '[keyword {][callee&variable css]([string "some-class"])[keyword }]', ''); MT('allow-missing-colon-in-@param', '[keyword {template] [def .foo][keyword }]', ' [keyword {@param] [def showThing] [type bool][keyword }]', ' [keyword {if] [variable-2 $showThing][keyword }]', ' Yo!', ' [keyword {/if}]', '[keyword {/template}]', ''); MT('single-quote-strings', '[keyword {][string "foo"] [string \'bar\'][keyword }]', ''); MT('literal-comments', '[keyword {literal}]/* comment */ // comment[keyword {/literal}]'); MT('highlight-command-at-eol', '[keyword {msg]', ' [keyword }]'); })(); ================================================ FILE: third_party/CodeMirror/mode/sparql/index.html ================================================ CodeMirror: SPARQL mode

SPARQL mode

MIME types defined: application/sparql-query.

================================================ FILE: third_party/CodeMirror/mode/sparql/sparql.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sparql", function(config) { var indentUnit = config.indentUnit; var curPunc; function wordRegexp(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var ops = wordRegexp(["str", "lang", "langmatches", "datatype", "bound", "sameterm", "isiri", "isuri", "iri", "uri", "bnode", "count", "sum", "min", "max", "avg", "sample", "group_concat", "rand", "abs", "ceil", "floor", "round", "concat", "substr", "strlen", "replace", "ucase", "lcase", "encode_for_uri", "contains", "strstarts", "strends", "strbefore", "strafter", "year", "month", "day", "hours", "minutes", "seconds", "timezone", "tz", "now", "uuid", "struuid", "md5", "sha1", "sha256", "sha384", "sha512", "coalesce", "if", "strlang", "strdt", "isnumeric", "regex", "exists", "isblank", "isliteral", "a", "bind"]); var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", "graph", "by", "asc", "desc", "as", "having", "undef", "values", "group", "minus", "in", "not", "service", "silent", "using", "insert", "delete", "union", "true", "false", "with", "data", "copy", "to", "move", "add", "create", "drop", "clear", "load"]); var operatorChars = /[*+\-<>=&|\^\/!\?]/; function tokenBase(stream, state) { var ch = stream.next(); curPunc = null; if (ch == "$" || ch == "?") { if(ch == "?" && stream.match(/\s/, false)){ return "operator"; } stream.match(/^[\w\d]*/); return "variable-2"; } else if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) { stream.match(/^[^\s\u00a0>]*>?/); return "atom"; } else if (ch == "\"" || ch == "'") { state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); } else if (/[{}\(\),\.;\[\]]/.test(ch)) { curPunc = ch; return "bracket"; } else if (ch == "#") { stream.skipToEnd(); return "comment"; } else if (operatorChars.test(ch)) { stream.eatWhile(operatorChars); return "operator"; } else if (ch == ":") { stream.eatWhile(/[\w\d\._\-]/); return "atom"; } else if (ch == "@") { stream.eatWhile(/[a-z\d\-]/i); return "meta"; } else { stream.eatWhile(/[_\w\d]/); if (stream.eat(":")) { stream.eatWhile(/[\w\d_\-]/); return "atom"; } var word = stream.current(); if (ops.test(word)) return "builtin"; else if (keywords.test(word)) return "keyword"; else return "variable"; } } function tokenLiteral(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = !escaped && ch == "\\"; } return "string"; }; } function pushContext(state, type, col) { state.context = {prev: state.context, indent: state.indent, col: col, type: type}; } function popContext(state) { state.indent = state.context.indent; state.context = state.context.prev; } return { startState: function() { return {tokenize: tokenBase, context: null, indent: 0, col: 0}; }, token: function(stream, state) { if (stream.sol()) { if (state.context && state.context.align == null) state.context.align = false; state.indent = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") { state.context.align = true; } if (curPunc == "(") pushContext(state, ")", stream.column()); else if (curPunc == "[") pushContext(state, "]", stream.column()); else if (curPunc == "{") pushContext(state, "}", stream.column()); else if (/[\]\}\)]/.test(curPunc)) { while (state.context && state.context.type == "pattern") popContext(state); if (state.context && curPunc == state.context.type) { popContext(state); if (curPunc == "}" && state.context && state.context.type == "pattern") popContext(state); } } else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state); else if (/atom|string|variable/.test(style) && state.context) { if (/[\}\]]/.test(state.context.type)) pushContext(state, "pattern", stream.column()); else if (state.context.type == "pattern" && !state.context.align) { state.context.align = true; state.context.col = stream.column(); } } return style; }, indent: function(state, textAfter) { var firstChar = textAfter && textAfter.charAt(0); var context = state.context; if (/[\]\}]/.test(firstChar)) while (context && context.type == "pattern") context = context.prev; var closing = context && firstChar == context.type; if (!context) return 0; else if (context.type == "pattern") return context.col; else if (context.align) return context.col + (closing ? 0 : 1); else return context.indent + (closing ? 0 : indentUnit); }, lineComment: "#" }; }); CodeMirror.defineMIME("application/sparql-query", "sparql"); }); ================================================ FILE: third_party/CodeMirror/mode/spreadsheet/index.html ================================================ CodeMirror: Spreadsheet mode

Spreadsheet mode

MIME types defined: text/x-spreadsheet.

The Spreadsheet Mode

Created by Robert Plummer

================================================ FILE: third_party/CodeMirror/mode/spreadsheet/spreadsheet.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("spreadsheet", function () { return { startState: function () { return { stringType: null, stack: [] }; }, token: function (stream, state) { if (!stream) return; //check for state changes if (state.stack.length === 0) { //strings if ((stream.peek() == '"') || (stream.peek() == "'")) { state.stringType = stream.peek(); stream.next(); // Skip quote state.stack.unshift("string"); } } //return state //stack has switch (state.stack[0]) { case "string": while (state.stack[0] === "string" && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.stack.shift(); // Clear flag } else if (stream.peek() === "\\") { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return "string"; case "characterClass": while (state.stack[0] === "characterClass" && !stream.eol()) { if (!(stream.match(/^[^\]\\]+/) || stream.match(/^\\./))) state.stack.shift(); } return "operator"; } var peek = stream.peek(); //no stack switch (peek) { case "[": stream.next(); state.stack.unshift("characterClass"); return "bracket"; case ":": stream.next(); return "operator"; case "\\": if (stream.match(/\\[a-z]+/)) return "string-2"; else { stream.next(); return "atom"; } case ".": case ",": case ";": case "*": case "-": case "+": case "^": case "<": case "/": case "=": stream.next(); return "atom"; case "$": stream.next(); return "builtin"; } if (stream.match(/\d+/)) { if (stream.match(/^\w+/)) return "error"; return "number"; } else if (stream.match(/^[a-zA-Z_]\w*/)) { if (stream.match(/(?=[\(.])/, false)) return "keyword"; return "variable-2"; } else if (["[", "]", "(", ")", "{", "}"].indexOf(peek) != -1) { stream.next(); return "bracket"; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }); CodeMirror.defineMIME("text/x-spreadsheet", "spreadsheet"); }); ================================================ FILE: third_party/CodeMirror/mode/sql/index.html ================================================ CodeMirror: SQL Mode for CodeMirror

SQL Mode for CodeMirror

MIME types defined: text/x-sql, text/x-mysql, text/x-mariadb, text/x-cassandra, text/x-plsql, text/x-mssql, text/x-hive, text/x-pgsql, text/x-gql, text/x-gpsql. text/x-esper.

================================================ FILE: third_party/CodeMirror/mode/sql/sql.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("sql", function(config, parserConfig) { var client = parserConfig.client || {}, atoms = parserConfig.atoms || {"false": true, "true": true, "null": true}, builtin = parserConfig.builtin || set(defaultBuiltin), keywords = parserConfig.keywords || set(sqlKeywords), operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^\/]/, support = parserConfig.support || {}, hooks = parserConfig.hooks || {}, dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true}, backslashStringEscapes = parserConfig.backslashStringEscapes !== false, brackets = parserConfig.brackets || /^[\{}\(\)\[\]]/, punctuation = parserConfig.punctuation || /^[;.,:]/ function tokenBase(stream, state) { var ch = stream.next(); // call hooks from the mime type if (hooks[ch]) { var result = hooks[ch](stream, state); if (result !== false) return result; } if (support.hexNumber && ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { // hex // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html return "number"; } else if (support.binaryNumber && (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) || (ch == "0" && stream.match(/^b[01]+/)))) { // bitstring // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html return "number"; } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { // numbers // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); support.decimallessFloat && stream.match(/^\.(?!\.)/); return "number"; } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { // placeholders return "variable-3"; } else if (ch == "'" || (ch == '"' && support.doubleQuote)) { // strings // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); } else if ((((support.nCharCast && (ch == "n" || ch == "N")) || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) && (stream.peek() == "'" || stream.peek() == '"'))) { // charset casting: _utf8'str', N'str', n'str' // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html return "keyword"; } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { // 1-line comment stream.skipToEnd(); return "comment"; } else if ((support.commentHash && ch == "#") || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) { // 1-line comments // ref: https://kb.askmonty.org/en/comment-syntax/ stream.skipToEnd(); return "comment"; } else if (ch == "/" && stream.eat("*")) { // multi-line comments // ref: https://kb.askmonty.org/en/comment-syntax/ state.tokenize = tokenComment(1); return state.tokenize(stream, state); } else if (ch == ".") { // .1 for 0.1 if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) return "number"; if (stream.match(/^\.+/)) return null // .table_name (ODBC) // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) return "variable-2"; } else if (operatorChars.test(ch)) { // operators stream.eatWhile(operatorChars); return "operator"; } else if (brackets.test(ch)) { // brackets return "bracket"; } else if (punctuation.test(ch)) { // punctuation stream.eatWhile(punctuation); return "punctuation"; } else if (ch == '{' && (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) { // dates (weird ODBC syntax) // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html return "number"; } else { stream.eatWhile(/^[_\w\d]/); var word = stream.current().toLowerCase(); // dates (standard SQL syntax) // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) return "number"; if (atoms.hasOwnProperty(word)) return "atom"; if (builtin.hasOwnProperty(word)) return "builtin"; if (keywords.hasOwnProperty(word)) return "keyword"; if (client.hasOwnProperty(word)) return "string-2"; return null; } } // 'string', with char specified in quote escaped by '\' function tokenLiteral(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = backslashStringEscapes && !escaped && ch == "\\"; } return "string"; }; } function tokenComment(depth) { return function(stream, state) { var m = stream.match(/^.*?(\/\*|\*\/)/) if (!m) stream.skipToEnd() else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1) else if (depth > 1) state.tokenize = tokenComment(depth - 1) else state.tokenize = tokenBase return "comment" } } function pushContext(stream, state, type) { state.context = { prev: state.context, indent: stream.indentation(), col: stream.column(), type: type }; } function popContext(state) { state.indent = state.context.indent; state.context = state.context.prev; } return { startState: function() { return {tokenize: tokenBase, context: null}; }, token: function(stream, state) { if (stream.sol()) { if (state.context && state.context.align == null) state.context.align = false; } if (state.tokenize == tokenBase && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style == "comment") return style; if (state.context && state.context.align == null) state.context.align = true; var tok = stream.current(); if (tok == "(") pushContext(stream, state, ")"); else if (tok == "[") pushContext(stream, state, "]"); else if (state.context && state.context.type == tok) popContext(state); return style; }, indent: function(state, textAfter) { var cx = state.context; if (!cx) return CodeMirror.Pass; var closing = textAfter.charAt(0) == cx.type; if (cx.align) return cx.col + (closing ? 0 : 1); else return cx.indent + (closing ? 0 : config.indentUnit); }, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--", closeBrackets: "()[]{}''\"\"``" }; }); // `identifier` function hookIdentifier(stream) { // MySQL/MariaDB identifiers // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html var ch; while ((ch = stream.next()) != null) { if (ch == "`" && !stream.eat("`")) return "variable-2"; } stream.backUp(stream.current().length - 1); return stream.eatWhile(/\w/) ? "variable-2" : null; } // "identifier" function hookIdentifierDoublequote(stream) { // Standard SQL /SQLite identifiers // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier // ref: http://sqlite.org/lang_keywords.html var ch; while ((ch = stream.next()) != null) { if (ch == "\"" && !stream.eat("\"")) return "variable-2"; } stream.backUp(stream.current().length - 1); return stream.eatWhile(/\w/) ? "variable-2" : null; } // variable token function hookVar(stream) { // variables // @@prefix.varName @varName // varName can be quoted with ` or ' or " // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html if (stream.eat("@")) { stream.match(/^session\./); stream.match(/^local\./); stream.match(/^global\./); } if (stream.eat("'")) { stream.match(/^.*'/); return "variable-2"; } else if (stream.eat('"')) { stream.match(/^.*"/); return "variable-2"; } else if (stream.eat("`")) { stream.match(/^.*`/); return "variable-2"; } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { return "variable-2"; } return null; }; // short client keyword token function hookClient(stream) { // \N means NULL // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html if (stream.eat("N")) { return "atom"; } // \g, etc // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; } // these keywords are used by all SQL dialects (however, a mode can still overwrite it) 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 "; // turn a space-separated list into an array function set(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } 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" // A generic SQL Mode. It's not a standard, it just try to support what is generally supported CodeMirror.defineMIME("text/x-sql", { name: "sql", keywords: set(sqlKeywords + "begin"), builtin: set(defaultBuiltin), atoms: set("false true null unknown"), dateSQL: set("date time timestamp"), support: set("ODBCdotTable doubleQuote binaryNumber hexNumber") }); CodeMirror.defineMIME("text/x-mssql", { name: "sql", 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"), 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"), 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 "), atoms: set("is not null like and or in left right between inner outer join all any some cross unpivot pivot exists"), operatorChars: /^[*+\-%<>!=^\&|\/]/, brackets: /^[\{}\(\)]/, punctuation: /^[;.,:/]/, backslashStringEscapes: false, dateSQL: set("date datetimeoffset datetime2 smalldatetime datetime time"), hooks: { "@": hookVar } }); CodeMirror.defineMIME("text/x-mysql", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), 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"), 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"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), hooks: { "@": hookVar, "`": hookIdentifier, "\\": hookClient } }); CodeMirror.defineMIME("text/x-mariadb", { name: "sql", client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"), 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"), 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"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber doubleQuote nCharCast charsetCast commentHash commentSpaceRequired"), hooks: { "@": hookVar, "`": hookIdentifier, "\\": hookClient } }); // provided by the phpLiteAdmin project - phpliteadmin.org CodeMirror.defineMIME("text/x-sqlite", { name: "sql", // commands of the official SQLite client, ref: https://www.sqlite.org/cli.html#dotcmd 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"), // ref: http://sqlite.org/lang_keywords.html 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"), // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types. 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"), // ref: http://sqlite.org/syntax/literal-value.html atoms: set("null current_date current_time current_timestamp"), // ref: http://sqlite.org/lang_expr.html#binaryops operatorChars: /^[*+\-%<>!=&|/~]/, // SQLite is weakly typed, ref: http://sqlite.org/datatype3.html. This is just a list of some common types. dateSQL: set("date time timestamp datetime"), support: set("decimallessFloat zerolessFloat"), identifierQuote: "\"", //ref: http://sqlite.org/lang_keywords.html hooks: { // bind-parameters ref:http://sqlite.org/lang_expr.html#varparam "@": hookVar, ":": hookVar, "?": hookVar, "$": hookVar, // The preferred way to escape Identifiers is using double quotes, ref: http://sqlite.org/lang_keywords.html "\"": hookIdentifierDoublequote, // there is also support for backtics, ref: http://sqlite.org/lang_keywords.html "`": hookIdentifier } }); // the query language used by Apache Cassandra is called CQL, but this mime type // is called Cassandra to avoid confusion with Contextual Query Language CodeMirror.defineMIME("text/x-cassandra", { name: "sql", client: { }, 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"), builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"), atoms: set("false true infinity NaN"), operatorChars: /^[<>=]/, dateSQL: { }, support: set("commentSlashSlash decimallessFloat"), hooks: { } }); // this is based on Peter Raganitsch's 'plsql' mode CodeMirror.defineMIME("text/x-plsql", { name: "sql", 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"), 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"), 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"), operatorChars: /^[*\/+\-%<>!=~]/, dateSQL: set("date time timestamp"), support: set("doubleQuote nCharCast zerolessFloat binaryNumber hexNumber") }); // Created to support specific hive keywords CodeMirror.defineMIME("text/x-hive", { name: "sql", 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"), 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"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=]/, dateSQL: set("date timestamp"), support: set("ODBCdotTable doubleQuote binaryNumber hexNumber") }); CodeMirror.defineMIME("text/x-pgsql", { name: "sql", client: set("source"), // https://www.postgresql.org/docs/10/static/sql-keywords-appendix.html 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"), // https://www.postgresql.org/docs/10/static/datatype.html 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"), atoms: set("false true null unknown"), operatorChars: /^[*\/+\-%<>!=&|^\/#@?~]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast") }); // Google's SQL-like query language, GQL CodeMirror.defineMIME("text/x-gql", { name: "sql", keywords: set("ancestor and asc by contains desc descendant distinct from group has in is limit offset on order select superset where"), atoms: set("false true"), builtin: set("blob datetime first key __key__ string integer double boolean null"), operatorChars: /^[*+\-%<>!=]/ }); // Greenplum CodeMirror.defineMIME("text/x-gpsql", { name: "sql", client: set("source"), //https://github.com/greenplum-db/gpdb/blob/master/src/include/parser/kwlist.h 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"), 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"), atoms: set("false true null unknown"), operatorChars: /^[*+\-%<>!=&|^\/#@?~]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable decimallessFloat zerolessFloat binaryNumber hexNumber nCharCast charsetCast") }); // Spark SQL CodeMirror.defineMIME("text/x-sparksql", { name: "sql", 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"), builtin: set("tinyint smallint int bigint boolean float double string binary timestamp decimal array map struct uniontype delimited serde sequencefile textfile rcfile inputformat outputformat"), atoms: set("false true null"), operatorChars: /^[*\/+\-%<>!=~&|^]/, dateSQL: set("date time timestamp"), support: set("ODBCdotTable doubleQuote zerolessFloat") }); // Esper CodeMirror.defineMIME("text/x-esper", { name: "sql", client: set("source"), // http://www.espertech.com/esper/release-5.5.0/esper-reference/html/appendix_keywords.html 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"), builtin: {}, atoms: set("false true null"), operatorChars: /^[*+\-%<>!=&|^\/#@?~]/, dateSQL: set("time"), support: set("decimallessFloat zerolessFloat binaryNumber hexNumber") }); }); /* How Properties of Mime Types are used by SQL Mode ================================================= keywords: A list of keywords you want to be highlighted. builtin: A list of builtin types you want to be highlighted (if you want types to be of class "builtin" instead of "keyword"). operatorChars: All characters that must be handled as operators. client: Commands parsed and executed by the client (not the server). support: A list of supported syntaxes which are not common, but are supported by more than 1 DBMS. * ODBCdotTable: .tableName * zerolessFloat: .1 * doubleQuote * nCharCast: N'string' * charsetCast: _utf8'string' * commentHash: use # char for comments * commentSlashSlash: use // for comments * commentSpaceRequired: require a space after -- for comments atoms: Keywords that must be highlighted as atoms,. Some DBMS's support more atoms than others: UNKNOWN, INFINITY, UNDERFLOW, NaN... dateSQL: Used for date/time SQL standard syntax, because not all DBMS's support same temporal types. */ ================================================ FILE: third_party/CodeMirror/mode/stex/index.html ================================================ CodeMirror: sTeX mode

sTeX mode

sTeX mode supports this option:

inMathMode: boolean
Whether to start parsing in math mode (default: false).

MIME types defined: text/x-stex.

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/stex/stex.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /* * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de) * Licence: MIT */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("stex", function(_config, parserConfig) { "use strict"; function pushCommand(state, command) { state.cmdState.push(command); } function peekCommand(state) { if (state.cmdState.length > 0) { return state.cmdState[state.cmdState.length - 1]; } else { return null; } } function popCommand(state) { var plug = state.cmdState.pop(); if (plug) { plug.closeBracket(); } } // returns the non-default plugin closest to the end of the list function getMostPowerful(state) { var context = state.cmdState; for (var i = context.length - 1; i >= 0; i--) { var plug = context[i]; if (plug.name == "DEFAULT") { continue; } return plug; } return { styleIdentifier: function() { return null; } }; } function addPluginPattern(pluginName, cmdStyle, styles) { return function () { this.name = pluginName; this.bracketNo = 0; this.style = cmdStyle; this.styles = styles; this.argument = null; // \begin and \end have arguments that follow. These are stored in the plugin this.styleIdentifier = function() { return this.styles[this.bracketNo - 1] || null; }; this.openBracket = function() { this.bracketNo++; return "bracket"; }; this.closeBracket = function() {}; }; } var plugins = {}; plugins["importmodule"] = addPluginPattern("importmodule", "tag", ["string", "builtin"]); plugins["documentclass"] = addPluginPattern("documentclass", "tag", ["", "atom"]); plugins["usepackage"] = addPluginPattern("usepackage", "tag", ["atom"]); plugins["begin"] = addPluginPattern("begin", "tag", ["atom"]); plugins["end"] = addPluginPattern("end", "tag", ["atom"]); plugins["label" ] = addPluginPattern("label" , "tag", ["atom"]); plugins["ref" ] = addPluginPattern("ref" , "tag", ["atom"]); plugins["eqref" ] = addPluginPattern("eqref" , "tag", ["atom"]); plugins["cite" ] = addPluginPattern("cite" , "tag", ["atom"]); plugins["bibitem" ] = addPluginPattern("bibitem" , "tag", ["atom"]); plugins["Bibitem" ] = addPluginPattern("Bibitem" , "tag", ["atom"]); plugins["RBibitem" ] = addPluginPattern("RBibitem" , "tag", ["atom"]); plugins["DEFAULT"] = function () { this.name = "DEFAULT"; this.style = "tag"; this.styleIdentifier = this.openBracket = this.closeBracket = function() {}; }; function setState(state, f) { state.f = f; } // called when in a normal (no environment) context function normal(source, state) { var plug; // Do we look like '\command' ? If so, attempt to apply the plugin 'command' if (source.match(/^\\[a-zA-Z@]+/)) { var cmdName = source.current().slice(1); plug = plugins[cmdName] || plugins["DEFAULT"]; plug = new plug(); pushCommand(state, plug); setState(state, beginParams); return plug.style; } // escape characters if (source.match(/^\\[$&%#{}_]/)) { return "tag"; } // white space control characters if (source.match(/^\\[,;!\/\\]/)) { return "tag"; } // find if we're starting various math modes if (source.match("\\[")) { setState(state, function(source, state){ return inMathMode(source, state, "\\]"); }); return "keyword"; } if (source.match("\\(")) { setState(state, function(source, state){ return inMathMode(source, state, "\\)"); }); return "keyword"; } if (source.match("$$")) { setState(state, function(source, state){ return inMathMode(source, state, "$$"); }); return "keyword"; } if (source.match("$")) { setState(state, function(source, state){ return inMathMode(source, state, "$"); }); return "keyword"; } var ch = source.next(); if (ch == "%") { source.skipToEnd(); return "comment"; } else if (ch == '}' || ch == ']') { plug = peekCommand(state); if (plug) { plug.closeBracket(ch); setState(state, beginParams); } else { return "error"; } return "bracket"; } else if (ch == '{' || ch == '[') { plug = plugins["DEFAULT"]; plug = new plug(); pushCommand(state, plug); return "bracket"; } else if (/\d/.test(ch)) { source.eatWhile(/[\w.%]/); return "atom"; } else { source.eatWhile(/[\w\-_]/); plug = getMostPowerful(state); if (plug.name == 'begin') { plug.argument = source.current(); } return plug.styleIdentifier(); } } function inMathMode(source, state, endModeSeq) { if (source.eatSpace()) { return null; } if (endModeSeq && source.match(endModeSeq)) { setState(state, normal); return "keyword"; } if (source.match(/^\\[a-zA-Z@]+/)) { return "tag"; } if (source.match(/^[a-zA-Z]+/)) { return "variable-2"; } // escape characters if (source.match(/^\\[$&%#{}_]/)) { return "tag"; } // white space control characters if (source.match(/^\\[,;!\/]/)) { return "tag"; } // special math-mode characters if (source.match(/^[\^_&]/)) { return "tag"; } // non-special characters if (source.match(/^[+\-<>|=,\/@!*:;'"`~#?]/)) { return null; } if (source.match(/^(\d+\.\d*|\d*\.\d+|\d+)/)) { return "number"; } var ch = source.next(); if (ch == "{" || ch == "}" || ch == "[" || ch == "]" || ch == "(" || ch == ")") { return "bracket"; } if (ch == "%") { source.skipToEnd(); return "comment"; } return "error"; } function beginParams(source, state) { var ch = source.peek(), lastPlug; if (ch == '{' || ch == '[') { lastPlug = peekCommand(state); lastPlug.openBracket(ch); source.eat(ch); setState(state, normal); return "bracket"; } if (/[ \t\r]/.test(ch)) { source.eat(ch); return null; } setState(state, normal); popCommand(state); return normal(source, state); } return { startState: function() { var f = parserConfig.inMathMode ? function(source, state){ return inMathMode(source, state); } : normal; return { cmdState: [], f: f }; }, copyState: function(s) { return { cmdState: s.cmdState.slice(), f: s.f }; }, token: function(stream, state) { return state.f(stream, state); }, blankLine: function(state) { state.f = normal; state.cmdState.length = 0; }, lineComment: "%" }; }); CodeMirror.defineMIME("text/x-stex", "stex"); CodeMirror.defineMIME("text/x-latex", "stex"); }); ================================================ FILE: third_party/CodeMirror/mode/stex/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({tabSize: 4}, "stex"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("word", "foo"); MT("twoWords", "foo bar"); MT("beginEndDocument", "[tag \\begin][bracket {][atom document][bracket }]", "[tag \\end][bracket {][atom document][bracket }]"); MT("beginEndEquation", "[tag \\begin][bracket {][atom equation][bracket }]", " E=mc^2", "[tag \\end][bracket {][atom equation][bracket }]"); MT("beginModule", "[tag \\begin][bracket {][atom module][bracket }[[]]]"); MT("beginModuleId", "[tag \\begin][bracket {][atom module][bracket }[[]id=bbt-size[bracket ]]]"); MT("importModule", "[tag \\importmodule][bracket [[][string b-b-t][bracket ]]{][builtin b-b-t][bracket }]"); MT("importModulePath", "[tag \\importmodule][bracket [[][tag \\KWARCslides][bracket {][string dmath/en/cardinality][bracket }]]{][builtin card][bracket }]"); MT("psForPDF", "[tag \\PSforPDF][bracket [[][atom 1][bracket ]]{]#1[bracket }]"); MT("comment", "[comment % foo]"); MT("tagComment", "[tag \\item][comment % bar]"); MT("commentTag", " [comment % \\item]"); MT("commentLineBreak", "[comment %]", "foo"); MT("tagErrorCurly", "[tag \\begin][error }][bracket {]"); MT("tagErrorSquare", "[tag \\item][error ]]][bracket {]"); MT("commentCurly", "[comment % }]"); MT("tagHash", "the [tag \\#] key"); MT("tagNumber", "a [tag \\$][atom 5] stetson"); MT("tagPercent", "[atom 100][tag \\%] beef"); MT("tagAmpersand", "L [tag \\&] N"); MT("tagUnderscore", "foo[tag \\_]bar"); MT("tagBracketOpen", "[tag \\emph][bracket {][tag \\{][bracket }]"); MT("tagBracketClose", "[tag \\emph][bracket {][tag \\}][bracket }]"); MT("tagLetterNumber", "section [tag \\S][atom 1]"); MT("textTagNumber", "para [tag \\P][atom 2]"); MT("thinspace", "x[tag \\,]y"); MT("thickspace", "x[tag \\;]y"); MT("negativeThinspace", "x[tag \\!]y"); MT("periodNotSentence", "J.\\ L.\\ is"); MT("periodSentence", "X[tag \\@]. The"); MT("italicCorrection", "[bracket {][tag \\em] If[tag \\/][bracket }] I"); MT("tagBracket", "[tag \\newcommand][bracket {][tag \\pop][bracket }]"); MT("inlineMathTagFollowedByNumber", "[keyword $][tag \\pi][number 2][keyword $]"); MT("inlineMath", "[keyword $][number 3][variable-2 x][tag ^][number 2.45]-[tag \\sqrt][bracket {][tag \\$\\alpha][bracket }] = [number 2][keyword $] other text"); MT("inlineMathLatexStyle", "[keyword \\(][number 3][variable-2 x][tag ^][number 2.45]-[tag \\sqrt][bracket {][tag \\$\\alpha][bracket }] = [number 2][keyword \\)] other text"); MT("displayMath", "More [keyword $$]\t[variable-2 S][tag ^][variable-2 n][tag \\sum] [variable-2 i][keyword $$] other text"); MT("displayMath environment", "[tag \\begin][bracket {][atom equation][bracket }] x [tag \\end][bracket {][atom equation][bracket }] other text"); MT("displayMath environment with label", "[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 }]"); MT("mathWithComment", "[keyword $][variable-2 x] [comment % $]", "[variable-2 y][keyword $] other text"); MT("lineBreakArgument", "[tag \\\\][bracket [[][atom 1cm][bracket ]]]"); })(); ================================================ FILE: third_party/CodeMirror/mode/stylus/index.html ================================================ CodeMirror: Stylus mode

Stylus mode

MIME types defined: text/x-styl.

Created by Dmitry Kiselyov

================================================ FILE: third_party/CodeMirror/mode/stylus/stylus.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Stylus mode created by Dmitry Kiselyov http://git.io/AaRB (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("stylus", function(config) { var indentUnit = config.indentUnit, indentUnitString = '', tagKeywords = keySet(tagKeywords_), tagVariablesRegexp = /^(a|b|i|s|col|em)$/i, propertyKeywords = keySet(propertyKeywords_), nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_), valueKeywords = keySet(valueKeywords_), colorKeywords = keySet(colorKeywords_), documentTypes = keySet(documentTypes_), documentTypesRegexp = wordRegexp(documentTypes_), mediaFeatures = keySet(mediaFeatures_), mediaTypes = keySet(mediaTypes_), fontProperties = keySet(fontProperties_), operatorsRegexp = /^\s*([.]{2,3}|&&|\|\||\*\*|[?!=:]?=|[-+*\/%<>]=?|\?:|\~)/, wordOperatorKeywordsRegexp = wordRegexp(wordOperatorKeywords_), blockKeywords = keySet(blockKeywords_), vendorPrefixesRegexp = new RegExp(/^\-(moz|ms|o|webkit)-/i), commonAtoms = keySet(commonAtoms_), firstWordMatch = "", states = {}, ch, style, type, override; while (indentUnitString.length < indentUnit) indentUnitString += ' '; /** * Tokenizers */ function tokenBase(stream, state) { firstWordMatch = stream.string.match(/(^[\w-]+\s*=\s*$)|(^\s*[\w-]+\s*=\s*[\w-])|(^\s*(\.|#|@|\$|\&|\[|\d|\+|::?|\{|\>|~|\/)?\s*[\w-]*([a-z0-9-]|\*|\/\*)(\(|,)?)/); state.context.line.firstWord = firstWordMatch ? firstWordMatch[0].replace(/^\s*/, "") : ""; state.context.line.indent = stream.indentation(); ch = stream.peek(); // Line comment if (stream.match("//")) { stream.skipToEnd(); return ["comment", "comment"]; } // Block comment if (stream.match("/*")) { state.tokenize = tokenCComment; return tokenCComment(stream, state); } // String if (ch == "\"" || ch == "'") { stream.next(); state.tokenize = tokenString(ch); return state.tokenize(stream, state); } // Def if (ch == "@") { stream.next(); stream.eatWhile(/[\w\\-]/); return ["def", stream.current()]; } // ID selector or Hex color if (ch == "#") { stream.next(); // Hex color if (stream.match(/^[0-9a-f]{3}([0-9a-f]([0-9a-f]{2}){0,2})?\b/i)) { return ["atom", "atom"]; } // ID selector if (stream.match(/^[a-z][\w-]*/i)) { return ["builtin", "hash"]; } } // Vendor prefixes if (stream.match(vendorPrefixesRegexp)) { return ["meta", "vendor-prefixes"]; } // Numbers if (stream.match(/^-?[0-9]?\.?[0-9]/)) { stream.eatWhile(/[a-z%]/i); return ["number", "unit"]; } // !important|optional if (ch == "!") { stream.next(); return [stream.match(/^(important|optional)/i) ? "keyword": "operator", "important"]; } // Class if (ch == "." && stream.match(/^\.[a-z][\w-]*/i)) { return ["qualifier", "qualifier"]; } // url url-prefix domain regexp if (stream.match(documentTypesRegexp)) { if (stream.peek() == "(") state.tokenize = tokenParenthesized; return ["property", "word"]; } // Mixins / Functions if (stream.match(/^[a-z][\w-]*\(/i)) { stream.backUp(1); return ["keyword", "mixin"]; } // Block mixins if (stream.match(/^(\+|-)[a-z][\w-]*\(/i)) { stream.backUp(1); return ["keyword", "block-mixin"]; } // Parent Reference BEM naming if (stream.string.match(/^\s*&/) && stream.match(/^[-_]+[a-z][\w-]*/)) { return ["qualifier", "qualifier"]; } // / Root Reference & Parent Reference if (stream.match(/^(\/|&)(-|_|:|\.|#|[a-z])/)) { stream.backUp(1); return ["variable-3", "reference"]; } if (stream.match(/^&{1}\s*$/)) { return ["variable-3", "reference"]; } // Word operator if (stream.match(wordOperatorKeywordsRegexp)) { return ["operator", "operator"]; } // Word if (stream.match(/^\$?[-_]*[a-z0-9]+[\w-]*/i)) { // Variable if (stream.match(/^(\.|\[)[\w-\'\"\]]+/i, false)) { if (!wordIsTag(stream.current())) { stream.match(/\./); return ["variable-2", "variable-name"]; } } return ["variable-2", "word"]; } // Operators if (stream.match(operatorsRegexp)) { return ["operator", stream.current()]; } // Delimiters if (/[:;,{}\[\]\(\)]/.test(ch)) { stream.next(); return [null, ch]; } // Non-detected items stream.next(); return [null, null]; } /** * Token comment */ function tokenCComment(stream, state) { var maybeEnd = false, ch; while ((ch = stream.next()) != null) { if (maybeEnd && ch == "/") { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return ["comment", "comment"]; } /** * Token string */ function tokenString(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { if (quote == ")") stream.backUp(1); break; } escaped = !escaped && ch == "\\"; } if (ch == quote || !escaped && quote != ")") state.tokenize = null; return ["string", "string"]; }; } /** * Token parenthesized */ function tokenParenthesized(stream, state) { stream.next(); // Must be "(" if (!stream.match(/\s*[\"\')]/, false)) state.tokenize = tokenString(")"); else state.tokenize = null; return [null, "("]; } /** * Context management */ function Context(type, indent, prev, line) { this.type = type; this.indent = indent; this.prev = prev; this.line = line || {firstWord: "", indent: 0}; } function pushContext(state, stream, type, indent) { indent = indent >= 0 ? indent : indentUnit; state.context = new Context(type, stream.indentation() + indent, state.context); return type; } function popContext(state, currentIndent) { var contextIndent = state.context.indent - indentUnit; currentIndent = currentIndent || false; state.context = state.context.prev; if (currentIndent) state.context.indent = contextIndent; return state.context.type; } function pass(type, stream, state) { return states[state.context.type](type, stream, state); } function popAndPass(type, stream, state, n) { for (var i = n || 1; i > 0; i--) state.context = state.context.prev; return pass(type, stream, state); } /** * Parser */ function wordIsTag(word) { return word.toLowerCase() in tagKeywords; } function wordIsProperty(word) { word = word.toLowerCase(); return word in propertyKeywords || word in fontProperties; } function wordIsBlock(word) { return word.toLowerCase() in blockKeywords; } function wordIsVendorPrefix(word) { return word.toLowerCase().match(vendorPrefixesRegexp); } function wordAsValue(word) { var wordLC = word.toLowerCase(); var override = "variable-2"; if (wordIsTag(word)) override = "tag"; else if (wordIsBlock(word)) override = "block-keyword"; else if (wordIsProperty(word)) override = "property"; else if (wordLC in valueKeywords || wordLC in commonAtoms) override = "atom"; else if (wordLC == "return" || wordLC in colorKeywords) override = "keyword"; // Font family else if (word.match(/^[A-Z]/)) override = "string"; return override; } function typeIsBlock(type, stream) { return ((endOfLine(stream) && (type == "{" || type == "]" || type == "hash" || type == "qualifier")) || type == "block-mixin"); } function typeIsInterpolation(type, stream) { return type == "{" && stream.match(/^\s*\$?[\w-]+/i, false); } function typeIsPseudo(type, stream) { return type == ":" && stream.match(/^[a-z-]+/, false); } function startOfLine(stream) { return stream.sol() || stream.string.match(new RegExp("^\\s*" + escapeRegExp(stream.current()))); } function endOfLine(stream) { return stream.eol() || stream.match(/^\s*$/, false); } function firstWordOfLine(line) { var re = /^\s*[-_]*[a-z0-9]+[\w-]*/i; var result = typeof line == "string" ? line.match(re) : line.string.match(re); return result ? result[0].replace(/^\s*/, "") : ""; } /** * Block */ states.block = function(type, stream, state) { if ((type == "comment" && startOfLine(stream)) || (type == "," && endOfLine(stream)) || type == "mixin") { return pushContext(state, stream, "block", 0); } if (typeIsInterpolation(type, stream)) { return pushContext(state, stream, "interpolation"); } if (endOfLine(stream) && type == "]") { if (!/^\s*(\.|#|:|\[|\*|&)/.test(stream.string) && !wordIsTag(firstWordOfLine(stream))) { return pushContext(state, stream, "block", 0); } } if (typeIsBlock(type, stream)) { return pushContext(state, stream, "block"); } if (type == "}" && endOfLine(stream)) { return pushContext(state, stream, "block", 0); } if (type == "variable-name") { if (stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/) || wordIsBlock(firstWordOfLine(stream))) { return pushContext(state, stream, "variableName"); } else { return pushContext(state, stream, "variableName", 0); } } if (type == "=") { if (!endOfLine(stream) && !wordIsBlock(firstWordOfLine(stream))) { return pushContext(state, stream, "block", 0); } return pushContext(state, stream, "block"); } if (type == "*") { if (endOfLine(stream) || stream.match(/\s*(,|\.|#|\[|:|{)/,false)) { override = "tag"; return pushContext(state, stream, "block"); } } if (typeIsPseudo(type, stream)) { return pushContext(state, stream, "pseudo"); } if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) { return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock"); } if (/@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) { return pushContext(state, stream, "keyframes"); } if (/@extends?/.test(type)) { return pushContext(state, stream, "extend", 0); } if (type && type.charAt(0) == "@") { // Property Lookup if (stream.indentation() > 0 && wordIsProperty(stream.current().slice(1))) { override = "variable-2"; return "block"; } if (/(@import|@require|@charset)/.test(type)) { return pushContext(state, stream, "block", 0); } return pushContext(state, stream, "block"); } if (type == "reference" && endOfLine(stream)) { return pushContext(state, stream, "block"); } if (type == "(") { return pushContext(state, stream, "parens"); } if (type == "vendor-prefixes") { return pushContext(state, stream, "vendorPrefixes"); } if (type == "word") { var word = stream.current(); override = wordAsValue(word); if (override == "property") { if (startOfLine(stream)) { return pushContext(state, stream, "block", 0); } else { override = "atom"; return "block"; } } if (override == "tag") { // tag is a css value if (/embed|menu|pre|progress|sub|table/.test(word)) { if (wordIsProperty(firstWordOfLine(stream))) { override = "atom"; return "block"; } } // tag is an attribute if (stream.string.match(new RegExp("\\[\\s*" + word + "|" + word +"\\s*\\]"))) { override = "atom"; return "block"; } // tag is a variable if (tagVariablesRegexp.test(word)) { if ((startOfLine(stream) && stream.string.match(/=/)) || (!startOfLine(stream) && !stream.string.match(/^(\s*\.|#|\&|\[|\/|>|\*)/) && !wordIsTag(firstWordOfLine(stream)))) { override = "variable-2"; if (wordIsBlock(firstWordOfLine(stream))) return "block"; return pushContext(state, stream, "block", 0); } } if (endOfLine(stream)) return pushContext(state, stream, "block"); } if (override == "block-keyword") { override = "keyword"; // Postfix conditionals if (stream.current(/(if|unless)/) && !startOfLine(stream)) { return "block"; } return pushContext(state, stream, "block"); } if (word == "return") return pushContext(state, stream, "block", 0); // Placeholder selector if (override == "variable-2" && stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/)) { return pushContext(state, stream, "block"); } } return state.context.type; }; /** * Parens */ states.parens = function(type, stream, state) { if (type == "(") return pushContext(state, stream, "parens"); if (type == ")") { if (state.context.prev.type == "parens") { return popContext(state); } if ((stream.string.match(/^[a-z][\w-]*\(/i) && endOfLine(stream)) || wordIsBlock(firstWordOfLine(stream)) || /(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(firstWordOfLine(stream)) || (!stream.string.match(/^-?[a-z][\w-\.\[\]\'\"]*\s*=/) && wordIsTag(firstWordOfLine(stream)))) { return pushContext(state, stream, "block"); } if (stream.string.match(/^[\$-]?[a-z][\w-\.\[\]\'\"]*\s*=/) || stream.string.match(/^\s*(\(|\)|[0-9])/) || stream.string.match(/^\s+[a-z][\w-]*\(/i) || stream.string.match(/^\s+[\$-]?[a-z]/i)) { return pushContext(state, stream, "block", 0); } if (endOfLine(stream)) return pushContext(state, stream, "block"); else return pushContext(state, stream, "block", 0); } if (type && type.charAt(0) == "@" && wordIsProperty(stream.current().slice(1))) { override = "variable-2"; } if (type == "word") { var word = stream.current(); override = wordAsValue(word); if (override == "tag" && tagVariablesRegexp.test(word)) { override = "variable-2"; } if (override == "property" || word == "to") override = "atom"; } if (type == "variable-name") { return pushContext(state, stream, "variableName"); } if (typeIsPseudo(type, stream)) { return pushContext(state, stream, "pseudo"); } return state.context.type; }; /** * Vendor prefixes */ states.vendorPrefixes = function(type, stream, state) { if (type == "word") { override = "property"; return pushContext(state, stream, "block", 0); } return popContext(state); }; /** * Pseudo */ states.pseudo = function(type, stream, state) { if (!wordIsProperty(firstWordOfLine(stream.string))) { stream.match(/^[a-z-]+/); override = "variable-3"; if (endOfLine(stream)) return pushContext(state, stream, "block"); return popContext(state); } return popAndPass(type, stream, state); }; /** * atBlock */ states.atBlock = function(type, stream, state) { if (type == "(") return pushContext(state, stream, "atBlock_parens"); if (typeIsBlock(type, stream)) { return pushContext(state, stream, "block"); } if (typeIsInterpolation(type, stream)) { return pushContext(state, stream, "interpolation"); } if (type == "word") { var word = stream.current().toLowerCase(); if (/^(only|not|and|or)$/.test(word)) override = "keyword"; else if (documentTypes.hasOwnProperty(word)) override = "tag"; else if (mediaTypes.hasOwnProperty(word)) override = "attribute"; else if (mediaFeatures.hasOwnProperty(word)) override = "property"; else if (nonStandardPropertyKeywords.hasOwnProperty(word)) override = "string-2"; else override = wordAsValue(stream.current()); if (override == "tag" && endOfLine(stream)) { return pushContext(state, stream, "block"); } } if (type == "operator" && /^(not|and|or)$/.test(stream.current())) { override = "keyword"; } return state.context.type; }; states.atBlock_parens = function(type, stream, state) { if (type == "{" || type == "}") return state.context.type; if (type == ")") { if (endOfLine(stream)) return pushContext(state, stream, "block"); else return pushContext(state, stream, "atBlock"); } if (type == "word") { var word = stream.current().toLowerCase(); override = wordAsValue(word); if (/^(max|min)/.test(word)) override = "property"; if (override == "tag") { tagVariablesRegexp.test(word) ? override = "variable-2" : override = "atom"; } return state.context.type; } return states.atBlock(type, stream, state); }; /** * Keyframes */ states.keyframes = function(type, stream, state) { if (stream.indentation() == "0" && ((type == "}" && startOfLine(stream)) || type == "]" || type == "hash" || type == "qualifier" || wordIsTag(stream.current()))) { return popAndPass(type, stream, state); } if (type == "{") return pushContext(state, stream, "keyframes"); if (type == "}") { if (startOfLine(stream)) return popContext(state, true); else return pushContext(state, stream, "keyframes"); } if (type == "unit" && /^[0-9]+\%$/.test(stream.current())) { return pushContext(state, stream, "keyframes"); } if (type == "word") { override = wordAsValue(stream.current()); if (override == "block-keyword") { override = "keyword"; return pushContext(state, stream, "keyframes"); } } if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) { return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock"); } if (type == "mixin") { return pushContext(state, stream, "block", 0); } return state.context.type; }; /** * Interpolation */ states.interpolation = function(type, stream, state) { if (type == "{") popContext(state) && pushContext(state, stream, "block"); if (type == "}") { if (stream.string.match(/^\s*(\.|#|:|\[|\*|&|>|~|\+|\/)/i) || (stream.string.match(/^\s*[a-z]/i) && wordIsTag(firstWordOfLine(stream)))) { return pushContext(state, stream, "block"); } if (!stream.string.match(/^(\{|\s*\&)/) || stream.match(/\s*[\w-]/,false)) { return pushContext(state, stream, "block", 0); } return pushContext(state, stream, "block"); } if (type == "variable-name") { return pushContext(state, stream, "variableName", 0); } if (type == "word") { override = wordAsValue(stream.current()); if (override == "tag") override = "atom"; } return state.context.type; }; /** * Extend/s */ states.extend = function(type, stream, state) { if (type == "[" || type == "=") return "extend"; if (type == "]") return popContext(state); if (type == "word") { override = wordAsValue(stream.current()); return "extend"; } return popContext(state); }; /** * Variable name */ states.variableName = function(type, stream, state) { if (type == "string" || type == "[" || type == "]" || stream.current().match(/^(\.|\$)/)) { if (stream.current().match(/^\.[\w-]+/i)) override = "variable-2"; return "variableName"; } return popAndPass(type, stream, state); }; return { startState: function(base) { return { tokenize: null, state: "block", context: new Context("block", base || 0, null) }; }, token: function(stream, state) { if (!state.tokenize && stream.eatSpace()) return null; style = (state.tokenize || tokenBase)(stream, state); if (style && typeof style == "object") { type = style[1]; style = style[0]; } override = style; state.state = states[state.state](type, stream, state); return override; }, indent: function(state, textAfter, line) { var cx = state.context, ch = textAfter && textAfter.charAt(0), indent = cx.indent, lineFirstWord = firstWordOfLine(textAfter), lineIndent = line.match(/^\s*/)[0].replace(/\t/g, indentUnitString).length, prevLineFirstWord = state.context.prev ? state.context.prev.line.firstWord : "", prevLineIndent = state.context.prev ? state.context.prev.line.indent : lineIndent; if (cx.prev && (ch == "}" && (cx.type == "block" || cx.type == "atBlock" || cx.type == "keyframes") || ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") || ch == "{" && (cx.type == "at"))) { indent = cx.indent - indentUnit; } else if (!(/(\})/.test(ch))) { if (/@|\$|\d/.test(ch) || /^\{/.test(textAfter) || /^\s*\/(\/|\*)/.test(textAfter) || /^\s*\/\*/.test(prevLineFirstWord) || /^\s*[\w-\.\[\]\'\"]+\s*(\?|:|\+)?=/i.test(textAfter) || /^(\+|-)?[a-z][\w-]*\(/i.test(textAfter) || /^return/.test(textAfter) || wordIsBlock(lineFirstWord)) { indent = lineIndent; } else if (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(ch) || wordIsTag(lineFirstWord)) { if (/\,\s*$/.test(prevLineFirstWord)) { indent = prevLineIndent; } else if (/^\s+/.test(line) && (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord))) { indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit; } else { indent = lineIndent; } } else if (!/,\s*$/.test(line) && (wordIsVendorPrefix(lineFirstWord) || wordIsProperty(lineFirstWord))) { if (wordIsBlock(prevLineFirstWord)) { indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit; } else if (/^\{/.test(prevLineFirstWord)) { indent = lineIndent <= prevLineIndent ? lineIndent : prevLineIndent + indentUnit; } else if (wordIsVendorPrefix(prevLineFirstWord) || wordIsProperty(prevLineFirstWord)) { indent = lineIndent >= prevLineIndent ? prevLineIndent : lineIndent; } else if (/^(\.|#|:|\[|\*|&|@|\+|\-|>|~|\/)/.test(prevLineFirstWord) || /=\s*$/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord) || /^\$[\w-\.\[\]\'\"]/.test(prevLineFirstWord)) { indent = prevLineIndent + indentUnit; } else { indent = lineIndent; } } } return indent; }, electricChars: "}", lineComment: "//", fold: "indent" }; }); // developer.mozilla.org/en-US/docs/Web/HTML/Element 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"]; // github.com/codemirror/CodeMirror/blob/master/mode/css/css.js var documentTypes_ = ["domain", "regexp", "url", "url-prefix"]; var mediaTypes_ = ["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"]; 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"]; 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"]; 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"]; var fontProperties_ = ["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]; 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"]; 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"]; var wordOperatorKeywords_ = ["in","and","or","not","is not","is a","is","isnt","defined","if unless"], blockKeywords_ = ["for","if","else","unless", "from", "to"], commonAtoms_ = ["null","true","false","href","title","type","not-allowed","readonly","disabled"], commonDef_ = ["@font-face", "@keyframes", "@media", "@viewport", "@page", "@host", "@supports", "@block", "@css"]; var hintWords = tagKeywords_.concat(documentTypes_,mediaTypes_,mediaFeatures_, propertyKeywords_,nonStandardPropertyKeywords_, colorKeywords_,valueKeywords_,fontProperties_, wordOperatorKeywords_,blockKeywords_, commonAtoms_,commonDef_); function wordRegexp(words) { words = words.sort(function(a,b){return b > a;}); return new RegExp("^((" + words.join(")|(") + "))\\b"); } function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) keys[array[i]] = true; return keys; } function escapeRegExp(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); } CodeMirror.registerHelper("hintWords", "stylus", hintWords); CodeMirror.defineMIME("text/x-styl", "stylus"); }); ================================================ FILE: third_party/CodeMirror/mode/swift/index.html ================================================ CodeMirror: Swift mode

Swift mode

A simple mode for Swift

MIME types defined: text/x-swift (Swift code)

================================================ FILE: third_party/CodeMirror/mode/swift/swift.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Swift mode created by Michael Kaminsky https://github.com/mkaminsky11 (function(mod) { if (typeof exports == "object" && typeof module == "object") mod(require("../../lib/codemirror")) else if (typeof define == "function" && define.amd) define(["../../lib/codemirror"], mod) else mod(CodeMirror) })(function(CodeMirror) { "use strict" function wordSet(words) { var set = {} for (var i = 0; i < words.length; i++) set[words[i]] = true return set } var keywords = wordSet(["_","var","let","class","enum","extension","import","protocol","struct","func","typealias","associatedtype", "open","public","internal","fileprivate","private","deinit","init","new","override","self","subscript","super", "convenience","dynamic","final","indirect","lazy","required","static","unowned","unowned(safe)","unowned(unsafe)","weak","as","is", "break","case","continue","default","else","fallthrough","for","guard","if","in","repeat","switch","where","while", "defer","return","inout","mutating","nonmutating","catch","do","rethrows","throw","throws","try","didSet","get","set","willSet", "assignment","associativity","infix","left","none","operator","postfix","precedence","precedencegroup","prefix","right", "Any","AnyObject","Type","dynamicType","Self","Protocol","__COLUMN__","__FILE__","__FUNCTION__","__LINE__"]) var definingKeywords = wordSet(["var","let","class","enum","extension","import","protocol","struct","func","typealias","associatedtype","for"]) var atoms = wordSet(["true","false","nil","self","super","_"]) var types = wordSet(["Array","Bool","Character","Dictionary","Double","Float","Int","Int8","Int16","Int32","Int64","Never","Optional","Set","String", "UInt8","UInt16","UInt32","UInt64","Void"]) var operators = "+-/*%=|&<>~^?!" var punc = ":;,.(){}[]" var binary = /^\-?0b[01][01_]*/ var octal = /^\-?0o[0-7][0-7_]*/ var hexadecimal = /^\-?0x[\dA-Fa-f][\dA-Fa-f_]*(?:(?:\.[\dA-Fa-f][\dA-Fa-f_]*)?[Pp]\-?\d[\d_]*)?/ var decimal = /^\-?\d[\d_]*(?:\.\d[\d_]*)?(?:[Ee]\-?\d[\d_]*)?/ var identifier = /^\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1/ var property = /^\.(?:\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1)/ var instruction = /^\#[A-Za-z]+/ var attribute = /^@(?:\$\d+|(`?)[_A-Za-z][_A-Za-z$0-9]*\1)/ //var regexp = /^\/(?!\s)(?:\/\/)?(?:\\.|[^\/])+\// function tokenBase(stream, state, prev) { if (stream.sol()) state.indented = stream.indentation() if (stream.eatSpace()) return null var ch = stream.peek() if (ch == "/") { if (stream.match("//")) { stream.skipToEnd() return "comment" } if (stream.match("/*")) { state.tokenize.push(tokenComment) return tokenComment(stream, state) } } if (stream.match(instruction)) return "builtin" if (stream.match(attribute)) return "attribute" if (stream.match(binary)) return "number" if (stream.match(octal)) return "number" if (stream.match(hexadecimal)) return "number" if (stream.match(decimal)) return "number" if (stream.match(property)) return "property" if (operators.indexOf(ch) > -1) { stream.next() return "operator" } if (punc.indexOf(ch) > -1) { stream.next() stream.match("..") return "punctuation" } if (ch = stream.match(/("{3}|"|')/)) { var tokenize = tokenString(ch[0]) state.tokenize.push(tokenize) return tokenize(stream, state) } if (stream.match(identifier)) { var ident = stream.current() if (types.hasOwnProperty(ident)) return "variable-2" if (atoms.hasOwnProperty(ident)) return "atom" if (keywords.hasOwnProperty(ident)) { if (definingKeywords.hasOwnProperty(ident)) state.prev = "define" return "keyword" } if (prev == "define") return "def" return "variable" } stream.next() return null } function tokenUntilClosingParen() { var depth = 0 return function(stream, state, prev) { var inner = tokenBase(stream, state, prev) if (inner == "punctuation") { if (stream.current() == "(") ++depth else if (stream.current() == ")") { if (depth == 0) { stream.backUp(1) state.tokenize.pop() return state.tokenize[state.tokenize.length - 1](stream, state) } else --depth } } return inner } } function tokenString(quote) { var singleLine = quote.length == 1 return function(stream, state) { var ch, escaped = false while (ch = stream.next()) { if (escaped) { if (ch == "(") { state.tokenize.push(tokenUntilClosingParen()) return "string" } escaped = false } else if (stream.match(quote)) { state.tokenize.pop() return "string" } else { escaped = ch == "\\" } } if (singleLine) { state.tokenize.pop() } return "string" } } function tokenComment(stream, state) { var ch while (true) { stream.match(/^[^/*]+/, true) ch = stream.next() if (!ch) break if (ch === "/" && stream.eat("*")) { state.tokenize.push(tokenComment) } else if (ch === "*" && stream.eat("/")) { state.tokenize.pop() } } return "comment" } function Context(prev, align, indented) { this.prev = prev this.align = align this.indented = indented } function pushContext(state, stream) { var align = stream.match(/^\s*($|\/[\/\*])/, false) ? null : stream.column() + 1 state.context = new Context(state.context, align, state.indented) } function popContext(state) { if (state.context) { state.indented = state.context.indented state.context = state.context.prev } } CodeMirror.defineMode("swift", function(config) { return { startState: function() { return { prev: null, context: null, indented: 0, tokenize: [] } }, token: function(stream, state) { var prev = state.prev state.prev = null var tokenize = state.tokenize[state.tokenize.length - 1] || tokenBase var style = tokenize(stream, state, prev) if (!style || style == "comment") state.prev = prev else if (!state.prev) state.prev = style if (style == "punctuation") { var bracket = /[\(\[\{]|([\]\)\}])/.exec(stream.current()) if (bracket) (bracket[1] ? popContext : pushContext)(state, stream) } return style }, indent: function(state, textAfter) { var cx = state.context if (!cx) return 0 var closing = /^[\]\}\)]/.test(textAfter) if (cx.align != null) return cx.align - (closing ? 1 : 0) return cx.indented + (closing ? 0 : config.indentUnit) }, electricInput: /^\s*[\)\}\]]$/, lineComment: "//", blockCommentStart: "/*", blockCommentEnd: "*/", fold: "brace", closeBrackets: "()[]{}''\"\"``" } }) CodeMirror.defineMIME("text/x-swift","swift") }); ================================================ FILE: third_party/CodeMirror/mode/swift/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "swift"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } // Ensure all number types are properly represented. MT("numbers", "[keyword var] [def a] [operator =] [number 17]", "[keyword var] [def b] [operator =] [number -0.5]", "[keyword var] [def c] [operator =] [number 0.3456e-4]", "[keyword var] [def d] [operator =] [number 345e2]", "[keyword var] [def e] [operator =] [number 0o7324]", "[keyword var] [def f] [operator =] [number 0b10010]", "[keyword var] [def g] [operator =] [number -0x35ade]", "[keyword var] [def h] [operator =] [number 0xaea.ep-13]", "[keyword var] [def i] [operator =] [number 0x13ep6]"); // Variable/class/etc definition. MT("definition", "[keyword var] [def a] [operator =] [number 5]", "[keyword let] [def b][punctuation :] [variable-2 Int] [operator =] [number 10]", "[keyword class] [def C] [punctuation {] [punctuation }]", "[keyword struct] [def D] [punctuation {] [punctuation }]", "[keyword enum] [def E] [punctuation {] [punctuation }]", "[keyword extension] [def F] [punctuation {] [punctuation }]", "[keyword protocol] [def G] [punctuation {] [punctuation }]", "[keyword func] [def h][punctuation ()] [punctuation {] [punctuation }]", "[keyword import] [def Foundation]", "[keyword typealias] [def NewString] [operator =] [variable-2 String]", "[keyword associatedtype] [def I]", "[keyword for] [def j] [keyword in] [number 0][punctuation ..][operator <][number 3] [punctuation {] [punctuation }]"); // Strings and string interpolation. MT("strings", "[keyword var] [def a][punctuation :] [variable-2 String] [operator =] [string \"test\"]", "[keyword var] [def b][punctuation :] [variable-2 String] [operator =] [string \"\\(][variable a][string )\"]", "[keyword var] [def c] [operator =] [string \"\"\"]", "[string multi]", "[string line]", "[string \"test\"]", "[string \"\"\"]"); // Comments. MT("comments", "[comment // This is a comment]", "[comment /* This is another comment */]", "[keyword var] [def a] [operator =] [number 5] [comment // Third comment]"); // Atoms. MT("atoms", "[keyword class] [def FooClass] [punctuation {]", " [keyword let] [def fooBool][punctuation :] [variable-2 Bool][operator ?]", " [keyword let] [def fooInt][punctuation :] [variable-2 Int][operator ?]", " [keyword func] [keyword init][punctuation (][variable fooBool][punctuation :] [variable-2 Bool][punctuation ,] [variable barBool][punctuation :] [variable-2 Bool][punctuation )] [punctuation {]", " [atom super][property .init][punctuation ()]", " [atom self][property .fooBool] [operator =] [variable fooBool]", " [variable fooInt] [operator =] [atom nil]", " [keyword if] [variable barBool] [operator ==] [atom true] [punctuation {]", " [variable print][punctuation (][string \"True!\"][punctuation )]", " [punctuation }] [keyword else] [keyword if] [variable barBool] [operator ==] [atom false] [punctuation {]", " [keyword for] [atom _] [keyword in] [number 0][punctuation ...][number 5] [punctuation {]", " [variable print][punctuation (][string \"False!\"][punctuation )]", " [punctuation }]", " [punctuation }]", " [punctuation }]", "[punctuation }]"); // Types. MT("types", "[keyword var] [def a] [operator =] [variable-2 Array][operator <][variable-2 Int][operator >]", "[keyword var] [def b] [operator =] [variable-2 Set][operator <][variable-2 Bool][operator >]", "[keyword var] [def c] [operator =] [variable-2 Dictionary][operator <][variable-2 String][punctuation ,][variable-2 Character][operator >]", "[keyword var] [def d][punctuation :] [variable-2 Int64][operator ?] [operator =] [variable-2 Optional][punctuation (][number 8][punctuation )]", "[keyword func] [def e][punctuation ()] [operator ->] [variable-2 Void] [punctuation {]", " [keyword var] [def e1][punctuation :] [variable-2 Float] [operator =] [number 1.2]", "[punctuation }]", "[keyword func] [def f][punctuation ()] [operator ->] [variable-2 Never] [punctuation {]", " [keyword var] [def f1][punctuation :] [variable-2 Double] [operator =] [number 2.4]", "[punctuation }]"); // Operators. MT("operators", "[keyword var] [def a] [operator =] [number 1] [operator +] [number 2]", "[keyword var] [def b] [operator =] [number 1] [operator -] [number 2]", "[keyword var] [def c] [operator =] [number 1] [operator *] [number 2]", "[keyword var] [def d] [operator =] [number 1] [operator /] [number 2]", "[keyword var] [def e] [operator =] [number 1] [operator %] [number 2]", "[keyword var] [def f] [operator =] [number 1] [operator |] [number 2]", "[keyword var] [def g] [operator =] [number 1] [operator &] [number 2]", "[keyword var] [def h] [operator =] [number 1] [operator <<] [number 2]", "[keyword var] [def i] [operator =] [number 1] [operator >>] [number 2]", "[keyword var] [def j] [operator =] [number 1] [operator ^] [number 2]", "[keyword var] [def k] [operator =] [operator ~][number 1]", "[keyword var] [def l] [operator =] [variable foo] [operator ?] [number 1] [punctuation :] [number 2]", "[keyword var] [def m][punctuation :] [variable-2 Int] [operator =] [variable-2 Optional][punctuation (][number 8][punctuation )][operator !]"); // Punctuation. MT("punctuation", "[keyword let] [def a] [operator =] [number 1][punctuation ;] [keyword let] [def b] [operator =] [number 2]", "[keyword let] [def testArr][punctuation :] [punctuation [[][variable-2 Int][punctuation ]]] [operator =] [punctuation [[][variable a][punctuation ,] [variable b][punctuation ]]]", "[keyword for] [def i] [keyword in] [number 0][punctuation ..][operator <][variable testArr][property .count] [punctuation {]", " [variable print][punctuation (][variable testArr][punctuation [[][variable i][punctuation ]])]", "[punctuation }]"); // Identifiers. MT("identifiers", "[keyword let] [def abc] [operator =] [number 1]", "[keyword let] [def ABC] [operator =] [number 2]", "[keyword let] [def _123] [operator =] [number 3]", "[keyword let] [def _$1$2$3] [operator =] [number 4]", "[keyword let] [def A1$_c32_$_] [operator =] [number 5]", "[keyword let] [def `var`] [operator =] [punctuation [[][number 1][punctuation ,] [number 2][punctuation ,] [number 3][punctuation ]]]", "[keyword let] [def square$] [operator =] [variable `var`][property .map] [punctuation {][variable $0] [operator *] [variable $0][punctuation }]", "$$ [number 1][variable a] $[atom _] [variable _$] [variable __] `[variable a] [variable b]`"); // Properties. MT("properties", "[variable print][punctuation (][variable foo][property .abc][punctuation )]", "[variable print][punctuation (][variable foo][property .ABC][punctuation )]", "[variable print][punctuation (][variable foo][property ._123][punctuation )]", "[variable print][punctuation (][variable foo][property ._$1$2$3][punctuation )]", "[variable print][punctuation (][variable foo][property .A1$_c32_$_][punctuation )]", "[variable print][punctuation (][variable foo][property .`var`][punctuation )]", "[variable print][punctuation (][variable foo][property .__][punctuation )]"); // Instructions or other things that start with #. MT("instructions", "[keyword if] [builtin #available][punctuation (][variable iOS] [number 9][punctuation ,] [operator *][punctuation )] [punctuation {}]", "[variable print][punctuation (][builtin #file][punctuation ,] [builtin #function][punctuation )]", "[variable print][punctuation (][builtin #line][punctuation ,] [builtin #column][punctuation )]", "[builtin #if] [atom true]", "[keyword import] [def A]", "[builtin #elseif] [atom false]", "[keyword import] [def B]", "[builtin #endif]", "[builtin #sourceLocation][punctuation (][variable file][punctuation :] [string \"file.swift\"][punctuation ,] [variable line][punctuation :] [number 2][punctuation )]"); // Attributes; things that start with @. MT("attributes", "[attribute @objc][punctuation (][variable objcFoo][punctuation :)]", "[attribute @available][punctuation (][variable iOS][punctuation )]"); // Property/number edge case. MT("property_number", "[variable print][punctuation (][variable foo][property ._123][punctuation )]", "[variable print][punctuation (]") MT("nested_comments", "[comment /*]", "[comment But wait /* this is a nested comment */ for real]", "[comment /**** let * me * show * you ****/]", "[comment ///// let / me / show / you /////]", "[comment */]"); // TODO: correctly identify when multiple variables are being declared // by use of a comma-separated list. // TODO: correctly identify when variables are being declared in a tuple. // TODO: identify protocols as types when used before an extension? })(); ================================================ FILE: third_party/CodeMirror/mode/tcl/index.html ================================================ CodeMirror: Tcl mode

Tcl mode

MIME types defined: text/x-tcl.

================================================ FILE: third_party/CodeMirror/mode/tcl/tcl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE //tcl mode by Ford_Lawnmower :: Based on Velocity mode by Steve O'Hara (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("tcl", function() { function parseWords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = parseWords("Tcl safe after append array auto_execok auto_import auto_load " + "auto_mkindex auto_mkindex_old auto_qualify auto_reset bgerror " + "binary break catch cd close concat continue dde eof encoding error " + "eval exec exit expr fblocked fconfigure fcopy file fileevent filename " + "filename flush for foreach format gets glob global history http if " + "incr info interp join lappend lindex linsert list llength load lrange " + "lreplace lsearch lset lsort memory msgcat namespace open package parray " + "pid pkg::create pkg_mkIndex proc puts pwd re_syntax read regex regexp " + "registry regsub rename resource return scan seek set socket source split " + "string subst switch tcl_endOfWord tcl_findLibrary tcl_startOfNextWord " + "tcl_wordBreakAfter tcl_startOfPreviousWord tcl_wordBreakBefore tcltest " + "tclvars tell time trace unknown unset update uplevel upvar variable " + "vwait"); var functions = parseWords("if elseif else and not or eq ne in ni for foreach while switch"); var isOperatorChar = /[+\-*&%=<>!?^\/\|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenBase(stream, state) { var beforeParams = state.beforeParams; state.beforeParams = false; var ch = stream.next(); if ((ch == '"' || ch == "'") && state.inParams) { return chain(stream, state, tokenString(ch)); } else if (/[\[\]{}\(\),;\.]/.test(ch)) { if (ch == "(" && beforeParams) state.inParams = true; else if (ch == ")") state.inParams = false; return null; } else if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } else if (ch == "#") { if (stream.eat("*")) return chain(stream, state, tokenComment); if (ch == "#" && stream.match(/ *\[ *\[/)) return chain(stream, state, tokenUnparsed); stream.skipToEnd(); return "comment"; } else if (ch == '"') { stream.skipTo(/"/); return "comment"; } else if (ch == "$") { stream.eatWhile(/[$_a-z0-9A-Z\.{:]/); stream.eatWhile(/}/); state.beforeParams = true; return "builtin"; } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "comment"; } else { stream.eatWhile(/[\w\$_{}\xa1-\uffff]/); var word = stream.current().toLowerCase(); if (keywords && keywords.propertyIsEnumerable(word)) return "keyword"; if (functions && functions.propertyIsEnumerable(word)) { state.beforeParams = true; return "keyword"; } return null; } } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) { end = true; break; } escaped = !escaped && next == "\\"; } if (end) state.tokenize = tokenBase; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenUnparsed(stream, state) { var maybeEnd = 0, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd == 2) { state.tokenize = tokenBase; break; } if (ch == "]") maybeEnd++; else if (ch != " ") maybeEnd = 0; } return "meta"; } return { startState: function() { return { tokenize: tokenBase, beforeParams: false, inParams: false }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); } }; }); CodeMirror.defineMIME("text/x-tcl", "tcl"); }); ================================================ FILE: third_party/CodeMirror/mode/textile/index.html ================================================ CodeMirror: Textile mode

Textile mode

MIME types defined: text/x-textile.

Parsing/Highlighting Tests: normal, verbose.

================================================ FILE: third_party/CodeMirror/mode/textile/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({tabSize: 4}, 'textile'); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT('simpleParagraphs', 'Some text.', '', 'Some more text.'); /* * Phrase Modifiers */ MT('em', 'foo [em _bar_]'); MT('emBoogus', 'code_mirror'); MT('strong', 'foo [strong *bar*]'); MT('strongBogus', '3 * 3 = 9'); MT('italic', 'foo [em __bar__]'); MT('italicBogus', 'code__mirror'); MT('bold', 'foo [strong **bar**]'); MT('boldBogus', '3 ** 3 = 27'); MT('simpleLink', '[link "CodeMirror":https://codemirror.net]'); MT('referenceLink', '[link "CodeMirror":code_mirror]', 'Normal Text.', '[link [[code_mirror]]https://codemirror.net]'); MT('footCite', 'foo bar[qualifier [[1]]]'); MT('footCiteBogus', 'foo bar[[1a2]]'); MT('special-characters', 'Registered [tag (r)], ' + 'Trademark [tag (tm)], and ' + 'Copyright [tag (c)] 2008'); MT('cite', "A book is [keyword ??The Count of Monte Cristo??] by Dumas."); MT('additionAndDeletion', 'The news networks declared [negative -Al Gore-] ' + '[positive +George W. Bush+] the winner in Florida.'); MT('subAndSup', 'f(x, n) = log [builtin ~4~] x [builtin ^n^]'); MT('spanAndCode', 'A [quote %span element%] and [atom @code element@]'); MT('spanBogus', 'Percentage 25% is not a span.'); MT('citeBogus', 'Question? is not a citation.'); MT('codeBogus', 'user@example.com'); MT('subBogus', '~username'); MT('supBogus', 'foo ^ bar'); MT('deletionBogus', '3 - 3 = 0'); MT('additionBogus', '3 + 3 = 6'); MT('image', 'An image: [string !http://www.example.com/image.png!]'); MT('imageWithAltText', 'An image: [string !http://www.example.com/image.png (Alt Text)!]'); MT('imageWithUrl', 'An image: [string !http://www.example.com/image.png!:http://www.example.com/]'); /* * Headers */ MT('h1', '[header&header-1 h1. foo]'); MT('h2', '[header&header-2 h2. foo]'); MT('h3', '[header&header-3 h3. foo]'); MT('h4', '[header&header-4 h4. foo]'); MT('h5', '[header&header-5 h5. foo]'); MT('h6', '[header&header-6 h6. foo]'); MT('h7Bogus', 'h7. foo'); MT('multipleHeaders', '[header&header-1 h1. Heading 1]', '', 'Some text.', '', '[header&header-2 h2. Heading 2]', '', 'More text.'); MT('h1inline', '[header&header-1 h1. foo ][header&header-1&em _bar_][header&header-1 baz]'); /* * Lists */ MT('ul', 'foo', 'bar', '', '[variable-2 * foo]', '[variable-2 * bar]'); MT('ulNoBlank', 'foo', 'bar', '[variable-2 * foo]', '[variable-2 * bar]'); MT('ol', 'foo', 'bar', '', '[variable-2 # foo]', '[variable-2 # bar]'); MT('olNoBlank', 'foo', 'bar', '[variable-2 # foo]', '[variable-2 # bar]'); MT('ulFormatting', '[variable-2 * ][variable-2&em _foo_][variable-2 bar]', '[variable-2 * ][variable-2&strong *][variable-2&em&strong _foo_]' + '[variable-2&strong *][variable-2 bar]', '[variable-2 * ][variable-2&strong *foo*][variable-2 bar]'); MT('olFormatting', '[variable-2 # ][variable-2&em _foo_][variable-2 bar]', '[variable-2 # ][variable-2&strong *][variable-2&em&strong _foo_]' + '[variable-2&strong *][variable-2 bar]', '[variable-2 # ][variable-2&strong *foo*][variable-2 bar]'); MT('ulNested', '[variable-2 * foo]', '[variable-3 ** bar]', '[keyword *** bar]', '[variable-2 **** bar]', '[variable-3 ** bar]'); MT('olNested', '[variable-2 # foo]', '[variable-3 ## bar]', '[keyword ### bar]', '[variable-2 #### bar]', '[variable-3 ## bar]'); MT('ulNestedWithOl', '[variable-2 * foo]', '[variable-3 ## bar]', '[keyword *** bar]', '[variable-2 #### bar]', '[variable-3 ** bar]'); MT('olNestedWithUl', '[variable-2 # foo]', '[variable-3 ** bar]', '[keyword ### bar]', '[variable-2 **** bar]', '[variable-3 ## bar]'); MT('definitionList', '[number - coffee := Hot ][number&em _and_][number black]', '', 'Normal text.'); MT('definitionListSpan', '[number - coffee :=]', '', '[number Hot ][number&em _and_][number black =:]', '', 'Normal text.'); MT('boo', '[number - dog := woof woof]', '[number - cat := meow meow]', '[number - whale :=]', '[number Whale noises.]', '', '[number Also, ][number&em _splashing_][number . =:]'); /* * Attributes */ MT('divWithAttribute', '[punctuation div][punctuation&attribute (#my-id)][punctuation . foo bar]'); MT('divWithAttributeAnd2emRightPadding', '[punctuation div][punctuation&attribute (#my-id)((][punctuation . foo bar]'); MT('divWithClassAndId', '[punctuation div][punctuation&attribute (my-class#my-id)][punctuation . foo bar]'); MT('paragraphWithCss', 'p[attribute {color:red;}]. foo bar'); MT('paragraphNestedStyles', 'p. [strong *foo ][strong&em _bar_][strong *]'); MT('paragraphWithLanguage', 'p[attribute [[fr]]]. Parlez-vous français?'); MT('paragraphLeftAlign', 'p[attribute <]. Left'); MT('paragraphRightAlign', 'p[attribute >]. Right'); MT('paragraphRightAlign', 'p[attribute =]. Center'); MT('paragraphJustified', 'p[attribute <>]. Justified'); MT('paragraphWithLeftIndent1em', 'p[attribute (]. Left'); MT('paragraphWithRightIndent1em', 'p[attribute )]. Right'); MT('paragraphWithLeftIndent2em', 'p[attribute ((]. Left'); MT('paragraphWithRightIndent2em', 'p[attribute ))]. Right'); MT('paragraphWithLeftIndent3emRightIndent2em', 'p[attribute ((())]. Right'); MT('divFormatting', '[punctuation div. ][punctuation&strong *foo ]' + '[punctuation&strong&em _bar_][punctuation&strong *]'); MT('phraseModifierAttributes', 'p[attribute (my-class)]. This is a paragraph that has a class and' + ' this [em _][em&attribute (#special-phrase)][em emphasized phrase_]' + ' has an id.'); MT('linkWithClass', '[link "(my-class). This is a link with class":http://redcloth.org]'); /* * Layouts */ MT('paragraphLayouts', 'p. This is one paragraph.', '', 'p. This is another.'); MT('div', '[punctuation div. foo bar]'); MT('pre', '[operator pre. Text]'); MT('bq.', '[bracket bq. foo bar]', '', 'Normal text.'); MT('footnote', '[variable fn123. foo ][variable&strong *bar*]'); /* * Spanning Layouts */ MT('bq..ThenParagraph', '[bracket bq.. foo bar]', '', '[bracket More quote.]', 'p. Normal Text'); MT('bq..ThenH1', '[bracket bq.. foo bar]', '', '[bracket More quote.]', '[header&header-1 h1. Header Text]'); MT('bc..ThenParagraph', '[atom bc.. # Some ruby code]', '[atom obj = {foo: :bar}]', '[atom puts obj]', '', '[atom obj[[:love]] = "*love*"]', '[atom puts obj.love.upcase]', '', 'p. Normal text.'); MT('fn1..ThenParagraph', '[variable fn1.. foo bar]', '', '[variable More.]', 'p. Normal Text'); MT('pre..ThenParagraph', '[operator pre.. foo bar]', '', '[operator More.]', 'p. Normal Text'); /* * Tables */ MT('table', '[variable-3&operator |_. name |_. age|]', '[variable-3 |][variable-3&strong *Walter*][variable-3 | 5 |]', '[variable-3 |Florence| 6 |]', '', 'p. Normal text.'); MT('tableWithAttributes', '[variable-3&operator |_. name |_. age|]', '[variable-3 |][variable-3&attribute /2.][variable-3 Jim |]', '[variable-3 |][variable-3&attribute \\2{color: red}.][variable-3 Sam |]'); /* * HTML */ MT('html', '[comment
]', '[comment
]', '', '[header&header-1 h1. Welcome]', '', '[variable-2 * Item one]', '[variable-2 * Item two]', '', '[comment Example]', '', '[comment
]', '[comment
]'); MT('inlineHtml', 'I can use HTML directly in my [comment Textile].'); /* * No-Textile */ MT('notextile', '[string-2 notextile. *No* formatting]'); MT('notextileInline', 'Use [string-2 ==*asterisks*==] for [strong *strong*] text.'); MT('notextileWithPre', '[operator pre. *No* formatting]'); MT('notextileWithSpanningPre', '[operator pre.. *No* formatting]', '', '[operator *No* formatting]'); /* Only toggling phrases between non-word chars. */ MT('phrase-in-word', 'foo_bar_baz'); MT('phrase-non-word', '[negative -x-] aaa-bbb ccc-ddd [negative -eee-] fff [negative -ggg-]'); MT('phrase-lone-dash', 'foo - bar - baz'); })(); ================================================ FILE: third_party/CodeMirror/mode/textile/textile.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") { // CommonJS mod(require("../../lib/codemirror")); } else if (typeof define == "function" && define.amd) { // AMD define(["../../lib/codemirror"], mod); } else { // Plain browser env mod(CodeMirror); } })(function(CodeMirror) { "use strict"; var TOKEN_STYLES = { addition: "positive", attributes: "attribute", bold: "strong", cite: "keyword", code: "atom", definitionList: "number", deletion: "negative", div: "punctuation", em: "em", footnote: "variable", footCite: "qualifier", header: "header", html: "comment", image: "string", italic: "em", link: "link", linkDefinition: "link", list1: "variable-2", list2: "variable-3", list3: "keyword", notextile: "string-2", pre: "operator", p: "property", quote: "bracket", span: "quote", specialChar: "tag", strong: "strong", sub: "builtin", sup: "builtin", table: "variable-3", tableHeading: "operator" }; function startNewLine(stream, state) { state.mode = Modes.newLayout; state.tableHeading = false; if (state.layoutType === "definitionList" && state.spanningLayout && stream.match(RE("definitionListEnd"), false)) state.spanningLayout = false; } function handlePhraseModifier(stream, state, ch) { if (ch === "_") { if (stream.eat("_")) return togglePhraseModifier(stream, state, "italic", /__/, 2); else return togglePhraseModifier(stream, state, "em", /_/, 1); } if (ch === "*") { if (stream.eat("*")) { return togglePhraseModifier(stream, state, "bold", /\*\*/, 2); } return togglePhraseModifier(stream, state, "strong", /\*/, 1); } if (ch === "[") { if (stream.match(/\d+\]/)) state.footCite = true; return tokenStyles(state); } if (ch === "(") { var spec = stream.match(/^(r|tm|c)\)/); if (spec) return tokenStylesWith(state, TOKEN_STYLES.specialChar); } if (ch === "<" && stream.match(/(\w+)[^>]+>[^<]+<\/\1>/)) return tokenStylesWith(state, TOKEN_STYLES.html); if (ch === "?" && stream.eat("?")) return togglePhraseModifier(stream, state, "cite", /\?\?/, 2); if (ch === "=" && stream.eat("=")) return togglePhraseModifier(stream, state, "notextile", /==/, 2); if (ch === "-" && !stream.eat("-")) return togglePhraseModifier(stream, state, "deletion", /-/, 1); if (ch === "+") return togglePhraseModifier(stream, state, "addition", /\+/, 1); if (ch === "~") return togglePhraseModifier(stream, state, "sub", /~/, 1); if (ch === "^") return togglePhraseModifier(stream, state, "sup", /\^/, 1); if (ch === "%") return togglePhraseModifier(stream, state, "span", /%/, 1); if (ch === "@") return togglePhraseModifier(stream, state, "code", /@/, 1); if (ch === "!") { var type = togglePhraseModifier(stream, state, "image", /(?:\([^\)]+\))?!/, 1); stream.match(/^:\S+/); // optional Url portion return type; } return tokenStyles(state); } function togglePhraseModifier(stream, state, phraseModifier, closeRE, openSize) { var charBefore = stream.pos > openSize ? stream.string.charAt(stream.pos - openSize - 1) : null; var charAfter = stream.peek(); if (state[phraseModifier]) { if ((!charAfter || /\W/.test(charAfter)) && charBefore && /\S/.test(charBefore)) { var type = tokenStyles(state); state[phraseModifier] = false; return type; } } else if ((!charBefore || /\W/.test(charBefore)) && charAfter && /\S/.test(charAfter) && stream.match(new RegExp("^.*\\S" + closeRE.source + "(?:\\W|$)"), false)) { state[phraseModifier] = true; state.mode = Modes.attributes; } return tokenStyles(state); }; function tokenStyles(state) { var disabled = textileDisabled(state); if (disabled) return disabled; var styles = []; if (state.layoutType) styles.push(TOKEN_STYLES[state.layoutType]); styles = styles.concat(activeStyles( state, "addition", "bold", "cite", "code", "deletion", "em", "footCite", "image", "italic", "link", "span", "strong", "sub", "sup", "table", "tableHeading")); if (state.layoutType === "header") styles.push(TOKEN_STYLES.header + "-" + state.header); return styles.length ? styles.join(" ") : null; } function textileDisabled(state) { var type = state.layoutType; switch(type) { case "notextile": case "code": case "pre": return TOKEN_STYLES[type]; default: if (state.notextile) return TOKEN_STYLES.notextile + (type ? (" " + TOKEN_STYLES[type]) : ""); return null; } } function tokenStylesWith(state, extraStyles) { var disabled = textileDisabled(state); if (disabled) return disabled; var type = tokenStyles(state); if (extraStyles) return type ? (type + " " + extraStyles) : extraStyles; else return type; } function activeStyles(state) { var styles = []; for (var i = 1; i < arguments.length; ++i) { if (state[arguments[i]]) styles.push(TOKEN_STYLES[arguments[i]]); } return styles; } function blankLine(state) { var spanningLayout = state.spanningLayout, type = state.layoutType; for (var key in state) if (state.hasOwnProperty(key)) delete state[key]; state.mode = Modes.newLayout; if (spanningLayout) { state.layoutType = type; state.spanningLayout = true; } } var REs = { cache: {}, single: { bc: "bc", bq: "bq", definitionList: /- .*?:=+/, definitionListEnd: /.*=:\s*$/, div: "div", drawTable: /\|.*\|/, foot: /fn\d+/, header: /h[1-6]/, html: /\s*<(?:\/)?(\w+)(?:[^>]+)?>(?:[^<]+<\/\1>)?/, link: /[^"]+":\S/, linkDefinition: /\[[^\s\]]+\]\S+/, list: /(?:#+|\*+)/, notextile: "notextile", para: "p", pre: "pre", table: "table", tableCellAttributes: /[\/\\]\d+/, tableHeading: /\|_\./, tableText: /[^"_\*\[\(\?\+~\^%@|-]+/, text: /[^!"_=\*\[\(<\?\+~\^%@-]+/ }, attributes: { align: /(?:<>|<|>|=)/, selector: /\([^\(][^\)]+\)/, lang: /\[[^\[\]]+\]/, pad: /(?:\(+|\)+){1,2}/, css: /\{[^\}]+\}/ }, createRe: function(name) { switch (name) { case "drawTable": return REs.makeRe("^", REs.single.drawTable, "$"); case "html": return REs.makeRe("^", REs.single.html, "(?:", REs.single.html, ")*", "$"); case "linkDefinition": return REs.makeRe("^", REs.single.linkDefinition, "$"); case "listLayout": return REs.makeRe("^", REs.single.list, RE("allAttributes"), "*\\s+"); case "tableCellAttributes": return REs.makeRe("^", REs.choiceRe(REs.single.tableCellAttributes, RE("allAttributes")), "+\\."); case "type": return REs.makeRe("^", RE("allTypes")); case "typeLayout": return REs.makeRe("^", RE("allTypes"), RE("allAttributes"), "*\\.\\.?", "(\\s+|$)"); case "attributes": return REs.makeRe("^", RE("allAttributes"), "+"); case "allTypes": return REs.choiceRe(REs.single.div, REs.single.foot, REs.single.header, REs.single.bc, REs.single.bq, REs.single.notextile, REs.single.pre, REs.single.table, REs.single.para); case "allAttributes": return REs.choiceRe(REs.attributes.selector, REs.attributes.css, REs.attributes.lang, REs.attributes.align, REs.attributes.pad); default: return REs.makeRe("^", REs.single[name]); } }, makeRe: function() { var pattern = ""; for (var i = 0; i < arguments.length; ++i) { var arg = arguments[i]; pattern += (typeof arg === "string") ? arg : arg.source; } return new RegExp(pattern); }, choiceRe: function() { var parts = [arguments[0]]; for (var i = 1; i < arguments.length; ++i) { parts[i * 2 - 1] = "|"; parts[i * 2] = arguments[i]; } parts.unshift("(?:"); parts.push(")"); return REs.makeRe.apply(null, parts); } }; function RE(name) { return (REs.cache[name] || (REs.cache[name] = REs.createRe(name))); } var Modes = { newLayout: function(stream, state) { if (stream.match(RE("typeLayout"), false)) { state.spanningLayout = false; return (state.mode = Modes.blockType)(stream, state); } var newMode; if (!textileDisabled(state)) { if (stream.match(RE("listLayout"), false)) newMode = Modes.list; else if (stream.match(RE("drawTable"), false)) newMode = Modes.table; else if (stream.match(RE("linkDefinition"), false)) newMode = Modes.linkDefinition; else if (stream.match(RE("definitionList"))) newMode = Modes.definitionList; else if (stream.match(RE("html"), false)) newMode = Modes.html; } return (state.mode = (newMode || Modes.text))(stream, state); }, blockType: function(stream, state) { var match, type; state.layoutType = null; if (match = stream.match(RE("type"))) type = match[0]; else return (state.mode = Modes.text)(stream, state); if (match = type.match(RE("header"))) { state.layoutType = "header"; state.header = parseInt(match[0][1]); } else if (type.match(RE("bq"))) { state.layoutType = "quote"; } else if (type.match(RE("bc"))) { state.layoutType = "code"; } else if (type.match(RE("foot"))) { state.layoutType = "footnote"; } else if (type.match(RE("notextile"))) { state.layoutType = "notextile"; } else if (type.match(RE("pre"))) { state.layoutType = "pre"; } else if (type.match(RE("div"))) { state.layoutType = "div"; } else if (type.match(RE("table"))) { state.layoutType = "table"; } state.mode = Modes.attributes; return tokenStyles(state); }, text: function(stream, state) { if (stream.match(RE("text"))) return tokenStyles(state); var ch = stream.next(); if (ch === '"') return (state.mode = Modes.link)(stream, state); return handlePhraseModifier(stream, state, ch); }, attributes: function(stream, state) { state.mode = Modes.layoutLength; if (stream.match(RE("attributes"))) return tokenStylesWith(state, TOKEN_STYLES.attributes); else return tokenStyles(state); }, layoutLength: function(stream, state) { if (stream.eat(".") && stream.eat(".")) state.spanningLayout = true; state.mode = Modes.text; return tokenStyles(state); }, list: function(stream, state) { var match = stream.match(RE("list")); state.listDepth = match[0].length; var listMod = (state.listDepth - 1) % 3; if (!listMod) state.layoutType = "list1"; else if (listMod === 1) state.layoutType = "list2"; else state.layoutType = "list3"; state.mode = Modes.attributes; return tokenStyles(state); }, link: function(stream, state) { state.mode = Modes.text; if (stream.match(RE("link"))) { stream.match(/\S+/); return tokenStylesWith(state, TOKEN_STYLES.link); } return tokenStyles(state); }, linkDefinition: function(stream, state) { stream.skipToEnd(); return tokenStylesWith(state, TOKEN_STYLES.linkDefinition); }, definitionList: function(stream, state) { stream.match(RE("definitionList")); state.layoutType = "definitionList"; if (stream.match(/\s*$/)) state.spanningLayout = true; else state.mode = Modes.attributes; return tokenStyles(state); }, html: function(stream, state) { stream.skipToEnd(); return tokenStylesWith(state, TOKEN_STYLES.html); }, table: function(stream, state) { state.layoutType = "table"; return (state.mode = Modes.tableCell)(stream, state); }, tableCell: function(stream, state) { if (stream.match(RE("tableHeading"))) state.tableHeading = true; else stream.eat("|"); state.mode = Modes.tableCellAttributes; return tokenStyles(state); }, tableCellAttributes: function(stream, state) { state.mode = Modes.tableText; if (stream.match(RE("tableCellAttributes"))) return tokenStylesWith(state, TOKEN_STYLES.attributes); else return tokenStyles(state); }, tableText: function(stream, state) { if (stream.match(RE("tableText"))) return tokenStyles(state); if (stream.peek() === "|") { // end of cell state.mode = Modes.tableCell; return tokenStyles(state); } return handlePhraseModifier(stream, state, stream.next()); } }; CodeMirror.defineMode("textile", function() { return { startState: function() { return { mode: Modes.newLayout }; }, token: function(stream, state) { if (stream.sol()) startNewLine(stream, state); return state.mode(stream, state); }, blankLine: blankLine }; }); CodeMirror.defineMIME("text/x-textile", "textile"); }); ================================================ FILE: third_party/CodeMirror/mode/tiddlywiki/index.html ================================================ CodeMirror: TiddlyWiki mode

TiddlyWiki mode

TiddlyWiki mode supports a single configuration.

MIME types defined: text/x-tiddlywiki.

================================================ FILE: third_party/CodeMirror/mode/tiddlywiki/tiddlywiki.css ================================================ span.cm-underlined { text-decoration: underline; } span.cm-strikethrough { text-decoration: line-through; } span.cm-brace { color: #170; font-weight: bold; } span.cm-table { color: blue; font-weight: bold; } ================================================ FILE: third_party/CodeMirror/mode/tiddlywiki/tiddlywiki.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /*** |''Name''|tiddlywiki.js| |''Description''|Enables TiddlyWikiy syntax highlighting using CodeMirror| |''Author''|PMario| |''Version''|0.1.7| |''Status''|''stable''| |''Source''|[[GitHub|https://github.com/pmario/CodeMirror2/blob/tw-syntax/mode/tiddlywiki]]| |''Documentation''|https://codemirror.tiddlyspace.com/| |''License''|[[MIT License|http://www.opensource.org/licenses/mit-license.php]]| |''CoreVersion''|2.5.0| |''Requires''|codemirror.js| |''Keywords''|syntax highlighting color code mirror codemirror| ! Info CoreVersion parameter is needed for TiddlyWiki only! ***/ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("tiddlywiki", function () { // Tokenizer var textwords = {}; var keywords = { "allTags": true, "closeAll": true, "list": true, "newJournal": true, "newTiddler": true, "permaview": true, "saveChanges": true, "search": true, "slider": true, "tabs": true, "tag": true, "tagging": true, "tags": true, "tiddler": true, "timeline": true, "today": true, "version": true, "option": true, "with": true, "filter": true }; var isSpaceName = /[\w_\-]/i, reHR = /^\-\-\-\-+$/, //
reWikiCommentStart = /^\/\*\*\*$/, // /*** reWikiCommentStop = /^\*\*\*\/$/, // ***/ reBlockQuote = /^<<<$/, reJsCodeStart = /^\/\/\{\{\{$/, // //{{{ js block start reJsCodeStop = /^\/\/\}\}\}$/, // //}}} js stop reXmlCodeStart = /^$/, // xml block start reXmlCodeStop = /^$/, // xml stop reCodeBlockStart = /^\{\{\{$/, // {{{ TW text div block start reCodeBlockStop = /^\}\}\}$/, // }}} TW text stop reUntilCodeStop = /.*?\}\}\}/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenBase(stream, state) { var sol = stream.sol(), ch = stream.peek(); state.block = false; // indicates the start of a code block. // check start of blocks if (sol && /[<\/\*{}\-]/.test(ch)) { if (stream.match(reCodeBlockStart)) { state.block = true; return chain(stream, state, twTokenCode); } if (stream.match(reBlockQuote)) return 'quote'; if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop)) return 'comment'; if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop)) return 'comment'; if (stream.match(reHR)) return 'hr'; } stream.next(); if (sol && /[\/\*!#;:>|]/.test(ch)) { if (ch == "!") { // tw header stream.skipToEnd(); return "header"; } if (ch == "*") { // tw list stream.eatWhile('*'); return "comment"; } if (ch == "#") { // tw numbered list stream.eatWhile('#'); return "comment"; } if (ch == ";") { // definition list, term stream.eatWhile(';'); return "comment"; } if (ch == ":") { // definition list, description stream.eatWhile(':'); return "comment"; } if (ch == ">") { // single line quote stream.eatWhile(">"); return "quote"; } if (ch == '|') return 'header'; } if (ch == '{' && stream.match(/\{\{/)) return chain(stream, state, twTokenCode); // rudimentary html:// file:// link matching. TW knows much more ... if (/[hf]/i.test(ch) && /[ti]/i.test(stream.peek()) && stream.match(/\b(ttps?|tp|ile):\/\/[\-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i)) return "link"; // just a little string indicator, don't want to have the whole string covered if (ch == '"') return 'string'; if (ch == '~') // _no_ CamelCase indicator should be bold return 'brace'; if (/[\[\]]/.test(ch) && stream.match(ch)) // check for [[..]] return 'brace'; if (ch == "@") { // check for space link. TODO fix @@...@@ highlighting stream.eatWhile(isSpaceName); return "link"; } if (/\d/.test(ch)) { // numbers stream.eatWhile(/\d/); return "number"; } if (ch == "/") { // tw invisible comment if (stream.eat("%")) { return chain(stream, state, twTokenComment); } else if (stream.eat("/")) { // return chain(stream, state, twTokenEm); } } if (ch == "_" && stream.eat("_")) // tw underline return chain(stream, state, twTokenUnderline); // strikethrough and mdash handling if (ch == "-" && stream.eat("-")) { // if strikethrough looks ugly, change CSS. if (stream.peek() != ' ') return chain(stream, state, twTokenStrike); // mdash if (stream.peek() == ' ') return 'brace'; } if (ch == "'" && stream.eat("'")) // tw bold return chain(stream, state, twTokenStrong); if (ch == "<" && stream.eat("<")) // tw macro return chain(stream, state, twTokenMacro); // core macro handling stream.eatWhile(/[\w\$_]/); return textwords.propertyIsEnumerable(stream.current()) ? "keyword" : null } // tw invisible comment function twTokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "%"); } return "comment"; } // tw strong / bold function twTokenStrong(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "'" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "'"); } return "strong"; } // tw code function twTokenCode(stream, state) { var sb = state.block; if (sb && stream.current()) { return "comment"; } if (!sb && stream.match(reUntilCodeStop)) { state.tokenize = tokenBase; return "comment"; } if (sb && stream.sol() && stream.match(reCodeBlockStop)) { state.tokenize = tokenBase; return "comment"; } stream.next(); return "comment"; } // tw em / italic function twTokenEm(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "/"); } return "em"; } // tw underlined text function twTokenUnderline(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "_" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "_"); } return "underlined"; } // tw strike through text looks ugly // change CSS if needed function twTokenStrike(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "-" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "-"); } return "strikethrough"; } // macro function twTokenMacro(stream, state) { if (stream.current() == '<<') { return 'macro'; } var ch = stream.next(); if (!ch) { state.tokenize = tokenBase; return null; } if (ch == ">") { if (stream.peek() == '>') { stream.next(); state.tokenize = tokenBase; return "macro"; } } stream.eatWhile(/[\w\$_]/); return keywords.propertyIsEnumerable(stream.current()) ? "keyword" : null } // Interface return { startState: function () { return {tokenize: tokenBase}; }, token: function (stream, state) { if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); return style; } }; }); CodeMirror.defineMIME("text/x-tiddlywiki", "tiddlywiki"); }); ================================================ FILE: third_party/CodeMirror/mode/tiki/index.html ================================================ CodeMirror: Tiki wiki mode

Tiki wiki mode

================================================ FILE: third_party/CodeMirror/mode/tiki/tiki.css ================================================ .cm-tw-syntaxerror { color: #FFF; background-color: #900; } .cm-tw-deleted { text-decoration: line-through; } .cm-tw-header5 { font-weight: bold; } .cm-tw-listitem:first-child { /*Added first child to fix duplicate padding when highlighting*/ padding-left: 10px; } .cm-tw-box { border-top-width: 0px !important; border-style: solid; border-width: 1px; border-color: inherit; } .cm-tw-underline { text-decoration: underline; } ================================================ FILE: third_party/CodeMirror/mode/tiki/tiki.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('tiki', function(config) { function inBlock(style, terminator, returnTokenizer) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } if (returnTokenizer) state.tokenize = returnTokenizer; return style; }; } function inLine(style) { return function(stream, state) { while(!stream.eol()) { stream.next(); } state.tokenize = inText; return style; }; } function inText(stream, state) { function chain(parser) { state.tokenize = parser; return parser(stream, state); } var sol = stream.sol(); var ch = stream.next(); //non start of line switch (ch) { //switch is generally much faster than if, so it is used here case "{": //plugin stream.eat("/"); stream.eatSpace(); stream.eatWhile(/[^\s\u00a0=\"\'\/?(}]/); state.tokenize = inPlugin; return "tag"; case "_": //bold if (stream.eat("_")) return chain(inBlock("strong", "__", inText)); break; case "'": //italics if (stream.eat("'")) return chain(inBlock("em", "''", inText)); break; case "(":// Wiki Link if (stream.eat("(")) return chain(inBlock("variable-2", "))", inText)); break; case "[":// Weblink return chain(inBlock("variable-3", "]", inText)); break; case "|": //table if (stream.eat("|")) return chain(inBlock("comment", "||")); break; case "-": if (stream.eat("=")) {//titleBar return chain(inBlock("header string", "=-", inText)); } else if (stream.eat("-")) {//deleted return chain(inBlock("error tw-deleted", "--", inText)); } break; case "=": //underline if (stream.match("==")) return chain(inBlock("tw-underline", "===", inText)); break; case ":": if (stream.eat(":")) return chain(inBlock("comment", "::")); break; case "^": //box return chain(inBlock("tw-box", "^")); break; case "~": //np if (stream.match("np~")) return chain(inBlock("meta", "~/np~")); break; } //start of line types if (sol) { switch (ch) { case "!": //header at start of line if (stream.match('!!!!!')) { return chain(inLine("header string")); } else if (stream.match('!!!!')) { return chain(inLine("header string")); } else if (stream.match('!!!')) { return chain(inLine("header string")); } else if (stream.match('!!')) { return chain(inLine("header string")); } else { return chain(inLine("header string")); } break; case "*": //unordered list line item, or
  • at start of line case "#": //ordered list line item, or
  • at start of line case "+": //ordered list line item, or
  • at start of line return chain(inLine("tw-listitem bracket")); break; } } //stream.eatWhile(/[&{]/); was eating up plugins, turned off to act less like html and more like tiki return null; } var indentUnit = config.indentUnit; // Return variables for tokenizers var pluginName, type; function inPlugin(stream, state) { var ch = stream.next(); var peek = stream.peek(); if (ch == "}") { state.tokenize = inText; //type = ch == ")" ? "endPlugin" : "selfclosePlugin"; inPlugin return "tag"; } else if (ch == "(" || ch == ")") { return "bracket"; } else if (ch == "=") { type = "equals"; if (peek == ">") { stream.next(); peek = stream.peek(); } //here we detect values directly after equal character with no quotes if (!/[\'\"]/.test(peek)) { state.tokenize = inAttributeNoQuote(); } //end detect values return "operator"; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); return state.tokenize(stream, state); } else { stream.eatWhile(/[^\s\u00a0=\"\'\/?]/); return "keyword"; } } function inAttribute(quote) { return function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inPlugin; break; } } return "string"; }; } function inAttributeNoQuote() { return function(stream, state) { while (!stream.eol()) { var ch = stream.next(); var peek = stream.peek(); if (ch == " " || ch == "," || /[ )}]/.test(peek)) { state.tokenize = inPlugin; break; } } return "string"; }; } var curState, setStyle; function pass() { for (var i = arguments.length - 1; i >= 0; i--) curState.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function pushContext(pluginName, startOfLine) { var noIndent = curState.context && curState.context.noIndent; curState.context = { prev: curState.context, pluginName: pluginName, indent: curState.indented, startOfLine: startOfLine, noIndent: noIndent }; } function popContext() { if (curState.context) curState.context = curState.context.prev; } function element(type) { if (type == "openPlugin") {curState.pluginName = pluginName; return cont(attributes, endplugin(curState.startOfLine));} else if (type == "closePlugin") { var err = false; if (curState.context) { err = curState.context.pluginName != pluginName; popContext(); } else { err = true; } if (err) setStyle = "error"; return cont(endcloseplugin(err)); } else if (type == "string") { if (!curState.context || curState.context.name != "!cdata") pushContext("!cdata"); if (curState.tokenize == inText) popContext(); return cont(); } else return cont(); } function endplugin(startOfLine) { return function(type) { if ( type == "selfclosePlugin" || type == "endPlugin" ) return cont(); if (type == "endPlugin") {pushContext(curState.pluginName, startOfLine); return cont();} return cont(); }; } function endcloseplugin(err) { return function(type) { if (err) setStyle = "error"; if (type == "endPlugin") return cont(); return pass(); }; } function attributes(type) { if (type == "keyword") {setStyle = "attribute"; return cont(attributes);} if (type == "equals") return cont(attvalue, attributes); return pass(); } function attvalue(type) { if (type == "keyword") {setStyle = "string"; return cont();} if (type == "string") return cont(attvaluemaybe); return pass(); } function attvaluemaybe(type) { if (type == "string") return cont(attvaluemaybe); else return pass(); } return { startState: function() { return {tokenize: inText, cc: [], indented: 0, startOfLine: true, pluginName: null, context: null}; }, token: function(stream, state) { if (stream.sol()) { state.startOfLine = true; state.indented = stream.indentation(); } if (stream.eatSpace()) return null; setStyle = type = pluginName = null; var style = state.tokenize(stream, state); if ((style || type) && style != "comment") { curState = state; while (true) { var comb = state.cc.pop() || element; if (comb(type || style)) break; } } state.startOfLine = false; return setStyle || style; }, indent: function(state, textAfter) { var context = state.context; if (context && context.noIndent) return 0; if (context && /^{\//.test(textAfter)) context = context.prev; while (context && !context.startOfLine) context = context.prev; if (context) return context.indent + indentUnit; else return 0; }, electricChars: "/" }; }); CodeMirror.defineMIME("text/tiki", "tiki"); }); ================================================ FILE: third_party/CodeMirror/mode/toml/index.html ================================================ CodeMirror: TOML Mode

    TOML Mode

    The TOML Mode

    Created by Forbes Lindesay.

    MIME type defined: text/x-toml.

    ================================================ FILE: third_party/CodeMirror/mode/toml/toml.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("toml", function () { return { startState: function () { return { inString: false, stringType: "", lhs: true, inArray: 0 }; }, token: function (stream, state) { //check for state changes if (!state.inString && ((stream.peek() == '"') || (stream.peek() == "'"))) { state.stringType = stream.peek(); stream.next(); // Skip quote state.inString = true; // Update state } if (stream.sol() && state.inArray === 0) { state.lhs = true; } //return state if (state.inString) { while (state.inString && !stream.eol()) { if (stream.peek() === state.stringType) { stream.next(); // Skip quote state.inString = false; // Clear flag } else if (stream.peek() === '\\') { stream.next(); stream.next(); } else { stream.match(/^.[^\\\"\']*/); } } return state.lhs ? "property string" : "string"; // Token style } else if (state.inArray && stream.peek() === ']') { stream.next(); state.inArray--; return 'bracket'; } else if (state.lhs && stream.peek() === '[' && stream.skipTo(']')) { stream.next();//skip closing ] // array of objects has an extra open & close [] if (stream.peek() === ']') stream.next(); return "atom"; } else if (stream.peek() === "#") { stream.skipToEnd(); return "comment"; } else if (stream.eatSpace()) { return null; } else if (state.lhs && stream.eatWhile(function (c) { return c != '=' && c != ' '; })) { return "property"; } else if (state.lhs && stream.peek() === "=") { stream.next(); state.lhs = false; return null; } else if (!state.lhs && stream.match(/^\d\d\d\d[\d\-\:\.T]*Z/)) { return 'atom'; //date } else if (!state.lhs && (stream.match('true') || stream.match('false'))) { return 'atom'; } else if (!state.lhs && stream.peek() === '[') { state.inArray++; stream.next(); return 'bracket'; } else if (!state.lhs && stream.match(/^\-?\d+(?:\.\d+)?/)) { return 'number'; } else if (!stream.eatSpace()) { stream.next(); } return null; } }; }); CodeMirror.defineMIME('text/x-toml', 'toml'); }); ================================================ FILE: third_party/CodeMirror/mode/tornado/index.html ================================================ CodeMirror: Tornado template mode

    Tornado template mode

    Mode for HTML with embedded Tornado template markup.

    MIME types defined: text/x-tornado

    ================================================ FILE: third_party/CodeMirror/mode/tornado/tornado.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../htmlmixed/htmlmixed"), require("../../addon/mode/overlay")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../htmlmixed/htmlmixed", "../../addon/mode/overlay"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("tornado:inner", function() { var keywords = ["and","as","assert","autoescape","block","break","class","comment","context", "continue","datetime","def","del","elif","else","end","escape","except", "exec","extends","false","finally","for","from","global","if","import","in", "include","is","json_encode","lambda","length","linkify","load","module", "none","not","or","pass","print","put","raise","raw","return","self","set", "squeeze","super","true","try","url_escape","while","with","without","xhtml_escape","yield"]; keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b"); function tokenBase (stream, state) { stream.eatWhile(/[^\{]/); var ch = stream.next(); if (ch == "{") { if (ch = stream.eat(/\{|%|#/)) { state.tokenize = inTag(ch); return "tag"; } } } function inTag (close) { if (close == "{") { close = "}"; } return function (stream, state) { var ch = stream.next(); if ((ch == close) && stream.eat("}")) { state.tokenize = tokenBase; return "tag"; } if (stream.match(keywords)) { return "keyword"; } return close == "#" ? "comment" : "string"; }; } return { startState: function () { return {tokenize: tokenBase}; }, token: function (stream, state) { return state.tokenize(stream, state); } }; }); CodeMirror.defineMode("tornado", function(config) { var htmlBase = CodeMirror.getMode(config, "text/html"); var tornadoInner = CodeMirror.getMode(config, "tornado:inner"); return CodeMirror.overlayMode(htmlBase, tornadoInner); }); CodeMirror.defineMIME("text/x-tornado", "tornado"); }); ================================================ FILE: third_party/CodeMirror/mode/troff/index.html ================================================ CodeMirror: troff mode

    troff

    MIME types defined: troff.

    ================================================ FILE: third_party/CodeMirror/mode/troff/troff.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) define(["../../lib/codemirror"], mod); else mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('troff', function() { var words = {}; function tokenBase(stream) { if (stream.eatSpace()) return null; var sol = stream.sol(); var ch = stream.next(); if (ch === '\\') { if (stream.match('fB') || stream.match('fR') || stream.match('fI') || stream.match('u') || stream.match('d') || stream.match('%') || stream.match('&')) { return 'string'; } if (stream.match('m[')) { stream.skipTo(']'); stream.next(); return 'string'; } if (stream.match('s+') || stream.match('s-')) { stream.eatWhile(/[\d-]/); return 'string'; } if (stream.match('\(') || stream.match('*\(')) { stream.eatWhile(/[\w-]/); return 'string'; } return 'string'; } if (sol && (ch === '.' || ch === '\'')) { if (stream.eat('\\') && stream.eat('\"')) { stream.skipToEnd(); return 'comment'; } } if (sol && ch === '.') { if (stream.match('B ') || stream.match('I ') || stream.match('R ')) { return 'attribute'; } if (stream.match('TH ') || stream.match('SH ') || stream.match('SS ') || stream.match('HP ')) { stream.skipToEnd(); return 'quote'; } if ((stream.match(/[A-Z]/) && stream.match(/[A-Z]/)) || (stream.match(/[a-z]/) && stream.match(/[a-z]/))) { return 'attribute'; } } stream.eatWhile(/[\w-]/); var cur = stream.current(); return words.hasOwnProperty(cur) ? words[cur] : null; } function tokenize(stream, state) { return (state.tokens[0] || tokenBase) (stream, state); }; return { startState: function() {return {tokens:[]};}, token: function(stream, state) { return tokenize(stream, state); } }; }); CodeMirror.defineMIME('text/troff', 'troff'); CodeMirror.defineMIME('text/x-troff', 'troff'); CodeMirror.defineMIME('application/x-troff', 'troff'); }); ================================================ FILE: third_party/CodeMirror/mode/ttcn/index.html ================================================ CodeMirror: TTCN mode

    TTCN example


    Language: Testing and Test Control Notation (TTCN)

    MIME types defined: text/x-ttcn, text/x-ttcn3, text/x-ttcnpp.


    The development of this mode has been sponsored by Ericsson .

    Coded by Asmelash Tsegay Gebretsadkan

    ================================================ FILE: third_party/CodeMirror/mode/ttcn/ttcn.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("ttcn", function(config, parserConfig) { var indentUnit = config.indentUnit, keywords = parserConfig.keywords || {}, builtin = parserConfig.builtin || {}, timerOps = parserConfig.timerOps || {}, portOps = parserConfig.portOps || {}, configOps = parserConfig.configOps || {}, verdictOps = parserConfig.verdictOps || {}, sutOps = parserConfig.sutOps || {}, functionOps = parserConfig.functionOps || {}, verdictConsts = parserConfig.verdictConsts || {}, booleanConsts = parserConfig.booleanConsts || {}, otherConsts = parserConfig.otherConsts || {}, types = parserConfig.types || {}, visibilityModifiers = parserConfig.visibilityModifiers || {}, templateMatch = parserConfig.templateMatch || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false; var isOperatorChar = /[+\-*&@=<>!\/]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[\[\]{}\(\),;\\:\?\.]/.test(ch)) { curPunc = ch; return "punctuation"; } if (ch == "#"){ stream.skipToEnd(); return "atom preprocessor"; } if (ch == "%"){ stream.eatWhile(/\b/); return "atom ttcn3Macros"; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } if (isOperatorChar.test(ch)) { if(ch == "@"){ if(stream.match("try") || stream.match("catch") || stream.match("lazy")){ return "keyword"; } } stream.eatWhile(isOperatorChar); return "operator"; } stream.eatWhile(/[\w\$_\xa1-\uffff]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) return "keyword"; if (builtin.propertyIsEnumerable(cur)) return "builtin"; if (timerOps.propertyIsEnumerable(cur)) return "def timerOps"; if (configOps.propertyIsEnumerable(cur)) return "def configOps"; if (verdictOps.propertyIsEnumerable(cur)) return "def verdictOps"; if (portOps.propertyIsEnumerable(cur)) return "def portOps"; if (sutOps.propertyIsEnumerable(cur)) return "def sutOps"; if (functionOps.propertyIsEnumerable(cur)) return "def functionOps"; if (verdictConsts.propertyIsEnumerable(cur)) return "string verdictConsts"; if (booleanConsts.propertyIsEnumerable(cur)) return "string booleanConsts"; if (otherConsts.propertyIsEnumerable(cur)) return "string otherConsts"; if (types.propertyIsEnumerable(cur)) return "builtin types"; if (visibilityModifiers.propertyIsEnumerable(cur)) return "builtin visibilityModifiers"; if (templateMatch.propertyIsEnumerable(cur)) return "atom templateMatch"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped){ var afterQuote = stream.peek(); //look if the character after the quote is like the B in '10100010'B if (afterQuote){ afterQuote = afterQuote.toLowerCase(); if(afterQuote == "b" || afterQuote == "h" || afterQuote == "o") stream.next(); } end = true; break; } escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = null; break; } maybeEnd = (ch == "*"); } return "comment"; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { var indent = state.indented; if (state.context && state.context.type == "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } //Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; curPunc = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement"){ popContext(state); } else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))) pushContext(state, stream.column(), "statement"); state.startOfLine = false; return style; }, electricChars: "{}", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } function def(mimes, mode) { if (typeof mimes == "string") mimes = [mimes]; var words = []; function add(obj) { if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) words.push(prop); } add(mode.keywords); add(mode.builtin); add(mode.timerOps); add(mode.portOps); if (words.length) { mode.helperType = mimes[0]; CodeMirror.registerHelper("hintWords", mimes[0], words); } for (var i = 0; i < mimes.length; ++i) CodeMirror.defineMIME(mimes[i], mode); } def(["text/x-ttcn", "text/x-ttcn3", "text/x-ttcnpp"], { name: "ttcn", keywords: words("activate address alive all alt altstep and and4b any" + " break case component const continue control deactivate" + " display do else encode enumerated except exception" + " execute extends extension external for from function" + " goto group if import in infinity inout interleave" + " label language length log match message mixed mod" + " modifies module modulepar mtc noblock not not4b nowait" + " of on optional or or4b out override param pattern port" + " procedure record recursive rem repeat return runs select" + " self sender set signature system template testcase to" + " type union value valueof var variant while with xor xor4b"), builtin: words("bit2hex bit2int bit2oct bit2str char2int char2oct encvalue" + " decomp decvalue float2int float2str hex2bit hex2int" + " hex2oct hex2str int2bit int2char int2float int2hex" + " int2oct int2str int2unichar isbound ischosen ispresent" + " isvalue lengthof log2str oct2bit oct2char oct2hex oct2int" + " oct2str regexp replace rnd sizeof str2bit str2float" + " str2hex str2int str2oct substr unichar2int unichar2char" + " enum2int"), types: words("anytype bitstring boolean char charstring default float" + " hexstring integer objid octetstring universal verdicttype timer"), timerOps: words("read running start stop timeout"), portOps: words("call catch check clear getcall getreply halt raise receive" + " reply send trigger"), configOps: words("create connect disconnect done kill killed map unmap"), verdictOps: words("getverdict setverdict"), sutOps: words("action"), functionOps: words("apply derefers refers"), verdictConsts: words("error fail inconc none pass"), booleanConsts: words("true false"), otherConsts: words("null NULL omit"), visibilityModifiers: words("private public friend"), templateMatch: words("complement ifpresent subset superset permutation"), multiLineStrings: true }); }); ================================================ FILE: third_party/CodeMirror/mode/ttcn-cfg/index.html ================================================ CodeMirror: TTCN-CFG mode

    TTCN-CFG example


    Language: Testing and Test Control Notation - Configuration files (TTCN-CFG)

    MIME types defined: text/x-ttcn-cfg.


    The development of this mode has been sponsored by Ericsson .

    Coded by Asmelash Tsegay Gebretsadkan

    ================================================ FILE: third_party/CodeMirror/mode/ttcn-cfg/ttcn-cfg.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("ttcn-cfg", function(config, parserConfig) { var indentUnit = config.indentUnit, keywords = parserConfig.keywords || {}, fileNCtrlMaskOptions = parserConfig.fileNCtrlMaskOptions || {}, externalCommands = parserConfig.externalCommands || {}, multiLineStrings = parserConfig.multiLineStrings, indentStatements = parserConfig.indentStatements !== false; var isOperatorChar = /[\|]/; var curPunc; function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } if (/[:=]/.test(ch)) { curPunc = ch; return "punctuation"; } if (ch == "#"){ stream.skipToEnd(); return "comment"; } if (/\d/.test(ch)) { stream.eatWhile(/[\w\.]/); return "number"; } if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return "operator"; } if (ch == "["){ stream.eatWhile(/[\w_\]]/); return "number sectionTitle"; } stream.eatWhile(/[\w\$_]/); var cur = stream.current(); if (keywords.propertyIsEnumerable(cur)) return "keyword"; if (fileNCtrlMaskOptions.propertyIsEnumerable(cur)) return "negative fileNCtrlMaskOptions"; if (externalCommands.propertyIsEnumerable(cur)) return "negative externalCommands"; return "variable"; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped){ var afterNext = stream.peek(); //look if the character if the quote is like the B in '10100010'B if (afterNext){ afterNext = afterNext.toLowerCase(); if(afterNext == "b" || afterNext == "h" || afterNext == "o") stream.next(); } end = true; break; } escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = null; return "string"; }; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { var indent = state.indented; if (state.context && state.context.type == "statement") indent = state.context.indented; return state.context = new Context(indent, col, type, null, state.context); } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") state.indented = state.context.indented; return state.context = state.context.prev; } //Interface return { startState: function(basecolumn) { return { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (stream.eatSpace()) return null; curPunc = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment") return style; if (ctx.align == null) ctx.align = true; if ((curPunc == ";" || curPunc == ":" || curPunc == ",") && ctx.type == "statement"){ popContext(state); } else if (curPunc == "{") pushContext(state, stream.column(), "}"); else if (curPunc == "[") pushContext(state, stream.column(), "]"); else if (curPunc == "(") pushContext(state, stream.column(), ")"); else if (curPunc == "}") { while (ctx.type == "statement") ctx = popContext(state); if (ctx.type == "}") ctx = popContext(state); while (ctx.type == "statement") ctx = popContext(state); } else if (curPunc == ctx.type) popContext(state); else if (indentStatements && (((ctx.type == "}" || ctx.type == "top") && curPunc != ';') || (ctx.type == "statement" && curPunc == "newstatement"))) pushContext(state, stream.column(), "statement"); state.startOfLine = false; return style; }, electricChars: "{}", lineComment: "#", fold: "brace" }; }); function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } CodeMirror.defineMIME("text/x-ttcn-cfg", { name: "ttcn-cfg", keywords: words("Yes No LogFile FileMask ConsoleMask AppendFile" + " TimeStampFormat LogEventTypes SourceInfoFormat" + " LogEntityName LogSourceInfo DiskFullAction" + " LogFileNumber LogFileSize MatchingHints Detailed" + " Compact SubCategories Stack Single None Seconds" + " DateTime Time Stop Error Retry Delete TCPPort KillTimer" + " NumHCs UnixSocketsEnabled LocalAddress"), fileNCtrlMaskOptions: words("TTCN_EXECUTOR TTCN_ERROR TTCN_WARNING" + " TTCN_PORTEVENT TTCN_TIMEROP TTCN_VERDICTOP" + " TTCN_DEFAULTOP TTCN_TESTCASE TTCN_ACTION" + " TTCN_USER TTCN_FUNCTION TTCN_STATISTICS" + " TTCN_PARALLEL TTCN_MATCHING TTCN_DEBUG" + " EXECUTOR ERROR WARNING PORTEVENT TIMEROP" + " VERDICTOP DEFAULTOP TESTCASE ACTION USER" + " FUNCTION STATISTICS PARALLEL MATCHING DEBUG" + " LOG_ALL LOG_NOTHING ACTION_UNQUALIFIED" + " DEBUG_ENCDEC DEBUG_TESTPORT" + " DEBUG_UNQUALIFIED DEFAULTOP_ACTIVATE" + " DEFAULTOP_DEACTIVATE DEFAULTOP_EXIT" + " DEFAULTOP_UNQUALIFIED ERROR_UNQUALIFIED" + " EXECUTOR_COMPONENT EXECUTOR_CONFIGDATA" + " EXECUTOR_EXTCOMMAND EXECUTOR_LOGOPTIONS" + " EXECUTOR_RUNTIME EXECUTOR_UNQUALIFIED" + " FUNCTION_RND FUNCTION_UNQUALIFIED" + " MATCHING_DONE MATCHING_MCSUCCESS" + " MATCHING_MCUNSUCC MATCHING_MMSUCCESS" + " MATCHING_MMUNSUCC MATCHING_PCSUCCESS" + " MATCHING_PCUNSUCC MATCHING_PMSUCCESS" + " MATCHING_PMUNSUCC MATCHING_PROBLEM" + " MATCHING_TIMEOUT MATCHING_UNQUALIFIED" + " PARALLEL_PORTCONN PARALLEL_PORTMAP" + " PARALLEL_PTC PARALLEL_UNQUALIFIED" + " PORTEVENT_DUALRECV PORTEVENT_DUALSEND" + " PORTEVENT_MCRECV PORTEVENT_MCSEND" + " PORTEVENT_MMRECV PORTEVENT_MMSEND" + " PORTEVENT_MQUEUE PORTEVENT_PCIN" + " PORTEVENT_PCOUT PORTEVENT_PMIN" + " PORTEVENT_PMOUT PORTEVENT_PQUEUE" + " PORTEVENT_STATE PORTEVENT_UNQUALIFIED" + " STATISTICS_UNQUALIFIED STATISTICS_VERDICT" + " TESTCASE_FINISH TESTCASE_START" + " TESTCASE_UNQUALIFIED TIMEROP_GUARD" + " TIMEROP_READ TIMEROP_START TIMEROP_STOP" + " TIMEROP_TIMEOUT TIMEROP_UNQUALIFIED" + " USER_UNQUALIFIED VERDICTOP_FINAL" + " VERDICTOP_GETVERDICT VERDICTOP_SETVERDICT" + " VERDICTOP_UNQUALIFIED WARNING_UNQUALIFIED"), externalCommands: words("BeginControlPart EndControlPart BeginTestCase" + " EndTestCase"), multiLineStrings: true }); }); ================================================ FILE: third_party/CodeMirror/mode/turtle/index.html ================================================ CodeMirror: Turtle mode

    Turtle mode

    MIME types defined: text/turtle.

    ================================================ FILE: third_party/CodeMirror/mode/turtle/turtle.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("turtle", function(config) { var indentUnit = config.indentUnit; var curPunc; function wordRegexp(words) { return new RegExp("^(?:" + words.join("|") + ")$", "i"); } var ops = wordRegexp([]); var keywords = wordRegexp(["@prefix", "@base", "a"]); var operatorChars = /[*+\-<>=&|]/; function tokenBase(stream, state) { var ch = stream.next(); curPunc = null; if (ch == "<" && !stream.match(/^[\s\u00a0=]/, false)) { stream.match(/^[^\s\u00a0>]*>?/); return "atom"; } else if (ch == "\"" || ch == "'") { state.tokenize = tokenLiteral(ch); return state.tokenize(stream, state); } else if (/[{}\(\),\.;\[\]]/.test(ch)) { curPunc = ch; return null; } else if (ch == "#") { stream.skipToEnd(); return "comment"; } else if (operatorChars.test(ch)) { stream.eatWhile(operatorChars); return null; } else if (ch == ":") { return "operator"; } else { stream.eatWhile(/[_\w\d]/); if(stream.peek() == ":") { return "variable-3"; } else { var word = stream.current(); if(keywords.test(word)) { return "meta"; } if(ch >= "A" && ch <= "Z") { return "comment"; } else { return "keyword"; } } var word = stream.current(); if (ops.test(word)) return null; else if (keywords.test(word)) return "meta"; else return "variable"; } } function tokenLiteral(quote) { return function(stream, state) { var escaped = false, ch; while ((ch = stream.next()) != null) { if (ch == quote && !escaped) { state.tokenize = tokenBase; break; } escaped = !escaped && ch == "\\"; } return "string"; }; } function pushContext(state, type, col) { state.context = {prev: state.context, indent: state.indent, col: col, type: type}; } function popContext(state) { state.indent = state.context.indent; state.context = state.context.prev; } return { startState: function() { return {tokenize: tokenBase, context: null, indent: 0, col: 0}; }, token: function(stream, state) { if (stream.sol()) { if (state.context && state.context.align == null) state.context.align = false; state.indent = stream.indentation(); } if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (style != "comment" && state.context && state.context.align == null && state.context.type != "pattern") { state.context.align = true; } if (curPunc == "(") pushContext(state, ")", stream.column()); else if (curPunc == "[") pushContext(state, "]", stream.column()); else if (curPunc == "{") pushContext(state, "}", stream.column()); else if (/[\]\}\)]/.test(curPunc)) { while (state.context && state.context.type == "pattern") popContext(state); if (state.context && curPunc == state.context.type) popContext(state); } else if (curPunc == "." && state.context && state.context.type == "pattern") popContext(state); else if (/atom|string|variable/.test(style) && state.context) { if (/[\}\]]/.test(state.context.type)) pushContext(state, "pattern", stream.column()); else if (state.context.type == "pattern" && !state.context.align) { state.context.align = true; state.context.col = stream.column(); } } return style; }, indent: function(state, textAfter) { var firstChar = textAfter && textAfter.charAt(0); var context = state.context; if (/[\]\}]/.test(firstChar)) while (context && context.type == "pattern") context = context.prev; var closing = context && firstChar == context.type; if (!context) return 0; else if (context.type == "pattern") return context.col; else if (context.align) return context.col + (closing ? 0 : 1); else return context.indent + (closing ? 0 : indentUnit); }, lineComment: "#" }; }); CodeMirror.defineMIME("text/turtle", "turtle"); }); ================================================ FILE: third_party/CodeMirror/mode/twig/index.html ================================================ CodeMirror: Twig mode

    Twig mode

    ================================================ FILE: third_party/CodeMirror/mode/twig/twig.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/multiplex")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../../addon/mode/multiplex"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("twig:inner", function() { 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"], operator = /^[+\-*&%=<>!?|~^]/, sign = /^[:\[\(\{]/, atom = ["true", "false", "null", "empty", "defined", "divisibleby", "divisible by", "even", "odd", "iterable", "sameas", "same as"], number = /^(\d[+\-\*\/])?\d+(\.\d+)?/; keywords = new RegExp("((" + keywords.join(")|(") + "))\\b"); atom = new RegExp("((" + atom.join(")|(") + "))\\b"); function tokenBase (stream, state) { var ch = stream.peek(); //Comment if (state.incomment) { if (!stream.skipTo("#}")) { stream.skipToEnd(); } else { stream.eatWhile(/\#|}/); state.incomment = false; } return "comment"; //Tag } else if (state.intag) { //After operator if (state.operator) { state.operator = false; if (stream.match(atom)) { return "atom"; } if (stream.match(number)) { return "number"; } } //After sign if (state.sign) { state.sign = false; if (stream.match(atom)) { return "atom"; } if (stream.match(number)) { return "number"; } } if (state.instring) { if (ch == state.instring) { state.instring = false; } stream.next(); return "string"; } else if (ch == "'" || ch == '"') { state.instring = ch; stream.next(); return "string"; } else if (stream.match(state.intag + "}") || stream.eat("-") && stream.match(state.intag + "}")) { state.intag = false; return "tag"; } else if (stream.match(operator)) { state.operator = true; return "operator"; } else if (stream.match(sign)) { state.sign = true; } else { if (stream.eat(" ") || stream.sol()) { if (stream.match(keywords)) { return "keyword"; } if (stream.match(atom)) { return "atom"; } if (stream.match(number)) { return "number"; } if (stream.sol()) { stream.next(); } } else { stream.next(); } } return "variable"; } else if (stream.eat("{")) { if (stream.eat("#")) { state.incomment = true; if (!stream.skipTo("#}")) { stream.skipToEnd(); } else { stream.eatWhile(/\#|}/); state.incomment = false; } return "comment"; //Open tag } else if (ch = stream.eat(/\{|%/)) { //Cache close tag state.intag = ch; if (ch == "{") { state.intag = "}"; } stream.eat("-"); return "tag"; } } stream.next(); }; return { startState: function () { return {}; }, token: function (stream, state) { return tokenBase(stream, state); } }; }); CodeMirror.defineMode("twig", function(config, parserConfig) { var twigInner = CodeMirror.getMode(config, "twig:inner"); if (!parserConfig || !parserConfig.base) return twigInner; return CodeMirror.multiplexingMode( CodeMirror.getMode(config, parserConfig.base), { open: /\{[{#%]/, close: /[}#%]\}/, mode: twigInner, parseDelimiters: true } ); }); CodeMirror.defineMIME("text/x-twig", "twig"); }); ================================================ FILE: third_party/CodeMirror/mode/vb/index.html ================================================ CodeMirror: VB.NET mode

    VB.NET mode

    MIME type defined: text/x-vb.

    ================================================ FILE: third_party/CodeMirror/mode/vb/vb.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("vb", function(conf, parserConf) { var ERRORCLASS = 'error'; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b", "i"); } var singleOperators = new RegExp("^[\\+\\-\\*/%&\\\\|\\^~<>!]"); var singleDelimiters = new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]'); var doubleOperators = new RegExp("^((==)|(<>)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))"); var doubleDelimiters = new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))"); var tripleDelimiters = new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))"); var identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*"); var openingKeywords = ['class','module', 'sub','enum','select','while','if','function', 'get','set','property', 'try']; var middleKeywords = ['else','elseif','case', 'catch']; var endKeywords = ['next','loop']; var operatorKeywords = ['and', 'or', 'not', 'xor', 'in']; var wordOperators = wordRegexp(operatorKeywords); var commonKeywords = ['as', 'dim', 'break', 'continue','optional', 'then', 'until', 'goto', 'byval','byref','new','handles','property', 'return', 'const','private', 'protected', 'friend', 'public', 'shared', 'static', 'true','false']; var commontypes = ['integer','string','double','decimal','boolean','short','char', 'float','single']; var keywords = wordRegexp(commonKeywords); var types = wordRegexp(commontypes); var stringPrefixes = '"'; var opening = wordRegexp(openingKeywords); var middle = wordRegexp(middleKeywords); var closing = wordRegexp(endKeywords); var doubleClosing = wordRegexp(['end']); var doOpening = wordRegexp(['do']); var indentInfo = null; CodeMirror.registerHelper("hintWords", "vb", openingKeywords.concat(middleKeywords).concat(endKeywords) .concat(operatorKeywords).concat(commonKeywords).concat(commontypes)); function indent(_stream, state) { state.currentIndent++; } function dedent(_stream, state) { state.currentIndent--; } // tokenizers function tokenBase(stream, state) { if (stream.eatSpace()) { return null; } var ch = stream.peek(); // Handle Comments if (ch === "'") { stream.skipToEnd(); return 'comment'; } // Handle Number Literals if (stream.match(/^((&H)|(&O))?[0-9\.a-f]/i, false)) { var floatLiteral = false; // Floats if (stream.match(/^\d*\.\d+F?/i)) { floatLiteral = true; } else if (stream.match(/^\d+\.\d*F?/)) { floatLiteral = true; } else if (stream.match(/^\.\d+F?/)) { floatLiteral = true; } if (floatLiteral) { // Float literals may be "imaginary" stream.eat(/J/i); return 'number'; } // Integers var intLiteral = false; // Hex if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; } // Octal else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; } // Decimal else if (stream.match(/^[1-9]\d*F?/)) { // Decimal literals may be "imaginary" stream.eat(/J/i); // TODO - Can you have imaginary longs? intLiteral = true; } // Zero by itself with no other piece of number. else if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; } if (intLiteral) { // Integer literals may be "long" stream.eat(/L/i); return 'number'; } } // Handle Strings if (stream.match(stringPrefixes)) { state.tokenize = tokenStringFactory(stream.current()); return state.tokenize(stream, state); } // Handle operators and Delimiters if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) { return null; } if (stream.match(doubleOperators) || stream.match(singleOperators) || stream.match(wordOperators)) { return 'operator'; } if (stream.match(singleDelimiters)) { return null; } if (stream.match(doOpening)) { indent(stream,state); state.doInCurrentLine = true; return 'keyword'; } if (stream.match(opening)) { if (! state.doInCurrentLine) indent(stream,state); else state.doInCurrentLine = false; return 'keyword'; } if (stream.match(middle)) { return 'keyword'; } if (stream.match(doubleClosing)) { dedent(stream,state); dedent(stream,state); return 'keyword'; } if (stream.match(closing)) { dedent(stream,state); return 'keyword'; } if (stream.match(types)) { return 'keyword'; } if (stream.match(keywords)) { return 'keyword'; } if (stream.match(identifiers)) { return 'variable'; } // Handle non-detected items stream.next(); return ERRORCLASS; } function tokenStringFactory(delimiter) { var singleline = delimiter.length == 1; var OUTCLASS = 'string'; return function(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^'"]/); if (stream.match(delimiter)) { state.tokenize = tokenBase; return OUTCLASS; } else { stream.eat(/['"]/); } } if (singleline) { if (parserConf.singleLineStringErrors) { return ERRORCLASS; } else { state.tokenize = tokenBase; } } return OUTCLASS; }; } function tokenLexer(stream, state) { var style = state.tokenize(stream, state); var current = stream.current(); // Handle '.' connected identifiers if (current === '.') { style = state.tokenize(stream, state); if (style === 'variable') { return 'variable'; } else { return ERRORCLASS; } } var delimiter_index = '[({'.indexOf(current); if (delimiter_index !== -1) { indent(stream, state ); } if (indentInfo === 'dedent') { if (dedent(stream, state)) { return ERRORCLASS; } } delimiter_index = '])}'.indexOf(current); if (delimiter_index !== -1) { if (dedent(stream, state)) { return ERRORCLASS; } } return style; } var external = { electricChars:"dDpPtTfFeE ", startState: function() { return { tokenize: tokenBase, lastToken: null, currentIndent: 0, nextLineIndent: 0, doInCurrentLine: false }; }, token: function(stream, state) { if (stream.sol()) { state.currentIndent += state.nextLineIndent; state.nextLineIndent = 0; state.doInCurrentLine = 0; } var style = tokenLexer(stream, state); state.lastToken = {style:style, content: stream.current()}; return style; }, indent: function(state, textAfter) { var trueText = textAfter.replace(/^\s+|\s+$/g, '') ; if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return conf.indentUnit*(state.currentIndent-1); if(state.currentIndent < 0) return 0; return state.currentIndent * conf.indentUnit; }, lineComment: "'" }; return external; }); CodeMirror.defineMIME("text/x-vb", "vb"); }); ================================================ FILE: third_party/CodeMirror/mode/vbscript/index.html ================================================ CodeMirror: VBScript mode

    VBScript mode

    MIME types defined: text/vbscript.

    ================================================ FILE: third_party/CodeMirror/mode/vbscript/vbscript.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE /* For extra ASP classic objects, initialize CodeMirror instance with this option: isASP: true E.G.: var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, isASP: true }); */ (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("vbscript", function(conf, parserConf) { var ERRORCLASS = 'error'; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b", "i"); } var singleOperators = new RegExp("^[\\+\\-\\*/&\\\\\\^<>=]"); var doubleOperators = new RegExp("^((<>)|(<=)|(>=))"); var singleDelimiters = new RegExp('^[\\.,]'); var brakets = new RegExp('^[\\(\\)]'); var identifiers = new RegExp("^[A-Za-z][_A-Za-z0-9]*"); var openingKeywords = ['class','sub','select','while','if','function', 'property', 'with', 'for']; var middleKeywords = ['else','elseif','case']; var endKeywords = ['next','loop','wend']; var wordOperators = wordRegexp(['and', 'or', 'not', 'xor', 'is', 'mod', 'eqv', 'imp']); var commonkeywords = ['dim', 'redim', 'then', 'until', 'randomize', 'byval','byref','new','property', 'exit', 'in', 'const','private', 'public', 'get','set','let', 'stop', 'on error resume next', 'on error goto 0', 'option explicit', 'call', 'me']; //This list was from: http://msdn.microsoft.com/en-us/library/f8tbc79x(v=vs.84).aspx var atomWords = ['true', 'false', 'nothing', 'empty', 'null']; //This list was from: http://msdn.microsoft.com/en-us/library/3ca8tfek(v=vs.84).aspx var builtinFuncsWords = ['abs', 'array', 'asc', 'atn', 'cbool', 'cbyte', 'ccur', 'cdate', 'cdbl', 'chr', 'cint', 'clng', 'cos', 'csng', 'cstr', 'date', 'dateadd', 'datediff', 'datepart', 'dateserial', 'datevalue', 'day', 'escape', 'eval', 'execute', 'exp', 'filter', 'formatcurrency', 'formatdatetime', 'formatnumber', 'formatpercent', 'getlocale', 'getobject', 'getref', 'hex', 'hour', 'inputbox', 'instr', 'instrrev', 'int', 'fix', 'isarray', 'isdate', 'isempty', 'isnull', 'isnumeric', 'isobject', 'join', 'lbound', 'lcase', 'left', 'len', 'loadpicture', 'log', 'ltrim', 'rtrim', 'trim', 'maths', 'mid', 'minute', 'month', 'monthname', 'msgbox', 'now', 'oct', 'replace', 'rgb', 'right', 'rnd', 'round', 'scriptengine', 'scriptenginebuildversion', 'scriptenginemajorversion', 'scriptengineminorversion', 'second', 'setlocale', 'sgn', 'sin', 'space', 'split', 'sqr', 'strcomp', 'string', 'strreverse', 'tan', 'time', 'timer', 'timeserial', 'timevalue', 'typename', 'ubound', 'ucase', 'unescape', 'vartype', 'weekday', 'weekdayname', 'year']; //This list was from: http://msdn.microsoft.com/en-us/library/ydz4cfk3(v=vs.84).aspx var builtinConsts = ['vbBlack', 'vbRed', 'vbGreen', 'vbYellow', 'vbBlue', 'vbMagenta', 'vbCyan', 'vbWhite', 'vbBinaryCompare', 'vbTextCompare', 'vbSunday', 'vbMonday', 'vbTuesday', 'vbWednesday', 'vbThursday', 'vbFriday', 'vbSaturday', 'vbUseSystemDayOfWeek', 'vbFirstJan1', 'vbFirstFourDays', 'vbFirstFullWeek', 'vbGeneralDate', 'vbLongDate', 'vbShortDate', 'vbLongTime', 'vbShortTime', 'vbObjectError', 'vbOKOnly', 'vbOKCancel', 'vbAbortRetryIgnore', 'vbYesNoCancel', 'vbYesNo', 'vbRetryCancel', 'vbCritical', 'vbQuestion', 'vbExclamation', 'vbInformation', 'vbDefaultButton1', 'vbDefaultButton2', 'vbDefaultButton3', 'vbDefaultButton4', 'vbApplicationModal', 'vbSystemModal', 'vbOK', 'vbCancel', 'vbAbort', 'vbRetry', 'vbIgnore', 'vbYes', 'vbNo', 'vbCr', 'VbCrLf', 'vbFormFeed', 'vbLf', 'vbNewLine', 'vbNullChar', 'vbNullString', 'vbTab', 'vbVerticalTab', 'vbUseDefault', 'vbTrue', 'vbFalse', 'vbEmpty', 'vbNull', 'vbInteger', 'vbLong', 'vbSingle', 'vbDouble', 'vbCurrency', 'vbDate', 'vbString', 'vbObject', 'vbError', 'vbBoolean', 'vbVariant', 'vbDataObject', 'vbDecimal', 'vbByte', 'vbArray']; //This list was from: http://msdn.microsoft.com/en-us/library/hkc375ea(v=vs.84).aspx var builtinObjsWords = ['WScript', 'err', 'debug', 'RegExp']; var knownProperties = ['description', 'firstindex', 'global', 'helpcontext', 'helpfile', 'ignorecase', 'length', 'number', 'pattern', 'source', 'value', 'count']; var knownMethods = ['clear', 'execute', 'raise', 'replace', 'test', 'write', 'writeline', 'close', 'open', 'state', 'eof', 'update', 'addnew', 'end', 'createobject', 'quit']; var aspBuiltinObjsWords = ['server', 'response', 'request', 'session', 'application']; var aspKnownProperties = ['buffer', 'cachecontrol', 'charset', 'contenttype', 'expires', 'expiresabsolute', 'isclientconnected', 'pics', 'status', //response 'clientcertificate', 'cookies', 'form', 'querystring', 'servervariables', 'totalbytes', //request 'contents', 'staticobjects', //application 'codepage', 'lcid', 'sessionid', 'timeout', //session 'scripttimeout']; //server var aspKnownMethods = ['addheader', 'appendtolog', 'binarywrite', 'end', 'flush', 'redirect', //response 'binaryread', //request 'remove', 'removeall', 'lock', 'unlock', //application 'abandon', //session 'getlasterror', 'htmlencode', 'mappath', 'transfer', 'urlencode']; //server var knownWords = knownMethods.concat(knownProperties); builtinObjsWords = builtinObjsWords.concat(builtinConsts); if (conf.isASP){ builtinObjsWords = builtinObjsWords.concat(aspBuiltinObjsWords); knownWords = knownWords.concat(aspKnownMethods, aspKnownProperties); }; var keywords = wordRegexp(commonkeywords); var atoms = wordRegexp(atomWords); var builtinFuncs = wordRegexp(builtinFuncsWords); var builtinObjs = wordRegexp(builtinObjsWords); var known = wordRegexp(knownWords); var stringPrefixes = '"'; var opening = wordRegexp(openingKeywords); var middle = wordRegexp(middleKeywords); var closing = wordRegexp(endKeywords); var doubleClosing = wordRegexp(['end']); var doOpening = wordRegexp(['do']); var noIndentWords = wordRegexp(['on error resume next', 'exit']); var comment = wordRegexp(['rem']); function indent(_stream, state) { state.currentIndent++; } function dedent(_stream, state) { state.currentIndent--; } // tokenizers function tokenBase(stream, state) { if (stream.eatSpace()) { return 'space'; //return null; } var ch = stream.peek(); // Handle Comments if (ch === "'") { stream.skipToEnd(); return 'comment'; } if (stream.match(comment)){ stream.skipToEnd(); return 'comment'; } // Handle Number Literals if (stream.match(/^((&H)|(&O))?[0-9\.]/i, false) && !stream.match(/^((&H)|(&O))?[0-9\.]+[a-z_]/i, false)) { var floatLiteral = false; // Floats if (stream.match(/^\d*\.\d+/i)) { floatLiteral = true; } else if (stream.match(/^\d+\.\d*/)) { floatLiteral = true; } else if (stream.match(/^\.\d+/)) { floatLiteral = true; } if (floatLiteral) { // Float literals may be "imaginary" stream.eat(/J/i); return 'number'; } // Integers var intLiteral = false; // Hex if (stream.match(/^&H[0-9a-f]+/i)) { intLiteral = true; } // Octal else if (stream.match(/^&O[0-7]+/i)) { intLiteral = true; } // Decimal else if (stream.match(/^[1-9]\d*F?/)) { // Decimal literals may be "imaginary" stream.eat(/J/i); // TODO - Can you have imaginary longs? intLiteral = true; } // Zero by itself with no other piece of number. else if (stream.match(/^0(?![\dx])/i)) { intLiteral = true; } if (intLiteral) { // Integer literals may be "long" stream.eat(/L/i); return 'number'; } } // Handle Strings if (stream.match(stringPrefixes)) { state.tokenize = tokenStringFactory(stream.current()); return state.tokenize(stream, state); } // Handle operators and Delimiters if (stream.match(doubleOperators) || stream.match(singleOperators) || stream.match(wordOperators)) { return 'operator'; } if (stream.match(singleDelimiters)) { return null; } if (stream.match(brakets)) { return "bracket"; } if (stream.match(noIndentWords)) { state.doInCurrentLine = true; return 'keyword'; } if (stream.match(doOpening)) { indent(stream,state); state.doInCurrentLine = true; return 'keyword'; } if (stream.match(opening)) { if (! state.doInCurrentLine) indent(stream,state); else state.doInCurrentLine = false; return 'keyword'; } if (stream.match(middle)) { return 'keyword'; } if (stream.match(doubleClosing)) { dedent(stream,state); dedent(stream,state); return 'keyword'; } if (stream.match(closing)) { if (! state.doInCurrentLine) dedent(stream,state); else state.doInCurrentLine = false; return 'keyword'; } if (stream.match(keywords)) { return 'keyword'; } if (stream.match(atoms)) { return 'atom'; } if (stream.match(known)) { return 'variable-2'; } if (stream.match(builtinFuncs)) { return 'builtin'; } if (stream.match(builtinObjs)){ return 'variable-2'; } if (stream.match(identifiers)) { return 'variable'; } // Handle non-detected items stream.next(); return ERRORCLASS; } function tokenStringFactory(delimiter) { var singleline = delimiter.length == 1; var OUTCLASS = 'string'; return function(stream, state) { while (!stream.eol()) { stream.eatWhile(/[^'"]/); if (stream.match(delimiter)) { state.tokenize = tokenBase; return OUTCLASS; } else { stream.eat(/['"]/); } } if (singleline) { if (parserConf.singleLineStringErrors) { return ERRORCLASS; } else { state.tokenize = tokenBase; } } return OUTCLASS; }; } function tokenLexer(stream, state) { var style = state.tokenize(stream, state); var current = stream.current(); // Handle '.' connected identifiers if (current === '.') { style = state.tokenize(stream, state); current = stream.current(); if (style && (style.substr(0, 8) === 'variable' || style==='builtin' || style==='keyword')){//|| knownWords.indexOf(current.substring(1)) > -1) { if (style === 'builtin' || style === 'keyword') style='variable'; if (knownWords.indexOf(current.substr(1)) > -1) style='variable-2'; return style; } else { return ERRORCLASS; } } return style; } var external = { electricChars:"dDpPtTfFeE ", startState: function() { return { tokenize: tokenBase, lastToken: null, currentIndent: 0, nextLineIndent: 0, doInCurrentLine: false, ignoreKeyword: false }; }, token: function(stream, state) { if (stream.sol()) { state.currentIndent += state.nextLineIndent; state.nextLineIndent = 0; state.doInCurrentLine = 0; } var style = tokenLexer(stream, state); state.lastToken = {style:style, content: stream.current()}; if (style==='space') style=null; return style; }, indent: function(state, textAfter) { var trueText = textAfter.replace(/^\s+|\s+$/g, '') ; if (trueText.match(closing) || trueText.match(doubleClosing) || trueText.match(middle)) return conf.indentUnit*(state.currentIndent-1); if(state.currentIndent < 0) return 0; return state.currentIndent * conf.indentUnit; } }; return external; }); CodeMirror.defineMIME("text/vbscript", "vbscript"); }); ================================================ FILE: third_party/CodeMirror/mode/velocity/index.html ================================================ CodeMirror: Velocity mode

    Velocity mode

    MIME types defined: text/velocity.

    ================================================ FILE: third_party/CodeMirror/mode/velocity/velocity.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("velocity", function() { function parseWords(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var keywords = parseWords("#end #else #break #stop #[[ #]] " + "#{end} #{else} #{break} #{stop}"); var functions = parseWords("#if #elseif #foreach #set #include #parse #macro #define #evaluate " + "#{if} #{elseif} #{foreach} #{set} #{include} #{parse} #{macro} #{define} #{evaluate}"); 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"); var isOperatorChar = /[+\-*&%=<>!?:\/|]/; function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } function tokenBase(stream, state) { var beforeParams = state.beforeParams; state.beforeParams = false; var ch = stream.next(); // start of unparsed string? if ((ch == "'") && !state.inString && state.inParams) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenString(ch)); } // start of parsed string? else if ((ch == '"')) { state.lastTokenWasBuiltin = false; if (state.inString) { state.inString = false; return "string"; } else if (state.inParams) return chain(stream, state, tokenString(ch)); } // is it one of the special signs []{}().,;? Seperator? else if (/[\[\]{}\(\),;\.]/.test(ch)) { if (ch == "(" && beforeParams) state.inParams = true; else if (ch == ")") { state.inParams = false; state.lastTokenWasBuiltin = true; } return null; } // start of a number value? else if (/\d/.test(ch)) { state.lastTokenWasBuiltin = false; stream.eatWhile(/[\w\.]/); return "number"; } // multi line comment? else if (ch == "#" && stream.eat("*")) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenComment); } // unparsed content? else if (ch == "#" && stream.match(/ *\[ *\[/)) { state.lastTokenWasBuiltin = false; return chain(stream, state, tokenUnparsed); } // single line comment? else if (ch == "#" && stream.eat("#")) { state.lastTokenWasBuiltin = false; stream.skipToEnd(); return "comment"; } // variable? else if (ch == "$") { stream.eatWhile(/[\w\d\$_\.{}-]/); // is it one of the specials? if (specials && specials.propertyIsEnumerable(stream.current())) { return "keyword"; } else { state.lastTokenWasBuiltin = true; state.beforeParams = true; return "builtin"; } } // is it a operator? else if (isOperatorChar.test(ch)) { state.lastTokenWasBuiltin = false; stream.eatWhile(isOperatorChar); return "operator"; } else { // get the whole word stream.eatWhile(/[\w\$_{}@]/); var word = stream.current(); // is it one of the listed keywords? if (keywords && keywords.propertyIsEnumerable(word)) return "keyword"; // is it one of the listed functions? if (functions && functions.propertyIsEnumerable(word) || (stream.current().match(/^#@?[a-z0-9_]+ *$/i) && stream.peek()=="(") && !(functions && functions.propertyIsEnumerable(word.toLowerCase()))) { state.beforeParams = true; state.lastTokenWasBuiltin = false; return "keyword"; } if (state.inString) { state.lastTokenWasBuiltin = false; return "string"; } if (stream.pos > word.length && stream.string.charAt(stream.pos-word.length-1)=="." && state.lastTokenWasBuiltin) return "builtin"; // default: just a "word" state.lastTokenWasBuiltin = false; return null; } } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if ((next == quote) && !escaped) { end = true; break; } if (quote=='"' && stream.peek() == '$' && !escaped) { state.inString = true; end = true; break; } escaped = !escaped && next == "\\"; } if (end) state.tokenize = tokenBase; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function tokenUnparsed(stream, state) { var maybeEnd = 0, ch; while (ch = stream.next()) { if (ch == "#" && maybeEnd == 2) { state.tokenize = tokenBase; break; } if (ch == "]") maybeEnd++; else if (ch != " ") maybeEnd = 0; } return "meta"; } // Interface return { startState: function() { return { tokenize: tokenBase, beforeParams: false, inParams: false, inString: false, lastTokenWasBuiltin: false }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, blockCommentStart: "#*", blockCommentEnd: "*#", lineComment: "##", fold: "velocity" }; }); CodeMirror.defineMIME("text/velocity", "velocity"); }); ================================================ FILE: third_party/CodeMirror/mode/verilog/index.html ================================================ CodeMirror: Verilog/SystemVerilog mode

    SystemVerilog mode

    Syntax highlighting and indentation for the Verilog and SystemVerilog languages (IEEE 1800).

    Configuration options:

    • noIndentKeywords - List of keywords which should not cause indentation to increase. E.g. ["package", "module"]. Default: None

    MIME types defined: text/x-verilog and text/x-systemverilog.

    ================================================ FILE: third_party/CodeMirror/mode/verilog/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 4}, "verilog"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("binary_literals", "[number 1'b0]", "[number 1'b1]", "[number 1'bx]", "[number 1'bz]", "[number 1'bX]", "[number 1'bZ]", "[number 1'B0]", "[number 1'B1]", "[number 1'Bx]", "[number 1'Bz]", "[number 1'BX]", "[number 1'BZ]", "[number 1'b0]", "[number 1'b1]", "[number 2'b01]", "[number 2'bxz]", "[number 2'b11]", "[number 2'b10]", "[number 2'b1Z]", "[number 12'b0101_0101_0101]", "[number 1'b 0]", "[number 'b0101]" ); MT("octal_literals", "[number 3'o7]", "[number 3'O7]", "[number 3'so7]", "[number 3'SO7]" ); MT("decimal_literals", "[number 0]", "[number 1]", "[number 7]", "[number 123_456]", "[number 'd33]", "[number 8'd255]", "[number 8'D255]", "[number 8'sd255]", "[number 8'SD255]", "[number 32'd123]", "[number 32 'd123]", "[number 32 'd 123]" ); MT("hex_literals", "[number 4'h0]", "[number 4'ha]", "[number 4'hF]", "[number 4'hx]", "[number 4'hz]", "[number 4'hX]", "[number 4'hZ]", "[number 32'hdc78]", "[number 32'hDC78]", "[number 32 'hDC78]", "[number 32'h DC78]", "[number 32 'h DC78]", "[number 32'h44x7]", "[number 32'hFFF?]" ); MT("real_number_literals", "[number 1.2]", "[number 0.1]", "[number 2394.26331]", "[number 1.2E12]", "[number 1.2e12]", "[number 1.30e-2]", "[number 0.1e-0]", "[number 23E10]", "[number 29E-2]", "[number 236.123_763_e-12]" ); MT("operators", "[meta ^]" ); MT("keywords", "[keyword logic]", "[keyword logic] [variable foo]", "[keyword reg] [variable abc]" ); MT("variables", "[variable _leading_underscore]", "[variable _if]", "[number 12] [variable foo]", "[variable foo] [number 14]" ); MT("tick_defines", "[def `FOO]", "[def `foo]", "[def `FOO_bar]" ); MT("system_calls", "[meta $display]", "[meta $vpi_printf]" ); MT("line_comment", "[comment // Hello world]"); // Alignment tests MT("align_port_map_style1", /** * mod mod(.a(a), * .b(b) * ); */ "[variable mod] [variable mod][bracket (].[variable a][bracket (][variable a][bracket )],", " .[variable b][bracket (][variable b][bracket )]", " [bracket )];", "" ); MT("align_port_map_style2", /** * mod mod( * .a(a), * .b(b) * ); */ "[variable mod] [variable mod][bracket (]", " .[variable a][bracket (][variable a][bracket )],", " .[variable b][bracket (][variable b][bracket )]", "[bracket )];", "" ); // Indentation tests MT("indent_single_statement_if", "[keyword if] [bracket (][variable foo][bracket )]", " [keyword break];", "" ); MT("no_indent_after_single_line_if", "[keyword if] [bracket (][variable foo][bracket )] [keyword break];", "" ); MT("indent_after_if_begin_same_line", "[keyword if] [bracket (][variable foo][bracket )] [keyword begin]", " [keyword break];", " [keyword break];", "[keyword end]", "" ); MT("indent_after_if_begin_next_line", "[keyword if] [bracket (][variable foo][bracket )]", " [keyword begin]", " [keyword break];", " [keyword break];", " [keyword end]", "" ); MT("indent_single_statement_if_else", "[keyword if] [bracket (][variable foo][bracket )]", " [keyword break];", "[keyword else]", " [keyword break];", "" ); MT("indent_if_else_begin_same_line", "[keyword if] [bracket (][variable foo][bracket )] [keyword begin]", " [keyword break];", " [keyword break];", "[keyword end] [keyword else] [keyword begin]", " [keyword break];", " [keyword break];", "[keyword end]", "" ); MT("indent_if_else_begin_next_line", "[keyword if] [bracket (][variable foo][bracket )]", " [keyword begin]", " [keyword break];", " [keyword break];", " [keyword end]", "[keyword else]", " [keyword begin]", " [keyword break];", " [keyword break];", " [keyword end]", "" ); MT("indent_if_nested_without_begin", "[keyword if] [bracket (][variable foo][bracket )]", " [keyword if] [bracket (][variable foo][bracket )]", " [keyword if] [bracket (][variable foo][bracket )]", " [keyword break];", "" ); MT("indent_case", "[keyword case] [bracket (][variable state][bracket )]", " [variable FOO]:", " [keyword break];", " [variable BAR]:", " [keyword break];", "[keyword endcase]", "" ); MT("unindent_after_end_with_preceding_text", "[keyword begin]", " [keyword break]; [keyword end]", "" ); MT("export_function_one_line_does_not_indent", "[keyword export] [string \"DPI-C\"] [keyword function] [variable helloFromSV];", "" ); MT("export_task_one_line_does_not_indent", "[keyword export] [string \"DPI-C\"] [keyword task] [variable helloFromSV];", "" ); MT("export_function_two_lines_indents_properly", "[keyword export]", " [string \"DPI-C\"] [keyword function] [variable helloFromSV];", "" ); MT("export_task_two_lines_indents_properly", "[keyword export]", " [string \"DPI-C\"] [keyword task] [variable helloFromSV];", "" ); MT("import_function_one_line_does_not_indent", "[keyword import] [string \"DPI-C\"] [keyword function] [variable helloFromC];", "" ); MT("import_task_one_line_does_not_indent", "[keyword import] [string \"DPI-C\"] [keyword task] [variable helloFromC];", "" ); MT("import_package_single_line_does_not_indent", "[keyword import] [variable p]::[variable x];", "[keyword import] [variable p]::[variable y];", "" ); MT("covergroup_with_function_indents_properly", "[keyword covergroup] [variable cg] [keyword with] [keyword function] [variable sample][bracket (][keyword bit] [variable b][bracket )];", " [variable c] : [keyword coverpoint] [variable c];", "[keyword endgroup]: [variable cg]", "" ); })(); ================================================ FILE: third_party/CodeMirror/mode/verilog/verilog.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("verilog", function(config, parserConfig) { var indentUnit = config.indentUnit, statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, dontAlignCalls = parserConfig.dontAlignCalls, noIndentKeywords = parserConfig.noIndentKeywords || [], multiLineStrings = parserConfig.multiLineStrings, hooks = parserConfig.hooks || {}; function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } /** * Keywords from IEEE 1800-2012 */ var keywords = words( "accept_on alias always always_comb always_ff always_latch and assert assign assume automatic before begin bind " + "bins binsof bit break buf bufif0 bufif1 byte case casex casez cell chandle checker class clocking cmos config " + "const constraint context continue cover covergroup coverpoint cross deassign default defparam design disable " + "dist do edge else end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup " + "endinterface endmodule endpackage endprimitive endprogram endproperty endspecify endsequence endtable endtask " + "enum event eventually expect export extends extern final first_match for force foreach forever fork forkjoin " + "function generate genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import " + "incdir include initial inout input inside instance int integer interconnect interface intersect join join_any " + "join_none large let liblist library local localparam logic longint macromodule matches medium modport module " + "nand negedge nettype new nexttime nmos nor noshowcancelled not notif0 notif1 null or output package packed " + "parameter pmos posedge primitive priority program property protected pull0 pull1 pulldown pullup " + "pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos real realtime ref reg " + "reject_on release repeat restrict return rnmos rpmos rtran rtranif0 rtranif1 s_always s_eventually s_nexttime " + "s_until s_until_with scalared sequence shortint shortreal showcancelled signed small soft solve specify " + "specparam static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on sync_reject_on " + "table tagged task this throughout time timeprecision timeunit tran tranif0 tranif1 tri tri0 tri1 triand trior " + "trireg type typedef union unique unique0 unsigned until until_with untyped use uwire var vectored virtual void " + "wait wait_order wand weak weak0 weak1 while wildcard wire with within wor xnor xor"); /** Operators from IEEE 1800-2012 unary_operator ::= + | - | ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~ binary_operator ::= + | - | * | / | % | == | != | === | !== | ==? | !=? | && | || | ** | < | <= | > | >= | & | | | ^ | ^~ | ~^ | >> | << | >>> | <<< | -> | <-> inc_or_dec_operator ::= ++ | -- unary_module_path_operator ::= ! | ~ | & | ~& | | | ~| | ^ | ~^ | ^~ binary_module_path_operator ::= == | != | && | || | & | | | ^ | ^~ | ~^ */ var isOperatorChar = /[\+\-\*\/!~&|^%=?:]/; var isBracketChar = /[\[\]{}()]/; var unsignedNumber = /\d[0-9_]*/; var decimalLiteral = /\d*\s*'s?d\s*\d[0-9_]*/i; var binaryLiteral = /\d*\s*'s?b\s*[xz01][xz01_]*/i; var octLiteral = /\d*\s*'s?o\s*[xz0-7][xz0-7_]*/i; var hexLiteral = /\d*\s*'s?h\s*[0-9a-fxz?][0-9a-fxz?_]*/i; var realLiteral = /(\d[\d_]*(\.\d[\d_]*)?E-?[\d_]+)|(\d[\d_]*\.\d[\d_]*)/i; var closingBracketOrWord = /^((\w+)|[)}\]])/; var closingBracket = /[)}\]]/; var curPunc; var curKeyword; // Block openings which are closed by a matching keyword in the form of ("end" + keyword) // E.g. "task" => "endtask" var blockKeywords = words( "case checker class clocking config function generate interface module package " + "primitive program property specify sequence table task" ); // Opening/closing pairs var openClose = {}; for (var keyword in blockKeywords) { openClose[keyword] = "end" + keyword; } openClose["begin"] = "end"; openClose["casex"] = "endcase"; openClose["casez"] = "endcase"; openClose["do" ] = "while"; openClose["fork" ] = "join;join_any;join_none"; openClose["covergroup"] = "endgroup"; for (var i in noIndentKeywords) { var keyword = noIndentKeywords[i]; if (openClose[keyword]) { openClose[keyword] = undefined; } } // Keywords which open statements that are ended with a semi-colon var statementKeywords = words("always always_comb always_ff always_latch assert assign assume else export for foreach forever if import initial repeat while"); function tokenBase(stream, state) { var ch = stream.peek(), style; if (hooks[ch] && (style = hooks[ch](stream, state)) != false) return style; if (hooks.tokenBase && (style = hooks.tokenBase(stream, state)) != false) return style; if (/[,;:\.]/.test(ch)) { curPunc = stream.next(); return null; } if (isBracketChar.test(ch)) { curPunc = stream.next(); return "bracket"; } // Macros (tick-defines) if (ch == '`') { stream.next(); if (stream.eatWhile(/[\w\$_]/)) { return "def"; } else { return null; } } // System calls if (ch == '$') { stream.next(); if (stream.eatWhile(/[\w\$_]/)) { return "meta"; } else { return null; } } // Time literals if (ch == '#') { stream.next(); stream.eatWhile(/[\d_.]/); return "def"; } // Strings if (ch == '"') { stream.next(); state.tokenize = tokenString(ch); return state.tokenize(stream, state); } // Comments if (ch == "/") { stream.next(); if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } stream.backUp(1); } // Numeric literals if (stream.match(realLiteral) || stream.match(decimalLiteral) || stream.match(binaryLiteral) || stream.match(octLiteral) || stream.match(hexLiteral) || stream.match(unsignedNumber) || stream.match(realLiteral)) { return "number"; } // Operators if (stream.eatWhile(isOperatorChar)) { return "meta"; } // Keywords / plain variables if (stream.eatWhile(/[\w\$_]/)) { var cur = stream.current(); if (keywords[cur]) { if (openClose[cur]) { curPunc = "newblock"; } if (statementKeywords[cur]) { curPunc = "newstatement"; } curKeyword = cur; return "keyword"; } return "variable"; } stream.next(); return null; } function tokenString(quote) { return function(stream, state) { var escaped = false, next, end = false; while ((next = stream.next()) != null) { if (next == quote && !escaped) {end = true; break;} escaped = !escaped && next == "\\"; } if (end || !(escaped || multiLineStrings)) state.tokenize = tokenBase; return "string"; }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return "comment"; } function Context(indented, column, type, align, prev) { this.indented = indented; this.column = column; this.type = type; this.align = align; this.prev = prev; } function pushContext(state, col, type) { var indent = state.indented; var c = new Context(indent, col, type, null, state.context); return state.context = c; } function popContext(state) { var t = state.context.type; if (t == ")" || t == "]" || t == "}") { state.indented = state.context.indented; } return state.context = state.context.prev; } function isClosing(text, contextClosing) { if (text == contextClosing) { return true; } else { // contextClosing may be multiple keywords separated by ; var closingKeywords = contextClosing.split(";"); for (var i in closingKeywords) { if (text == closingKeywords[i]) { return true; } } return false; } } function buildElectricInputRegEx() { // Reindentation should occur on any bracket char: {}()[] // or on a match of any of the block closing keywords, at // the end of a line var allClosings = []; for (var i in openClose) { if (openClose[i]) { var closings = openClose[i].split(";"); for (var j in closings) { allClosings.push(closings[j]); } } } var re = new RegExp("[{}()\\[\\]]|(" + allClosings.join("|") + ")$"); return re; } // Interface return { // Regex to force current line to reindent electricInput: buildElectricInputRegEx(), startState: function(basecolumn) { var state = { tokenize: null, context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), indented: 0, startOfLine: true }; if (hooks.startState) hooks.startState(state); return state; }, token: function(stream, state) { var ctx = state.context; if (stream.sol()) { if (ctx.align == null) ctx.align = false; state.indented = stream.indentation(); state.startOfLine = true; } if (hooks.token) { // Call hook, with an optional return value of a style to override verilog styling. var style = hooks.token(stream, state); if (style !== undefined) { return style; } } if (stream.eatSpace()) return null; curPunc = null; curKeyword = null; var style = (state.tokenize || tokenBase)(stream, state); if (style == "comment" || style == "meta" || style == "variable") return style; if (ctx.align == null) ctx.align = true; if (curPunc == ctx.type) { popContext(state); } else if ((curPunc == ";" && ctx.type == "statement") || (ctx.type && isClosing(curKeyword, ctx.type))) { ctx = popContext(state); while (ctx && ctx.type == "statement") ctx = popContext(state); } else if (curPunc == "{") { pushContext(state, stream.column(), "}"); } else if (curPunc == "[") { pushContext(state, stream.column(), "]"); } else if (curPunc == "(") { pushContext(state, stream.column(), ")"); } else if (ctx && ctx.type == "endcase" && curPunc == ":") { pushContext(state, stream.column(), "statement"); } else if (curPunc == "newstatement") { pushContext(state, stream.column(), "statement"); } else if (curPunc == "newblock") { if (curKeyword == "function" && ctx && (ctx.type == "statement" || ctx.type == "endgroup")) { // The 'function' keyword can appear in some other contexts where it actually does not // indicate a function (import/export DPI and covergroup definitions). // Do nothing in this case } else if (curKeyword == "task" && ctx && ctx.type == "statement") { // Same thing for task } else { var close = openClose[curKeyword]; pushContext(state, stream.column(), close); } } state.startOfLine = false; return style; }, indent: function(state, textAfter) { if (state.tokenize != tokenBase && state.tokenize != null) return CodeMirror.Pass; if (hooks.indent) { var fromHook = hooks.indent(state); if (fromHook >= 0) return fromHook; } var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; var closing = false; var possibleClosing = textAfter.match(closingBracketOrWord); if (possibleClosing) closing = isClosing(possibleClosing[0], ctx.type); if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); else if (closingBracket.test(ctx.type) && ctx.align && !dontAlignCalls) return ctx.column + (closing ? 0 : 1); else if (ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; else return ctx.indented + (closing ? 0 : indentUnit); }, blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); CodeMirror.defineMIME("text/x-verilog", { name: "verilog" }); CodeMirror.defineMIME("text/x-systemverilog", { name: "verilog" }); // TL-Verilog mode. // See tl-x.org for language spec. // See the mode in action at makerchip.com. // Contact: steve.hoover@redwoodeda.com // TLV Identifier prefixes. // Note that sign is not treated separately, so "+/-" versions of numeric identifiers // are included. var tlvIdentifierStyle = { "|": "link", ">": "property", // Should condition this off for > TLV 1c. "$": "variable", "$$": "variable", "?$": "qualifier", "?*": "qualifier", "-": "hr", "/": "property", "/-": "property", "@": "variable-3", "@-": "variable-3", "@++": "variable-3", "@+=": "variable-3", "@+=-": "variable-3", "@--": "variable-3", "@-=": "variable-3", "%+": "tag", "%-": "tag", "%": "tag", ">>": "tag", "<<": "tag", "<>": "tag", "#": "tag", // Need to choose a style for this. "^": "attribute", "^^": "attribute", "^!": "attribute", "*": "variable-2", "**": "variable-2", "\\": "keyword", "\"": "comment" }; // Lines starting with these characters define scope (result in indentation). var tlvScopePrefixChars = { "/": "beh-hier", ">": "beh-hier", "-": "phys-hier", "|": "pipe", "?": "when", "@": "stage", "\\": "keyword" }; var tlvIndentUnit = 3; var tlvTrackStatements = false; var tlvIdentMatch = /^([~!@#\$%\^&\*-\+=\?\/\\\|'"<>]+)([\d\w_]*)/; // Matches an identifiere. // Note that ':' is excluded, because of it's use in [:]. var tlvFirstLevelIndentMatch = /^[! ] /; var tlvLineIndentationMatch = /^[! ] */; var tlvCommentMatch = /^\/[\/\*]/; // Returns a style specific to the scope at the given indentation column. // Type is one of: "indent", "scope-ident", "before-scope-ident". function tlvScopeStyle(state, indentation, type) { // Begin scope. var depth = indentation / tlvIndentUnit; // TODO: Pass this in instead. return "tlv-" + state.tlvIndentationStyle[depth] + "-" + type; } // Return true if the next thing in the stream is an identifier with a mnemonic. function tlvIdentNext(stream) { var match; return (match = stream.match(tlvIdentMatch, false)) && match[2].length > 0; } CodeMirror.defineMIME("text/x-tlv", { name: "verilog", hooks: { electricInput: false, // Return undefined for verilog tokenizing, or style for TLV token (null not used). // Standard CM styles are used for most formatting, but some TL-Verilog-specific highlighting // can be enabled with the definition of cm-tlv-* styles, including highlighting for: // - M4 tokens // - TLV scope indentation // - Statement delimitation (enabled by tlvTrackStatements) token: function(stream, state) { var style = undefined; var match; // Return value of pattern matches. // Set highlighting mode based on code region (TLV or SV). if (stream.sol() && ! state.tlvInBlockComment) { // Process region. if (stream.peek() == '\\') { style = "def"; stream.skipToEnd(); if (stream.string.match(/\\SV/)) { state.tlvCodeActive = false; } else if (stream.string.match(/\\TLV/)){ state.tlvCodeActive = true; } } // Correct indentation in the face of a line prefix char. if (state.tlvCodeActive && stream.pos == 0 && (state.indented == 0) && (match = stream.match(tlvLineIndentationMatch, false))) { state.indented = match[0].length; } // Compute indentation state: // o Auto indentation on next line // o Indentation scope styles var indented = state.indented; var depth = indented / tlvIndentUnit; if (depth <= state.tlvIndentationStyle.length) { // not deeper than current scope var blankline = stream.string.length == indented; var chPos = depth * tlvIndentUnit; if (chPos < stream.string.length) { var bodyString = stream.string.slice(chPos); var ch = bodyString[0]; if (tlvScopePrefixChars[ch] && ((match = bodyString.match(tlvIdentMatch)) && tlvIdentifierStyle[match[1]])) { // This line begins scope. // Next line gets indented one level. indented += tlvIndentUnit; // Style the next level of indentation (except non-region keyword identifiers, // which are statements themselves) if (!(ch == "\\" && chPos > 0)) { state.tlvIndentationStyle[depth] = tlvScopePrefixChars[ch]; if (tlvTrackStatements) {state.statementComment = false;} depth++; } } } // Clear out deeper indentation levels unless line is blank. if (!blankline) { while (state.tlvIndentationStyle.length > depth) { state.tlvIndentationStyle.pop(); } } } // Set next level of indentation. state.tlvNextIndent = indented; } if (state.tlvCodeActive) { // Highlight as TLV. var beginStatement = false; if (tlvTrackStatements) { // This starts a statement if the position is at the scope level // and we're not within a statement leading comment. beginStatement = (stream.peek() != " ") && // not a space (style === undefined) && // not a region identifier !state.tlvInBlockComment && // not in block comment //!stream.match(tlvCommentMatch, false) && // not comment start (stream.column() == state.tlvIndentationStyle.length * tlvIndentUnit); // at scope level if (beginStatement) { if (state.statementComment) { // statement already started by comment beginStatement = false; } state.statementComment = stream.match(tlvCommentMatch, false); // comment start } } var match; if (style !== undefined) { // Region line. style += " " + tlvScopeStyle(state, 0, "scope-ident") } else if (((stream.pos / tlvIndentUnit) < state.tlvIndentationStyle.length) && (match = stream.match(stream.sol() ? tlvFirstLevelIndentMatch : /^ /))) { // Indentation style = // make this style distinct from the previous one to prevent // codemirror from combining spans "tlv-indent-" + (((stream.pos % 2) == 0) ? "even" : "odd") + // and style it " " + tlvScopeStyle(state, stream.pos - tlvIndentUnit, "indent"); // Style the line prefix character. if (match[0].charAt(0) == "!") { style += " tlv-alert-line-prefix"; } // Place a class before a scope identifier. if (tlvIdentNext(stream)) { style += " " + tlvScopeStyle(state, stream.pos, "before-scope-ident"); } } else if (state.tlvInBlockComment) { // In a block comment. if (stream.match(/^.*?\*\//)) { // Exit block comment. state.tlvInBlockComment = false; if (tlvTrackStatements && !stream.eol()) { // Anything after comment is assumed to be real statement content. state.statementComment = false; } } else { stream.skipToEnd(); } style = "comment"; } else if ((match = stream.match(tlvCommentMatch)) && !state.tlvInBlockComment) { // Start comment. if (match[0] == "//") { // Line comment. stream.skipToEnd(); } else { // Block comment. state.tlvInBlockComment = true; } style = "comment"; } else if (match = stream.match(tlvIdentMatch)) { // looks like an identifier (or identifier prefix) var prefix = match[1]; var mnemonic = match[2]; if (// is identifier prefix tlvIdentifierStyle.hasOwnProperty(prefix) && // has mnemonic or we're at the end of the line (maybe it hasn't been typed yet) (mnemonic.length > 0 || stream.eol())) { style = tlvIdentifierStyle[prefix]; if (stream.column() == state.indented) { // Begin scope. style += " " + tlvScopeStyle(state, stream.column(), "scope-ident") } } else { // Just swallow one character and try again. // This enables subsequent identifier match with preceding symbol character, which // is legal within a statement. (Eg, !$reset). It also enables detection of // comment start with preceding symbols. stream.backUp(stream.current().length - 1); style = "tlv-default"; } } else if (stream.match(/^\t+/)) { // Highlight tabs, which are illegal. style = "tlv-tab"; } else if (stream.match(/^[\[\]{}\(\);\:]+/)) { // [:], (), {}, ;. style = "meta"; } else if (match = stream.match(/^[mM]4([\+_])?[\w\d_]*/)) { // m4 pre proc style = (match[1] == "+") ? "tlv-m4-plus" : "tlv-m4"; } else if (stream.match(/^ +/)){ // Skip over spaces. if (stream.eol()) { // Trailing spaces. style = "error"; } else { // Non-trailing spaces. style = "tlv-default"; } } else if (stream.match(/^[\w\d_]+/)) { // alpha-numeric token. style = "number"; } else { // Eat the next char w/ no formatting. stream.next(); style = "tlv-default"; } if (beginStatement) { style += " tlv-statement"; } } else { if (stream.match(/^[mM]4([\w\d_]*)/)) { // m4 pre proc style = "tlv-m4"; } } return style; }, indent: function(state) { return (state.tlvCodeActive == true) ? state.tlvNextIndent : -1; }, startState: function(state) { state.tlvIndentationStyle = []; // Styles to use for each level of indentation. state.tlvCodeActive = true; // True when we're in a TLV region (and at beginning of file). state.tlvNextIndent = -1; // The number of spaces to autoindent the next line if tlvCodeActive. state.tlvInBlockComment = false; // True inside /**/ comment. if (tlvTrackStatements) { state.statementComment = false; // True inside a statement's header comment. } } } }); }); ================================================ FILE: third_party/CodeMirror/mode/vhdl/index.html ================================================ CodeMirror: VHDL mode

    VHDL mode

    Syntax highlighting and indentation for the VHDL language.

    Configuration options:

    • atoms - List of atom words. Default: "null"
    • hooks - List of meta hooks. Default: ["`", "$"]
    • multiLineStrings - Whether multi-line strings are accepted. Default: false

    MIME types defined: text/x-vhdl.

    ================================================ FILE: third_party/CodeMirror/mode/vhdl/vhdl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Originally written by Alf Nielsen, re-written by Michael Zhou (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function words(str) { var obj = {}, words = str.split(","); for (var i = 0; i < words.length; ++i) { var allCaps = words[i].toUpperCase(); var firstCap = words[i].charAt(0).toUpperCase() + words[i].slice(1); obj[words[i]] = true; obj[allCaps] = true; obj[firstCap] = true; } return obj; } function metaHook(stream) { stream.eatWhile(/[\w\$_]/); return "meta"; } CodeMirror.defineMode("vhdl", function(config, parserConfig) { var indentUnit = config.indentUnit, atoms = parserConfig.atoms || words("null"), hooks = parserConfig.hooks || {"`": metaHook, "$": metaHook}, multiLineStrings = parserConfig.multiLineStrings; var keywords = words("abs,access,after,alias,all,and,architecture,array,assert,attribute,begin,block," + "body,buffer,bus,case,component,configuration,constant,disconnect,downto,else,elsif,end,end block,end case," + "end component,end for,end generate,end if,end loop,end process,end record,end units,entity,exit,file,for," + "function,generate,generic,generic map,group,guarded,if,impure,in,inertial,inout,is,label,library,linkage," + "literal,loop,map,mod,nand,new,next,nor,null,of,on,open,or,others,out,package,package body,port,port map," + "postponed,procedure,process,pure,range,record,register,reject,rem,report,return,rol,ror,select,severity,signal," + "sla,sll,sra,srl,subtype,then,to,transport,type,unaffected,units,until,use,variable,wait,when,while,with,xnor,xor"); var blockKeywords = words("architecture,entity,begin,case,port,else,elsif,end,for,function,if"); var isOperatorChar = /[&|~> CodeMirror: Vue.js mode

    Vue.js mode

    MIME types defined: text/x-vue

    ================================================ FILE: third_party/CodeMirror/mode/vue/vue.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function (mod) { "use strict"; if (typeof exports === "object" && typeof module === "object") {// CommonJS mod(require("../../lib/codemirror"), require("../../addon/mode/overlay"), require("../xml/xml"), require("../javascript/javascript"), require("../coffeescript/coffeescript"), require("../css/css"), require("../sass/sass"), require("../stylus/stylus"), require("../pug/pug"), require("../handlebars/handlebars")); } else if (typeof define === "function" && define.amd) { // AMD define(["../../lib/codemirror", "../../addon/mode/overlay", "../xml/xml", "../javascript/javascript", "../coffeescript/coffeescript", "../css/css", "../sass/sass", "../stylus/stylus", "../pug/pug", "../handlebars/handlebars"], mod); } else { // Plain browser env mod(CodeMirror); } })(function (CodeMirror) { var tagLanguages = { script: [ ["lang", /coffee(script)?/, "coffeescript"], ["type", /^(?:text|application)\/(?:x-)?coffee(?:script)?$/, "coffeescript"], ["lang", /^babel$/, "javascript"], ["type", /^text\/babel$/, "javascript"], ["type", /^text\/ecmascript-\d+$/, "javascript"] ], style: [ ["lang", /^stylus$/i, "stylus"], ["lang", /^sass$/i, "sass"], ["lang", /^less$/i, "text/x-less"], ["lang", /^scss$/i, "text/x-scss"], ["type", /^(text\/)?(x-)?styl(us)?$/i, "stylus"], ["type", /^text\/sass/i, "sass"], ["type", /^(text\/)?(x-)?scss$/i, "text/x-scss"], ["type", /^(text\/)?(x-)?less$/i, "text/x-less"] ], template: [ ["lang", /^vue-template$/i, "vue"], ["lang", /^pug$/i, "pug"], ["lang", /^handlebars$/i, "handlebars"], ["type", /^(text\/)?(x-)?pug$/i, "pug"], ["type", /^text\/x-handlebars-template$/i, "handlebars"], [null, null, "vue-template"] ] }; CodeMirror.defineMode("vue-template", function (config, parserConfig) { var mustacheOverlay = { token: function (stream) { if (stream.match(/^\{\{.*?\}\}/)) return "meta mustache"; while (stream.next() && !stream.match("{{", false)) {} return null; } }; return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "text/html"), mustacheOverlay); }); CodeMirror.defineMode("vue", function (config) { return CodeMirror.getMode(config, {name: "htmlmixed", tags: tagLanguages}); }, "htmlmixed", "xml", "javascript", "coffeescript", "css", "sass", "stylus", "pug", "handlebars"); CodeMirror.defineMIME("script/x-vue", "vue"); CodeMirror.defineMIME("text/x-vue", "vue"); }); ================================================ FILE: third_party/CodeMirror/mode/webidl/index.html ================================================ CodeMirror: Web IDL mode

    Web IDL mode

    MIME type defined: text/x-webidl.

    ================================================ FILE: third_party/CodeMirror/mode/webidl/webidl.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; function wordRegexp(words) { return new RegExp("^((" + words.join(")|(") + "))\\b"); }; var builtinArray = [ "Clamp", "Constructor", "EnforceRange", "Exposed", "ImplicitThis", "Global", "PrimaryGlobal", "LegacyArrayClass", "LegacyUnenumerableNamedProperties", "LenientThis", "NamedConstructor", "NewObject", "NoInterfaceObject", "OverrideBuiltins", "PutForwards", "Replaceable", "SameObject", "TreatNonObjectAsNull", "TreatNullAs", "EmptyString", "Unforgeable", "Unscopeable" ]; var builtins = wordRegexp(builtinArray); var typeArray = [ "unsigned", "short", "long", // UnsignedIntegerType "unrestricted", "float", "double", // UnrestrictedFloatType "boolean", "byte", "octet", // Rest of PrimitiveType "Promise", // PromiseType "ArrayBuffer", "DataView", "Int8Array", "Int16Array", "Int32Array", "Uint8Array", "Uint16Array", "Uint32Array", "Uint8ClampedArray", "Float32Array", "Float64Array", // BufferRelatedType "ByteString", "DOMString", "USVString", "sequence", "object", "RegExp", "Error", "DOMException", "FrozenArray", // Rest of NonAnyType "any", // Rest of SingleType "void" // Rest of ReturnType ]; var types = wordRegexp(typeArray); var keywordArray = [ "attribute", "callback", "const", "deleter", "dictionary", "enum", "getter", "implements", "inherit", "interface", "iterable", "legacycaller", "maplike", "partial", "required", "serializer", "setlike", "setter", "static", "stringifier", "typedef", // ArgumentNameKeyword except // "unrestricted" "optional", "readonly", "or" ]; var keywords = wordRegexp(keywordArray); var atomArray = [ "true", "false", // BooleanLiteral "Infinity", "NaN", // FloatLiteral "null" // Rest of ConstValue ]; var atoms = wordRegexp(atomArray); CodeMirror.registerHelper("hintWords", "webidl", builtinArray.concat(typeArray).concat(keywordArray).concat(atomArray)); var startDefArray = ["callback", "dictionary", "enum", "interface"]; var startDefs = wordRegexp(startDefArray); var endDefArray = ["typedef"]; var endDefs = wordRegexp(endDefArray); var singleOperators = /^[:<=>?]/; var integers = /^-?([1-9][0-9]*|0[Xx][0-9A-Fa-f]+|0[0-7]*)/; var floats = /^-?(([0-9]+\.[0-9]*|[0-9]*\.[0-9]+)([Ee][+-]?[0-9]+)?|[0-9]+[Ee][+-]?[0-9]+)/; var identifiers = /^_?[A-Za-z][0-9A-Z_a-z-]*/; var identifiersEnd = /^_?[A-Za-z][0-9A-Z_a-z-]*(?=\s*;)/; var strings = /^"[^"]*"/; var multilineComments = /^\/\*.*?\*\//; var multilineCommentsStart = /^\/\*.*/; var multilineCommentsEnd = /^.*?\*\//; function readToken(stream, state) { // whitespace if (stream.eatSpace()) return null; // comment if (state.inComment) { if (stream.match(multilineCommentsEnd)) { state.inComment = false; return "comment"; } stream.skipToEnd(); return "comment"; } if (stream.match("//")) { stream.skipToEnd(); return "comment"; } if (stream.match(multilineComments)) return "comment"; if (stream.match(multilineCommentsStart)) { state.inComment = true; return "comment"; } // integer and float if (stream.match(/^-?[0-9\.]/, false)) { if (stream.match(integers) || stream.match(floats)) return "number"; } // string if (stream.match(strings)) return "string"; // identifier if (state.startDef && stream.match(identifiers)) return "def"; if (state.endDef && stream.match(identifiersEnd)) { state.endDef = false; return "def"; } if (stream.match(keywords)) return "keyword"; if (stream.match(types)) { var lastToken = state.lastToken; var nextToken = (stream.match(/^\s*(.+?)\b/, false) || [])[1]; if (lastToken === ":" || lastToken === "implements" || nextToken === "implements" || nextToken === "=") { // Used as identifier return "builtin"; } else { // Used as type return "variable-3"; } } if (stream.match(builtins)) return "builtin"; if (stream.match(atoms)) return "atom"; if (stream.match(identifiers)) return "variable"; // other if (stream.match(singleOperators)) return "operator"; // unrecognized stream.next(); return null; }; CodeMirror.defineMode("webidl", function() { return { startState: function() { return { // Is in multiline comment inComment: false, // Last non-whitespace, matched token lastToken: "", // Next token is a definition startDef: false, // Last token of the statement is a definition endDef: false }; }, token: function(stream, state) { var style = readToken(stream, state); if (style) { var cur = stream.current(); state.lastToken = cur; if (style === "keyword") { state.startDef = startDefs.test(cur); state.endDef = state.endDef || endDefs.test(cur); } else { state.startDef = false; } } return style; } }; }); CodeMirror.defineMIME("text/x-webidl", "webidl"); }); ================================================ FILE: third_party/CodeMirror/mode/xml/index.html ================================================ CodeMirror: XML mode

    XML mode

    The XML mode supports these configuration parameters:

    htmlMode (boolean)
    This switches the mode to parse HTML instead of XML. This means attributes do not have to be quoted, and some elements (such as br) do not require a closing tag.
    matchClosing (boolean)
    Controls whether the mode checks that close tags match the corresponding opening tag, and highlights mismatches as errors. Defaults to true.
    alignCDATA (boolean)
    Setting this to true will force the opening tag of CDATA blocks to not be indented.

    MIME types defined: application/xml, text/html.

    ================================================ FILE: third_party/CodeMirror/mode/xml/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var mode = CodeMirror.getMode({indentUnit: 2}, "xml"), mname = "xml"; function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), mname); } MT("matching", "[tag&bracket <][tag top][tag&bracket >]", " text", " [tag&bracket <][tag inner][tag&bracket />]", "[tag&bracket ]"); MT("nonmatching", "[tag&bracket <][tag top][tag&bracket >]", " [tag&bracket <][tag inner][tag&bracket />]", " [tag&bracket ]"); MT("doctype", "[meta ]", "[tag&bracket <][tag top][tag&bracket />]"); MT("cdata", "[tag&bracket <][tag top][tag&bracket >]", " [atom ]", "[tag&bracket ]"); // HTML tests mode = CodeMirror.getMode({indentUnit: 2}, "text/html"); MT("selfclose", "[tag&bracket <][tag html][tag&bracket >]", " [tag&bracket <][tag link] [attribute rel]=[string stylesheet] [attribute href]=[string \"/foobar\"][tag&bracket >]", "[tag&bracket ]"); MT("list", "[tag&bracket <][tag ol][tag&bracket >]", " [tag&bracket <][tag li][tag&bracket >]one", " [tag&bracket <][tag li][tag&bracket >]two", "[tag&bracket ]"); MT("valueless", "[tag&bracket <][tag input] [attribute type]=[string checkbox] [attribute checked][tag&bracket />]"); MT("pThenArticle", "[tag&bracket <][tag p][tag&bracket >]", " foo", "[tag&bracket <][tag article][tag&bracket >]bar"); })(); ================================================ FILE: third_party/CodeMirror/mode/xml/xml.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; var htmlConfig = { autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true, 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true, 'menuitem': true}, implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true, 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true, 'th': true, 'tr': true}, contextGrabbers: { 'dd': {'dd': true, 'dt': true}, 'dt': {'dd': true, 'dt': true}, 'li': {'li': true}, 'option': {'option': true, 'optgroup': true}, 'optgroup': {'optgroup': true}, 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true, 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true, 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true, 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true, 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true}, 'rp': {'rp': true, 'rt': true}, 'rt': {'rp': true, 'rt': true}, 'tbody': {'tbody': true, 'tfoot': true}, 'td': {'td': true, 'th': true}, 'tfoot': {'tbody': true}, 'th': {'td': true, 'th': true}, 'thead': {'tbody': true, 'tfoot': true}, 'tr': {'tr': true} }, doNotIndent: {"pre": true}, allowUnquoted: true, allowMissing: true, caseFold: true } var xmlConfig = { autoSelfClosers: {}, implicitlyClosed: {}, contextGrabbers: {}, doNotIndent: {}, allowUnquoted: false, allowMissing: false, allowMissingTagName: false, caseFold: false } CodeMirror.defineMode("xml", function(editorConf, config_) { var indentUnit = editorConf.indentUnit var config = {} var defaults = config_.htmlMode ? htmlConfig : xmlConfig for (var prop in defaults) config[prop] = defaults[prop] for (var prop in config_) config[prop] = config_[prop] // Return variables for tokenizers var type, setStyle; function inText(stream, state) { function chain(parser) { state.tokenize = parser; return parser(stream, state); } var ch = stream.next(); if (ch == "<") { if (stream.eat("!")) { if (stream.eat("[")) { if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>")); else return null; } else if (stream.match("--")) { return chain(inBlock("comment", "-->")); } else if (stream.match("DOCTYPE", true, true)) { stream.eatWhile(/[\w\._\-]/); return chain(doctype(1)); } else { return null; } } else if (stream.eat("?")) { stream.eatWhile(/[\w\._\-]/); state.tokenize = inBlock("meta", "?>"); return "meta"; } else { type = stream.eat("/") ? "closeTag" : "openTag"; state.tokenize = inTag; return "tag bracket"; } } else if (ch == "&") { var ok; if (stream.eat("#")) { if (stream.eat("x")) { ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";"); } else { ok = stream.eatWhile(/[\d]/) && stream.eat(";"); } } else { ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";"); } return ok ? "atom" : "error"; } else { stream.eatWhile(/[^&<]/); return null; } } inText.isInText = true; function inTag(stream, state) { var ch = stream.next(); if (ch == ">" || (ch == "/" && stream.eat(">"))) { state.tokenize = inText; type = ch == ">" ? "endTag" : "selfcloseTag"; return "tag bracket"; } else if (ch == "=") { type = "equals"; return null; } else if (ch == "<") { state.tokenize = inText; state.state = baseState; state.tagName = state.tagStart = null; var next = state.tokenize(stream, state); return next ? next + " tag error" : "tag error"; } else if (/[\'\"]/.test(ch)) { state.tokenize = inAttribute(ch); state.stringStartCol = stream.column(); return state.tokenize(stream, state); } else { stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/); return "word"; } } function inAttribute(quote) { var closure = function(stream, state) { while (!stream.eol()) { if (stream.next() == quote) { state.tokenize = inTag; break; } } return "string"; }; closure.isInAttribute = true; return closure; } function inBlock(style, terminator) { return function(stream, state) { while (!stream.eol()) { if (stream.match(terminator)) { state.tokenize = inText; break; } stream.next(); } return style; } } function doctype(depth) { return function(stream, state) { var ch; while ((ch = stream.next()) != null) { if (ch == "<") { state.tokenize = doctype(depth + 1); return state.tokenize(stream, state); } else if (ch == ">") { if (depth == 1) { state.tokenize = inText; break; } else { state.tokenize = doctype(depth - 1); return state.tokenize(stream, state); } } } return "meta"; }; } function Context(state, tagName, startOfLine) { this.prev = state.context; this.tagName = tagName; this.indent = state.indented; this.startOfLine = startOfLine; if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent)) this.noIndent = true; } function popContext(state) { if (state.context) state.context = state.context.prev; } function maybePopContext(state, nextTagName) { var parentTagName; while (true) { if (!state.context) { return; } parentTagName = state.context.tagName; if (!config.contextGrabbers.hasOwnProperty(parentTagName) || !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { return; } popContext(state); } } function baseState(type, stream, state) { if (type == "openTag") { state.tagStart = stream.column(); return tagNameState; } else if (type == "closeTag") { return closeTagNameState; } else { return baseState; } } function tagNameState(type, stream, state) { if (type == "word") { state.tagName = stream.current(); setStyle = "tag"; return attrState; } else if (config.allowMissingTagName && type == "endTag") { setStyle = "tag bracket"; return attrState(type, stream, state); } else { setStyle = "error"; return tagNameState; } } function closeTagNameState(type, stream, state) { if (type == "word") { var tagName = stream.current(); if (state.context && state.context.tagName != tagName && config.implicitlyClosed.hasOwnProperty(state.context.tagName)) popContext(state); if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) { setStyle = "tag"; return closeState; } else { setStyle = "tag error"; return closeStateErr; } } else if (config.allowMissingTagName && type == "endTag") { setStyle = "tag bracket"; return closeState(type, stream, state); } else { setStyle = "error"; return closeStateErr; } } function closeState(type, _stream, state) { if (type != "endTag") { setStyle = "error"; return closeState; } popContext(state); return baseState; } function closeStateErr(type, stream, state) { setStyle = "error"; return closeState(type, stream, state); } function attrState(type, _stream, state) { if (type == "word") { setStyle = "attribute"; return attrEqState; } else if (type == "endTag" || type == "selfcloseTag") { var tagName = state.tagName, tagStart = state.tagStart; state.tagName = state.tagStart = null; if (type == "selfcloseTag" || config.autoSelfClosers.hasOwnProperty(tagName)) { maybePopContext(state, tagName); } else { maybePopContext(state, tagName); state.context = new Context(state, tagName, tagStart == state.indented); } return baseState; } setStyle = "error"; return attrState; } function attrEqState(type, stream, state) { if (type == "equals") return attrValueState; if (!config.allowMissing) setStyle = "error"; return attrState(type, stream, state); } function attrValueState(type, stream, state) { if (type == "string") return attrContinuedState; if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;} setStyle = "error"; return attrState(type, stream, state); } function attrContinuedState(type, stream, state) { if (type == "string") return attrContinuedState; return attrState(type, stream, state); } return { startState: function(baseIndent) { var state = {tokenize: inText, state: baseState, indented: baseIndent || 0, tagName: null, tagStart: null, context: null} if (baseIndent != null) state.baseIndent = baseIndent return state }, token: function(stream, state) { if (!state.tagName && stream.sol()) state.indented = stream.indentation(); if (stream.eatSpace()) return null; type = null; var style = state.tokenize(stream, state); if ((style || type) && style != "comment") { setStyle = null; state.state = state.state(type || style, stream, state); if (setStyle) style = setStyle == "error" ? style + " error" : setStyle; } return style; }, indent: function(state, textAfter, fullLine) { var context = state.context; // Indent multi-line strings (e.g. css). if (state.tokenize.isInAttribute) { if (state.tagStart == state.indented) return state.stringStartCol + 1; else return state.indented + indentUnit; } if (context && context.noIndent) return CodeMirror.Pass; if (state.tokenize != inTag && state.tokenize != inText) return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; // Indent the starts of attribute names. if (state.tagName) { if (config.multilineTagIndentPastTag !== false) return state.tagStart + state.tagName.length + 2; else return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1); } if (config.alignCDATA && /$/, blockCommentStart: "", configuration: config.htmlMode ? "html" : "xml", helperType: config.htmlMode ? "html" : "xml", skipAttribute: function(state) { if (state.state == attrValueState) state.state = attrState } }; }); CodeMirror.defineMIME("text/xml", "xml"); CodeMirror.defineMIME("application/xml", "xml"); if (!CodeMirror.mimeModes.hasOwnProperty("text/html")) CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true}); }); ================================================ FILE: third_party/CodeMirror/mode/xquery/index.html ================================================ CodeMirror: XQuery mode

    XQuery mode

    MIME types defined: application/xquery.

    Development of the CodeMirror XQuery mode was sponsored by MarkLogic and developed by Mike Brevoort.

    ================================================ FILE: third_party/CodeMirror/mode/xquery/test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Don't take these too seriously -- the expected results appear to be // based on the results of actual runs without any serious manual // verification. If a change you made causes them to fail, the test is // as likely to wrong as the code. (function() { var mode = CodeMirror.getMode({tabSize: 4}, "xquery"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } MT("eviltest", "[keyword xquery] [keyword version] [variable "1][keyword .][atom 0][keyword -][variable ml"][def&variable ;] [comment (: this is : a \"comment\" :)]", " [keyword let] [variable $let] [keyword :=] [variable <x] [variable attr][keyword =][variable "value">"test"<func>][def&variable ;function]() [variable $var] {[keyword function]()} {[variable $var]}[variable <][keyword /][variable func><][keyword /][variable x>]", " [keyword let] [variable $joe][keyword :=][atom 1]", " [keyword return] [keyword element] [variable element] {", " [keyword attribute] [variable attribute] { [atom 1] },", " [keyword element] [variable test] { [variable 'a'] }, [keyword attribute] [variable foo] { [variable "bar"] },", " [def&variable fn:doc]()[[ [variable foo][keyword /][variable @bar] [keyword eq] [variable $let] ]],", " [keyword //][variable x] } [comment (: a more 'evil' test :)]", " [comment (: Modified Blakeley example (: with nested comment :) ... :)]", " [keyword declare] [variable private] [keyword function] [def&variable local:declare]() {()}[variable ;]", " [keyword declare] [variable private] [keyword function] [def&variable local:private]() {()}[variable ;]", " [keyword declare] [variable private] [keyword function] [def&variable local:function]() {()}[variable ;]", " [keyword declare] [variable private] [keyword function] [def&variable local:local]() {()}[variable ;]", " [keyword let] [variable $let] [keyword :=] [variable <let>let] [variable $let] [keyword :=] [variable "let"<][keyword /let][variable >]", " [keyword return] [keyword element] [variable element] {", " [keyword attribute] [variable attribute] { [keyword try] { [def&variable xdmp:version]() } [keyword catch]([variable $e]) { [def&variable xdmp:log]([variable $e]) } },", " [keyword attribute] [variable fn:doc] { [variable "bar"] [keyword castable] [keyword as] [atom xs:string] },", " [keyword element] [variable text] { [keyword text] { [variable "text"] } },", " [def&variable fn:doc]()[[ [qualifier child::][variable eq][keyword /]([variable @bar] [keyword |] [qualifier attribute::][variable attribute]) [keyword eq] [variable $let] ]],", " [keyword //][variable fn:doc]", " }"); MT("testEmptySequenceKeyword", "[string \"foo\"] [keyword instance] [keyword of] [keyword empty-sequence]()"); MT("testMultiAttr", "[tag

    ][variable hello] [variable world][tag

    ]"); MT("test namespaced variable", "[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;]"); MT("test EQName variable", "[keyword declare] [keyword variable] [variable $\"http://www.example.com/ns/my\":var] [keyword :=] [atom 12][variable ;]", "[tag ]{[variable $\"http://www.example.com/ns/my\":var]}[tag ]"); MT("test EQName function", "[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] {", " [variable $a] [keyword +] [atom 2]", "}[variable ;]", "[tag ]{[def&variable \"http://www.example.com/ns/my\":fn]([atom 12])}[tag ]"); MT("test EQName function with single quotes", "[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] {", " [variable $a] [keyword +] [atom 2]", "}[variable ;]", "[tag ]{[def&variable 'http://www.example.com/ns/my':fn]([atom 12])}[tag ]"); MT("testProcessingInstructions", "[def&variable data]([comment&meta ]) [keyword instance] [keyword of] [atom xs:string]"); MT("testQuoteEscapeDouble", "[keyword let] [variable $rootfolder] [keyword :=] [string \"c:\\builds\\winnt\\HEAD\\qa\\scripts\\\"]", "[keyword let] [variable $keysfolder] [keyword :=] [def&variable concat]([variable $rootfolder], [string \"keys\\\"])"); })(); ================================================ FILE: third_party/CodeMirror/mode/xquery/xquery.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("xquery", function() { // The keywords object is set to the result of this self executing // function. Each keyword is a property of the keywords object whose // value is {type: atype, style: astyle} var keywords = function(){ // convenience functions used to build keywords object function kw(type) {return {type: type, style: "keyword"};} var operator = kw("operator") , atom = {type: "atom", style: "atom"} , punctuation = {type: "punctuation", style: null} , qualifier = {type: "axis_specifier", style: "qualifier"}; // kwObj is what is return from this function at the end var kwObj = { ',': punctuation }; // a list of 'basic' keywords. For each add a property to kwObj with the value of // {type: basic[i], style: "keyword"} e.g. 'after' --> {type: "after", style: "keyword"} var basic = ['after', 'all', 'allowing', 'ancestor', 'ancestor-or-self', 'any', 'array', 'as', 'ascending', 'at', 'attribute', 'base-uri', 'before', 'boundary-space', 'by', 'case', 'cast', 'castable', 'catch', 'child', 'collation', 'comment', 'construction', 'contains', 'content', 'context', 'copy', 'copy-namespaces', 'count', 'decimal-format', 'declare', 'default', 'delete', 'descendant', 'descendant-or-self', 'descending', 'diacritics', 'different', 'distance', 'document', 'document-node', 'element', 'else', 'empty', 'empty-sequence', 'encoding', 'end', 'entire', 'every', 'exactly', 'except', 'external', 'first', 'following', 'following-sibling', 'for', 'from', 'ftand', 'ftnot', 'ft-option', 'ftor', 'function', 'fuzzy', 'greatest', 'group', 'if', 'import', 'in', 'inherit', 'insensitive', 'insert', 'instance', 'intersect', 'into', 'invoke', 'is', 'item', 'language', 'last', 'lax', 'least', 'let', 'levels', 'lowercase', 'map', 'modify', 'module', 'most', 'namespace', 'next', 'no', 'node', 'nodes', 'no-inherit', 'no-preserve', 'not', 'occurs', 'of', 'only', 'option', 'order', 'ordered', 'ordering', 'paragraph', 'paragraphs', 'parent', 'phrase', 'preceding', 'preceding-sibling', 'preserve', 'previous', 'processing-instruction', 'relationship', 'rename', 'replace', 'return', 'revalidation', 'same', 'satisfies', 'schema', 'schema-attribute', 'schema-element', 'score', 'self', 'sensitive', 'sentence', 'sentences', 'sequence', 'skip', 'sliding', 'some', 'stable', 'start', 'stemming', 'stop', 'strict', 'strip', 'switch', 'text', 'then', 'thesaurus', 'times', 'to', 'transform', 'treat', 'try', 'tumbling', 'type', 'typeswitch', 'union', 'unordered', 'update', 'updating', 'uppercase', 'using', 'validate', 'value', 'variable', 'version', 'weight', 'when', 'where', 'wildcards', 'window', 'with', 'without', 'word', 'words', 'xquery']; for(var i=0, l=basic.length; i < l; i++) { kwObj[basic[i]] = kw(basic[i]);}; // a list of types. For each add a property to kwObj with the value of // {type: "atom", style: "atom"} var types = ['xs:anyAtomicType', 'xs:anySimpleType', 'xs:anyType', 'xs:anyURI', 'xs:base64Binary', 'xs:boolean', 'xs:byte', 'xs:date', 'xs:dateTime', 'xs:dateTimeStamp', 'xs:dayTimeDuration', 'xs:decimal', 'xs:double', 'xs:duration', 'xs:ENTITIES', 'xs:ENTITY', 'xs:float', 'xs:gDay', 'xs:gMonth', 'xs:gMonthDay', 'xs:gYear', 'xs:gYearMonth', 'xs:hexBinary', 'xs:ID', 'xs:IDREF', 'xs:IDREFS', 'xs:int', 'xs:integer', 'xs:item', 'xs:java', 'xs:language', 'xs:long', 'xs:Name', 'xs:NCName', 'xs:negativeInteger', 'xs:NMTOKEN', 'xs:NMTOKENS', 'xs:nonNegativeInteger', 'xs:nonPositiveInteger', 'xs:normalizedString', 'xs:NOTATION', 'xs:numeric', 'xs:positiveInteger', 'xs:precisionDecimal', 'xs:QName', 'xs:short', 'xs:string', 'xs:time', 'xs:token', 'xs:unsignedByte', 'xs:unsignedInt', 'xs:unsignedLong', 'xs:unsignedShort', 'xs:untyped', 'xs:untypedAtomic', 'xs:yearMonthDuration']; for(var i=0, l=types.length; i < l; i++) { kwObj[types[i]] = atom;}; // each operator will add a property to kwObj with value of {type: "operator", style: "keyword"} var operators = ['eq', 'ne', 'lt', 'le', 'gt', 'ge', ':=', '=', '>', '>=', '<', '<=', '.', '|', '?', 'and', 'or', 'div', 'idiv', 'mod', '*', '/', '+', '-']; for(var i=0, l=operators.length; i < l; i++) { kwObj[operators[i]] = operator;}; // each axis_specifiers will add a property to kwObj with value of {type: "axis_specifier", style: "qualifier"} var axis_specifiers = ["self::", "attribute::", "child::", "descendant::", "descendant-or-self::", "parent::", "ancestor::", "ancestor-or-self::", "following::", "preceding::", "following-sibling::", "preceding-sibling::"]; for(var i=0, l=axis_specifiers.length; i < l; i++) { kwObj[axis_specifiers[i]] = qualifier; }; return kwObj; }(); function chain(stream, state, f) { state.tokenize = f; return f(stream, state); } // the primary mode tokenizer function tokenBase(stream, state) { var ch = stream.next(), mightBeFunction = false, isEQName = isEQNameAhead(stream); // an XML tag (if not in some sub, chained tokenizer) if (ch == "<") { if(stream.match("!--", true)) return chain(stream, state, tokenXMLComment); if(stream.match("![CDATA", false)) { state.tokenize = tokenCDATA; return "tag"; } if(stream.match("?", false)) { return chain(stream, state, tokenPreProcessing); } var isclose = stream.eat("/"); stream.eatSpace(); var tagName = "", c; while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; return chain(stream, state, tokenTag(tagName, isclose)); } // start code block else if(ch == "{") { pushStateStack(state, { type: "codeblock"}); return null; } // end code block else if(ch == "}") { popStateStack(state); return null; } // if we're in an XML block else if(isInXmlBlock(state)) { if(ch == ">") return "tag"; else if(ch == "/" && stream.eat(">")) { popStateStack(state); return "tag"; } else return "variable"; } // if a number else if (/\d/.test(ch)) { stream.match(/^\d*(?:\.\d*)?(?:E[+\-]?\d+)?/); return "atom"; } // comment start else if (ch === "(" && stream.eat(":")) { pushStateStack(state, { type: "comment"}); return chain(stream, state, tokenComment); } // quoted string else if (!isEQName && (ch === '"' || ch === "'")) return chain(stream, state, tokenString(ch)); // variable else if(ch === "$") { return chain(stream, state, tokenVariable); } // assignment else if(ch ===":" && stream.eat("=")) { return "keyword"; } // open paren else if(ch === "(") { pushStateStack(state, { type: "paren"}); return null; } // close paren else if(ch === ")") { popStateStack(state); return null; } // open paren else if(ch === "[") { pushStateStack(state, { type: "bracket"}); return null; } // close paren else if(ch === "]") { popStateStack(state); return null; } else { var known = keywords.propertyIsEnumerable(ch) && keywords[ch]; // if there's a EQName ahead, consume the rest of the string portion, it's likely a function if(isEQName && ch === '\"') while(stream.next() !== '"'){} if(isEQName && ch === '\'') while(stream.next() !== '\''){} // gobble up a word if the character is not known if(!known) stream.eatWhile(/[\w\$_-]/); // gobble a colon in the case that is a lib func type call fn:doc var foundColon = stream.eat(":"); // if there's not a second colon, gobble another word. Otherwise, it's probably an axis specifier // which should get matched as a keyword if(!stream.eat(":") && foundColon) { stream.eatWhile(/[\w\$_-]/); } // if the next non whitespace character is an open paren, this is probably a function (if not a keyword of other sort) if(stream.match(/^[ \t]*\(/, false)) { mightBeFunction = true; } // is the word a keyword? var word = stream.current(); known = keywords.propertyIsEnumerable(word) && keywords[word]; // if we think it's a function call but not yet known, // set style to variable for now for lack of something better if(mightBeFunction && !known) known = {type: "function_call", style: "variable def"}; // if the previous word was element, attribute, axis specifier, this word should be the name of that if(isInXmlConstructor(state)) { popStateStack(state); return "variable"; } // as previously checked, if the word is element,attribute, axis specifier, call it an "xmlconstructor" and // push the stack so we know to look for it on the next word if(word == "element" || word == "attribute" || known.type == "axis_specifier") pushStateStack(state, {type: "xmlconstructor"}); // if the word is known, return the details of that else just call this a generic 'word' return known ? known.style : "variable"; } } // handle comments, including nested function tokenComment(stream, state) { var maybeEnd = false, maybeNested = false, nestedCount = 0, ch; while (ch = stream.next()) { if (ch == ")" && maybeEnd) { if(nestedCount > 0) nestedCount--; else { popStateStack(state); break; } } else if(ch == ":" && maybeNested) { nestedCount++; } maybeEnd = (ch == ":"); maybeNested = (ch == "("); } return "comment"; } // tokenizer for string literals // optionally pass a tokenizer function to set state.tokenize back to when finished function tokenString(quote, f) { return function(stream, state) { var ch; if(isInString(state) && stream.current() == quote) { popStateStack(state); if(f) state.tokenize = f; return "string"; } pushStateStack(state, { type: "string", name: quote, tokenize: tokenString(quote, f) }); // if we're in a string and in an XML block, allow an embedded code block if(stream.match("{", false) && isInXmlAttributeBlock(state)) { state.tokenize = tokenBase; return "string"; } while (ch = stream.next()) { if (ch == quote) { popStateStack(state); if(f) state.tokenize = f; break; } else { // if we're in a string and in an XML block, allow an embedded code block in an attribute if(stream.match("{", false) && isInXmlAttributeBlock(state)) { state.tokenize = tokenBase; return "string"; } } } return "string"; }; } // tokenizer for variables function tokenVariable(stream, state) { var isVariableChar = /[\w\$_-]/; // a variable may start with a quoted EQName so if the next character is quote, consume to the next quote if(stream.eat("\"")) { while(stream.next() !== '\"'){}; stream.eat(":"); } else { stream.eatWhile(isVariableChar); if(!stream.match(":=", false)) stream.eat(":"); } stream.eatWhile(isVariableChar); state.tokenize = tokenBase; return "variable"; } // tokenizer for XML tags function tokenTag(name, isclose) { return function(stream, state) { stream.eatSpace(); if(isclose && stream.eat(">")) { popStateStack(state); state.tokenize = tokenBase; return "tag"; } // self closing tag without attributes? if(!stream.eat("/")) pushStateStack(state, { type: "tag", name: name, tokenize: tokenBase}); if(!stream.eat(">")) { state.tokenize = tokenAttribute; return "tag"; } else { state.tokenize = tokenBase; } return "tag"; }; } // tokenizer for XML attributes function tokenAttribute(stream, state) { var ch = stream.next(); if(ch == "/" && stream.eat(">")) { if(isInXmlAttributeBlock(state)) popStateStack(state); if(isInXmlBlock(state)) popStateStack(state); return "tag"; } if(ch == ">") { if(isInXmlAttributeBlock(state)) popStateStack(state); return "tag"; } if(ch == "=") return null; // quoted string if (ch == '"' || ch == "'") return chain(stream, state, tokenString(ch, tokenAttribute)); if(!isInXmlAttributeBlock(state)) pushStateStack(state, { type: "attribute", tokenize: tokenAttribute}); stream.eat(/[a-zA-Z_:]/); stream.eatWhile(/[-a-zA-Z0-9_:.]/); stream.eatSpace(); // the case where the attribute has not value and the tag was closed if(stream.match(">", false) || stream.match("/", false)) { popStateStack(state); state.tokenize = tokenBase; } return "attribute"; } // handle comments, including nested function tokenXMLComment(stream, state) { var ch; while (ch = stream.next()) { if (ch == "-" && stream.match("->", true)) { state.tokenize = tokenBase; return "comment"; } } } // handle CDATA function tokenCDATA(stream, state) { var ch; while (ch = stream.next()) { if (ch == "]" && stream.match("]", true)) { state.tokenize = tokenBase; return "comment"; } } } // handle preprocessing instructions function tokenPreProcessing(stream, state) { var ch; while (ch = stream.next()) { if (ch == "?" && stream.match(">", true)) { state.tokenize = tokenBase; return "comment meta"; } } } // functions to test the current context of the state function isInXmlBlock(state) { return isIn(state, "tag"); } function isInXmlAttributeBlock(state) { return isIn(state, "attribute"); } function isInXmlConstructor(state) { return isIn(state, "xmlconstructor"); } function isInString(state) { return isIn(state, "string"); } function isEQNameAhead(stream) { // assume we've already eaten a quote (") if(stream.current() === '"') return stream.match(/^[^\"]+\"\:/, false); else if(stream.current() === '\'') return stream.match(/^[^\"]+\'\:/, false); else return false; } function isIn(state, type) { return (state.stack.length && state.stack[state.stack.length - 1].type == type); } function pushStateStack(state, newState) { state.stack.push(newState); } function popStateStack(state) { state.stack.pop(); var reinstateTokenize = state.stack.length && state.stack[state.stack.length-1].tokenize; state.tokenize = reinstateTokenize || tokenBase; } // the interface for the mode API return { startState: function() { return { tokenize: tokenBase, cc: [], stack: [] }; }, token: function(stream, state) { if (stream.eatSpace()) return null; var style = state.tokenize(stream, state); return style; }, blockCommentStart: "(:", blockCommentEnd: ":)" }; }); CodeMirror.defineMIME("application/xquery", "xquery"); }); ================================================ FILE: third_party/CodeMirror/mode/yacas/index.html ================================================ CodeMirror: yacas mode

    yacas mode

    MIME types defined: text/x-yacas (yacas).

    ================================================ FILE: third_party/CodeMirror/mode/yacas/yacas.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // Yacas mode copyright (c) 2015 by Grzegorz Mazur // Loosely based on mathematica mode by Calin Barbat (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('yacas', function(_config, _parserConfig) { function words(str) { var obj = {}, words = str.split(" "); for (var i = 0; i < words.length; ++i) obj[words[i]] = true; return obj; } var bodiedOps = words("Assert BackQuote D Defun Deriv For ForEach FromFile " + "FromString Function Integrate InverseTaylor Limit " + "LocalSymbols Macro MacroRule MacroRulePattern " + "NIntegrate Rule RulePattern Subst TD TExplicitSum " + "TSum Taylor Taylor1 Taylor2 Taylor3 ToFile " + "ToStdout ToString TraceRule Until While"); // patterns var pFloatForm = "(?:(?:\\.\\d+|\\d+\\.\\d*|\\d+)(?:[eE][+-]?\\d+)?)"; var pIdentifier = "(?:[a-zA-Z\\$'][a-zA-Z0-9\\$']*)"; // regular expressions var reFloatForm = new RegExp(pFloatForm); var reIdentifier = new RegExp(pIdentifier); var rePattern = new RegExp(pIdentifier + "?_" + pIdentifier); var reFunctionLike = new RegExp(pIdentifier + "\\s*\\("); function tokenBase(stream, state) { var ch; // get next character ch = stream.next(); // string if (ch === '"') { state.tokenize = tokenString; return state.tokenize(stream, state); } // comment if (ch === '/') { if (stream.eat('*')) { state.tokenize = tokenComment; return state.tokenize(stream, state); } if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } } // go back one character stream.backUp(1); // update scope info var m = stream.match(/^(\w+)\s*\(/, false); if (m !== null && bodiedOps.hasOwnProperty(m[1])) state.scopes.push('bodied'); var scope = currentScope(state); if (scope === 'bodied' && ch === '[') state.scopes.pop(); if (ch === '[' || ch === '{' || ch === '(') state.scopes.push(ch); scope = currentScope(state); if (scope === '[' && ch === ']' || scope === '{' && ch === '}' || scope === '(' && ch === ')') state.scopes.pop(); if (ch === ';') { while (scope === 'bodied') { state.scopes.pop(); scope = currentScope(state); } } // look for ordered rules if (stream.match(/\d+ *#/, true, false)) { return 'qualifier'; } // look for numbers if (stream.match(reFloatForm, true, false)) { return 'number'; } // look for placeholders if (stream.match(rePattern, true, false)) { return 'variable-3'; } // match all braces separately if (stream.match(/(?:\[|\]|{|}|\(|\))/, true, false)) { return 'bracket'; } // literals looking like function calls if (stream.match(reFunctionLike, true, false)) { stream.backUp(1); return 'variable'; } // all other identifiers if (stream.match(reIdentifier, true, false)) { return 'variable-2'; } // operators; note that operators like @@ or /; are matched separately for each symbol. if (stream.match(/(?:\\|\+|\-|\*|\/|,|;|\.|:|@|~|=|>|<|&|\||_|`|'|\^|\?|!|%|#)/, true, false)) { return 'operator'; } // everything else is an error return 'error'; } function tokenString(stream, state) { var next, end = false, escaped = false; while ((next = stream.next()) != null) { if (next === '"' && !escaped) { end = true; break; } escaped = !escaped && next === '\\'; } if (end && !escaped) { state.tokenize = tokenBase; } return 'string'; }; function tokenComment(stream, state) { var prev, next; while((next = stream.next()) != null) { if (prev === '*' && next === '/') { state.tokenize = tokenBase; break; } prev = next; } return 'comment'; } function currentScope(state) { var scope = null; if (state.scopes.length > 0) scope = state.scopes[state.scopes.length - 1]; return scope; } return { startState: function() { return { tokenize: tokenBase, scopes: [] }; }, token: function(stream, state) { if (stream.eatSpace()) return null; return state.tokenize(stream, state); }, indent: function(state, textAfter) { if (state.tokenize !== tokenBase && state.tokenize !== null) return CodeMirror.Pass; var delta = 0; if (textAfter === ']' || textAfter === '];' || textAfter === '}' || textAfter === '};' || textAfter === ');') delta = -1; return (state.scopes.length + delta) * _config.indentUnit; }, electricChars: "{}[]();", blockCommentStart: "/*", blockCommentEnd: "*/", lineComment: "//" }; }); CodeMirror.defineMIME('text/x-yacas', { name: 'yacas' }); }); ================================================ FILE: third_party/CodeMirror/mode/yaml/index.html ================================================ CodeMirror: YAML mode

    YAML mode

    MIME types defined: text/x-yaml.

    ================================================ FILE: third_party/CodeMirror/mode/yaml/yaml.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("yaml", function() { var cons = ['true', 'false', 'on', 'off', 'yes', 'no']; var keywordRegex = new RegExp("\\b(("+cons.join(")|(")+"))$", 'i'); return { token: function(stream, state) { var ch = stream.peek(); var esc = state.escaped; state.escaped = false; /* comments */ if (ch == "#" && (stream.pos == 0 || /\s/.test(stream.string.charAt(stream.pos - 1)))) { stream.skipToEnd(); return "comment"; } if (stream.match(/^('([^']|\\.)*'?|"([^"]|\\.)*"?)/)) return "string"; if (state.literal && stream.indentation() > state.keyCol) { stream.skipToEnd(); return "string"; } else if (state.literal) { state.literal = false; } if (stream.sol()) { state.keyCol = 0; state.pair = false; state.pairStart = false; /* document start */ if(stream.match(/---/)) { return "def"; } /* document end */ if (stream.match(/\.\.\./)) { return "def"; } /* array list item */ if (stream.match(/\s*-\s+/)) { return 'meta'; } } /* inline pairs/lists */ if (stream.match(/^(\{|\}|\[|\])/)) { if (ch == '{') state.inlinePairs++; else if (ch == '}') state.inlinePairs--; else if (ch == '[') state.inlineList++; else state.inlineList--; return 'meta'; } /* list seperator */ if (state.inlineList > 0 && !esc && ch == ',') { stream.next(); return 'meta'; } /* pairs seperator */ if (state.inlinePairs > 0 && !esc && ch == ',') { state.keyCol = 0; state.pair = false; state.pairStart = false; stream.next(); return 'meta'; } /* start of value of a pair */ if (state.pairStart) { /* block literals */ if (stream.match(/^\s*(\||\>)\s*/)) { state.literal = true; return 'meta'; }; /* references */ if (stream.match(/^\s*(\&|\*)[a-z0-9\._-]+\b/i)) { return 'variable-2'; } /* numbers */ if (state.inlinePairs == 0 && stream.match(/^\s*-?[0-9\.\,]+\s?$/)) { return 'number'; } if (state.inlinePairs > 0 && stream.match(/^\s*-?[0-9\.\,]+\s?(?=(,|}))/)) { return 'number'; } /* keywords */ if (stream.match(keywordRegex)) { return 'keyword'; } } /* pairs (associative arrays) -> key */ if (!state.pair && stream.match(/^\s*(?:[,\[\]{}&*!|>'"%@`][^\s'":]|[^,\[\]{}#&*!|>'"%@`])[^#]*?(?=\s*:($|\s))/)) { state.pair = true; state.keyCol = stream.indentation(); return "atom"; } if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; return 'meta'; } /* nothing found, continue */ state.pairStart = false; state.escaped = (ch == '\\'); stream.next(); return null; }, startState: function() { return { pair: false, pairStart: false, keyCol: 0, inlinePairs: 0, inlineList: 0, literal: false, escaped: false }; }, lineComment: "#", fold: "indent" }; }); CodeMirror.defineMIME("text/x-yaml", "yaml"); CodeMirror.defineMIME("text/yaml", "yaml"); }); ================================================ FILE: third_party/CodeMirror/mode/yaml-frontmatter/index.html ================================================ CodeMirror: YAML front matter mode

    YAML front matter mode

    Defines a mode that parses a YAML frontmatter at the start of a file, switching to a base mode at the end of that. Takes a mode configuration option base to configure the base mode, which defaults to "gfm".

    ================================================ FILE: third_party/CodeMirror/mode/yaml-frontmatter/yaml-frontmatter.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function (mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../yaml/yaml")) else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../yaml/yaml"], mod) else // Plain browser env mod(CodeMirror) })(function (CodeMirror) { var START = 0, FRONTMATTER = 1, BODY = 2 // a mixed mode for Markdown text with an optional YAML front matter CodeMirror.defineMode("yaml-frontmatter", function (config, parserConfig) { var yamlMode = CodeMirror.getMode(config, "yaml") var innerMode = CodeMirror.getMode(config, parserConfig && parserConfig.base || "gfm") function curMode(state) { return state.state == BODY ? innerMode : yamlMode } return { startState: function () { return { state: START, inner: CodeMirror.startState(yamlMode) } }, copyState: function (state) { return { state: state.state, inner: CodeMirror.copyState(curMode(state), state.inner) } }, token: function (stream, state) { if (state.state == START) { if (stream.match(/---/, false)) { state.state = FRONTMATTER return yamlMode.token(stream, state.inner) } else { state.state = BODY state.inner = CodeMirror.startState(innerMode) return innerMode.token(stream, state.inner) } } else if (state.state == FRONTMATTER) { var end = stream.sol() && stream.match(/---/, false) var style = yamlMode.token(stream, state.inner) if (end) { state.state = BODY state.inner = CodeMirror.startState(innerMode) } return style } else { return innerMode.token(stream, state.inner) } }, innerMode: function (state) { return {mode: curMode(state), state: state.inner} }, blankLine: function (state) { var mode = curMode(state) if (mode.blankLine) return mode.blankLine(state.inner) } } }) }); ================================================ FILE: third_party/CodeMirror/mode/z80/index.html ================================================ CodeMirror: Z80 assembly mode

    Z80 assembly mode

    MIME types defined: text/x-z80, text/x-ez80.

    ================================================ FILE: third_party/CodeMirror/mode/z80/z80.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode('z80', function(_config, parserConfig) { var ez80 = parserConfig.ez80; var keywords1, keywords2; if (ez80) { 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; keywords2 = /^(((call|j[pr]|rst|ret[in]?)(\.([sl]?i)?[sl])?)|(rs|st)mix)\b/i; } else { 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; keywords2 = /^(call|j[pr]|ret[in]?|b_?(call|jump))\b/i; } var variables1 = /^(af?|bc?|c|de?|e|hl?|l|i[xy]?|r|sp)\b/i; var variables2 = /^(n?[zc]|p[oe]?|m)\b/i; var errors = /^([hl][xy]|i[xy][hl]|slia|sll)\b/i; var numbers = /^([\da-f]+h|[0-7]+o|[01]+b|\d+d?)\b/i; return { startState: function() { return { context: 0 }; }, token: function(stream, state) { if (!stream.column()) state.context = 0; if (stream.eatSpace()) return null; var w; if (stream.eatWhile(/\w/)) { if (ez80 && stream.eat('.')) { stream.eatWhile(/\w/); } w = stream.current(); if (stream.indentation()) { if ((state.context == 1 || state.context == 4) && variables1.test(w)) { state.context = 4; return 'var2'; } if (state.context == 2 && variables2.test(w)) { state.context = 4; return 'var3'; } if (keywords1.test(w)) { state.context = 1; return 'keyword'; } else if (keywords2.test(w)) { state.context = 2; return 'keyword'; } else if (state.context == 4 && numbers.test(w)) { return 'number'; } if (errors.test(w)) return 'error'; } else if (stream.match(numbers)) { return 'number'; } else { return null; } } else if (stream.eat(';')) { stream.skipToEnd(); return 'comment'; } else if (stream.eat('"')) { while (w = stream.next()) { if (w == '"') break; if (w == '\\') stream.next(); } return 'string'; } else if (stream.eat('\'')) { if (stream.match(/\\?.'/)) return 'number'; } else if (stream.eat('.') || stream.sol() && stream.eat('#')) { state.context = 5; if (stream.eatWhile(/\w/)) return 'def'; } else if (stream.eat('$')) { if (stream.eatWhile(/[\da-f]/i)) return 'number'; } else if (stream.eat('%')) { if (stream.eatWhile(/[01]/)) return 'number'; } else { stream.next(); } return null; } }; }); CodeMirror.defineMIME("text/x-z80", "z80"); CodeMirror.defineMIME("text/x-ez80", { name: "z80", ez80: true }); }); ================================================ FILE: third_party/CodeMirror/package.json ================================================ { "name": "codemirror", "version": "5.43.0", "main": "lib/codemirror.js", "style": "lib/codemirror.css", "author": { "name": "Marijn Haverbeke", "email": "marijnh@gmail.com", "url": "http://marijnhaverbeke.nl" }, "description": "Full-featured in-browser code editor", "license": "MIT", "directories": { "lib": "./lib" }, "scripts": { "build": "rollup -c", "watch": "rollup -w -c", "prepare": "npm run-script build", "test": "node ./test/run.js", "lint": "bin/lint" }, "devDependencies": { "blint": "^1", "node-static": "0.7.11", "phantomjs-prebuilt": "^2.1.12", "rollup": "^0.66.2", "rollup-plugin-buble": "^0.19.2", "rollup-watch": "^4.3.1" }, "bugs": "http://github.com/codemirror/CodeMirror/issues", "keywords": [ "JavaScript", "CodeMirror", "Editor" ], "homepage": "https://codemirror.net", "repository": { "type": "git", "url": "https://github.com/codemirror/CodeMirror.git" }, "jspm": { "directories": {}, "dependencies": {}, "devDependencies": {} } } ================================================ FILE: third_party/CodeMirror/rollup.config.js ================================================ import buble from 'rollup-plugin-buble'; export default { input: "src/codemirror.js", output: { banner: `// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE // This is CodeMirror (https://codemirror.net), a code editor // implemented in JavaScript on top of the browser's DOM. // // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . `, format: "umd", file: "lib/codemirror.js", name: "CodeMirror" }, plugins: [ buble({namedFunctionExpressions: false}) ] }; ================================================ FILE: third_party/CodeMirror/src/codemirror.js ================================================ import { CodeMirror } from "./edit/main.js" export default CodeMirror ================================================ FILE: third_party/CodeMirror/src/display/Display.js ================================================ import { gecko, ie, ie_version, mobile, webkit } from "../util/browser.js" import { elt, eltP } from "../util/dom.js" import { scrollerGap } from "../util/misc.js" // The display handles the DOM integration, both for input reading // and content drawing. It holds references to DOM nodes and // display-related state. export function Display(place, doc, input) { let d = this this.input = input // Covers bottom-right square when both scrollbars are present. d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler") d.scrollbarFiller.setAttribute("cm-not-content", "true") // Covers bottom of gutter when coverGutterNextToScrollbar is on // and h scrollbar is present. d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler") d.gutterFiller.setAttribute("cm-not-content", "true") // Will contain the actual code, positioned to cover the viewport. d.lineDiv = eltP("div", null, "CodeMirror-code") // Elements are added to these to represent selection and cursors. d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1") d.cursorDiv = elt("div", null, "CodeMirror-cursors") // A visibility: hidden element used to find the size of things. d.measure = elt("div", null, "CodeMirror-measure") // When lines outside of the viewport are measured, they are drawn in this. d.lineMeasure = elt("div", null, "CodeMirror-measure") // Wraps everything that needs to exist inside the vertically-padded coordinate system d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], null, "position: relative; outline: none") let lines = eltP("div", [d.lineSpace], "CodeMirror-lines") // Moved around its parent to cover visible view. d.mover = elt("div", [lines], null, "position: relative") // Set to the height of the document, allowing scrolling. d.sizer = elt("div", [d.mover], "CodeMirror-sizer") d.sizerWidth = null // Behavior of elts with overflow: auto and padding is // inconsistent across browsers. This is used to ensure the // scrollable area is big enough. d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;") // Will contain the gutters, if any. d.gutters = elt("div", null, "CodeMirror-gutters") d.lineGutter = null // Actual scrollable element. d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll") d.scroller.setAttribute("tabIndex", "-1") // The element in which the editor lives. d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror") // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0 } if (!webkit && !(gecko && mobile)) d.scroller.draggable = true if (place) { if (place.appendChild) place.appendChild(d.wrapper) else place(d.wrapper) } // Current rendered range (may be bigger than the view window). d.viewFrom = d.viewTo = doc.first d.reportedViewFrom = d.reportedViewTo = doc.first // Information about the rendered lines. d.view = [] d.renderedView = null // Holds info about a single rendered line when it was rendered // for measurement, while not in view. d.externalMeasured = null // Empty space (in pixels) above the view d.viewOffset = 0 d.lastWrapHeight = d.lastWrapWidth = 0 d.updateLineNumbers = null d.nativeBarWidth = d.barHeight = d.barWidth = 0 d.scrollbarsClipped = false // Used to only resize the line number gutter when necessary (when // the amount of lines crosses a boundary that makes its width change) d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null // Set to true when a non-horizontal-scrolling line widget is // added. As an optimization, line widget aligning is skipped when // this is false. d.alignWidgets = false d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null // Tracks the maximum line length so that the horizontal scrollbar // can be kept static when scrolling. d.maxLine = null d.maxLineLength = 0 d.maxLineChanged = false // Used for measuring wheel scrolling granularity d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null // True when shift is held down. d.shift = false // Used to track whether anything happened since the context menu // was opened. d.selForContextMenu = null d.activeTouch = null input.init(d) } ================================================ FILE: third_party/CodeMirror/src/display/focus.js ================================================ import { restartBlink } from "./selection.js" import { webkit } from "../util/browser.js" import { addClass, rmClass } from "../util/dom.js" import { signal } from "../util/event.js" export function ensureFocus(cm) { if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm) } } export function delayBlurEvent(cm) { cm.state.delayingBlurEvent = true setTimeout(() => { if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false onBlur(cm) } }, 100) } export function onFocus(cm, e) { if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false if (cm.options.readOnly == "nocursor") return if (!cm.state.focused) { signal(cm, "focus", cm, e) cm.state.focused = true addClass(cm.display.wrapper, "CodeMirror-focused") // This test prevents this from firing when a context // menu is closed (since the input reset would kill the // select-all detection hack) if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { cm.display.input.reset() if (webkit) setTimeout(() => cm.display.input.reset(true), 20) // Issue #1730 } cm.display.input.receivedFocus() } restartBlink(cm) } export function onBlur(cm, e) { if (cm.state.delayingBlurEvent) return if (cm.state.focused) { signal(cm, "blur", cm, e) cm.state.focused = false rmClass(cm.display.wrapper, "CodeMirror-focused") } clearInterval(cm.display.blinker) setTimeout(() => { if (!cm.state.focused) cm.display.shift = false }, 150) } ================================================ FILE: third_party/CodeMirror/src/display/gutters.js ================================================ import { elt, removeChildren } from "../util/dom.js" import { indexOf } from "../util/misc.js" import { updateGutterSpace } from "./update_display.js" // Rebuild the gutter elements, ensure the margin to the left of the // code matches their width. export function updateGutters(cm) { let gutters = cm.display.gutters, specs = cm.options.gutters removeChildren(gutters) let i = 0 for (; i < specs.length; ++i) { let gutterClass = specs[i] let gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)) if (gutterClass == "CodeMirror-linenumbers") { cm.display.lineGutter = gElt gElt.style.width = (cm.display.lineNumWidth || 1) + "px" } } gutters.style.display = i ? "" : "none" updateGutterSpace(cm) } // Make sure the gutters options contains the element // "CodeMirror-linenumbers" when the lineNumbers option is true. export function setGuttersForLineNumbers(options) { let found = indexOf(options.gutters, "CodeMirror-linenumbers") if (found == -1 && options.lineNumbers) { options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]) } else if (found > -1 && !options.lineNumbers) { options.gutters = options.gutters.slice(0) options.gutters.splice(found, 1) } } ================================================ FILE: third_party/CodeMirror/src/display/highlight_worker.js ================================================ import { getContextBefore, highlightLine, processLine } from "../line/highlight.js" import { copyState } from "../modes.js" import { bind } from "../util/misc.js" import { runInOp } from "./operations.js" import { regLineChange } from "./view_tracking.js" // HIGHLIGHT WORKER export function startWorker(cm, time) { if (cm.doc.highlightFrontier < cm.display.viewTo) cm.state.highlight.set(time, bind(highlightWorker, cm)) } function highlightWorker(cm) { let doc = cm.doc if (doc.highlightFrontier >= cm.display.viewTo) return let end = +new Date + cm.options.workTime let context = getContextBefore(cm, doc.highlightFrontier) let changedLines = [] doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), line => { if (context.line >= cm.display.viewFrom) { // Visible let oldStyles = line.styles let resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null let highlighted = highlightLine(cm, line, context, true) if (resetState) context.state = resetState line.styles = highlighted.styles let oldCls = line.styleClasses, newCls = highlighted.classes if (newCls) line.styleClasses = newCls else if (oldCls) line.styleClasses = null let ischange = !oldStyles || oldStyles.length != line.styles.length || oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass) for (let i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i] if (ischange) changedLines.push(context.line) line.stateAfter = context.save() context.nextLine() } else { if (line.text.length <= cm.options.maxHighlightLength) processLine(cm, line.text, context) line.stateAfter = context.line % 5 == 0 ? context.save() : null context.nextLine() } if (+new Date > end) { startWorker(cm, cm.options.workDelay) return true } }) doc.highlightFrontier = context.line doc.modeFrontier = Math.max(doc.modeFrontier, context.line) if (changedLines.length) runInOp(cm, () => { for (let i = 0; i < changedLines.length; i++) regLineChange(cm, changedLines[i], "text") }) } ================================================ FILE: third_party/CodeMirror/src/display/line_numbers.js ================================================ import { lineNumberFor } from "../line/utils_line.js" import { compensateForHScroll } from "../measurement/position_measurement.js" import { elt } from "../util/dom.js" import { updateGutterSpace } from "./update_display.js" // Re-align line numbers and gutter marks to compensate for // horizontal scrolling. export function alignHorizontally(cm) { let display = cm.display, view = display.view if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return let comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft let gutterW = display.gutters.offsetWidth, left = comp + "px" for (let i = 0; i < view.length; i++) if (!view[i].hidden) { if (cm.options.fixedGutter) { if (view[i].gutter) view[i].gutter.style.left = left if (view[i].gutterBackground) view[i].gutterBackground.style.left = left } let align = view[i].alignable if (align) for (let j = 0; j < align.length; j++) align[j].style.left = left } if (cm.options.fixedGutter) display.gutters.style.left = (comp + gutterW) + "px" } // Used to ensure that the line number gutter is still the right // size for the current document size. Returns true when an update // is needed. export function maybeUpdateLineNumberWidth(cm) { if (!cm.options.lineNumbers) return false let doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display if (last.length != display.lineNumChars) { let test = display.measure.appendChild(elt("div", [elt("div", last)], "CodeMirror-linenumber CodeMirror-gutter-elt")) let innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW display.lineGutter.style.width = "" display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1 display.lineNumWidth = display.lineNumInnerWidth + padding display.lineNumChars = display.lineNumInnerWidth ? last.length : -1 display.lineGutter.style.width = display.lineNumWidth + "px" updateGutterSpace(cm) return true } return false } ================================================ FILE: third_party/CodeMirror/src/display/mode_state.js ================================================ import { getMode } from "../modes.js" import { startWorker } from "./highlight_worker.js" import { regChange } from "./view_tracking.js" // Used to get the editor into a consistent state again when options change. export function loadMode(cm) { cm.doc.mode = getMode(cm.options, cm.doc.modeOption) resetModeState(cm) } export function resetModeState(cm) { cm.doc.iter(line => { if (line.stateAfter) line.stateAfter = null if (line.styles) line.styles = null }) cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first startWorker(cm, 100) cm.state.modeGen++ if (cm.curOp) regChange(cm) } ================================================ FILE: third_party/CodeMirror/src/display/operations.js ================================================ import { clipPos } from "../line/pos.js" import { findMaxLine } from "../line/spans.js" import { displayWidth, measureChar, scrollGap } from "../measurement/position_measurement.js" import { signal } from "../util/event.js" import { activeElt } from "../util/dom.js" import { finishOperation, pushOperation } from "../util/operation_group.js" import { ensureFocus } from "./focus.js" import { measureForScrollbars, updateScrollbars } from "./scrollbars.js" import { restartBlink } from "./selection.js" import { maybeScrollWindow, scrollPosIntoView, setScrollLeft, setScrollTop } from "./scrolling.js" import { DisplayUpdate, maybeClipScrollbars, postUpdateDisplay, setDocumentHeight, updateDisplayIfNeeded } from "./update_display.js" import { updateHeightsInViewport } from "./update_lines.js" // Operations are used to wrap a series of changes to the editor // state in such a way that each change won't have to update the // cursor and display (which would be awkward, slow, and // error-prone). Instead, display updates are batched and then all // combined and executed at once. let nextOpId = 0 // Start a new operation. export function startOperation(cm) { cm.curOp = { cm: cm, viewChanged: false, // Flag that indicates that lines might need to be redrawn startHeight: cm.doc.height, // Used to detect need to update scrollbar forceUpdate: false, // Used to force a redraw updateInput: 0, // Whether to reset the input textarea typing: false, // Whether this reset should be careful to leave existing text (for compositing) changeObjs: null, // Accumulated changes, for firing change events cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already selectionChanged: false, // Whether the selection needs to be redrawn updateMaxLine: false, // Set when the widest line needs to be determined anew scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet scrollToPos: null, // Used to scroll to a specific position focus: false, id: ++nextOpId // Unique ID } pushOperation(cm.curOp) } // Finish an operation, updating the display and signalling delayed events export function endOperation(cm) { let op = cm.curOp if (op) finishOperation(op, group => { for (let i = 0; i < group.ops.length; i++) group.ops[i].cm.curOp = null endOperations(group) }) } // The DOM updates done when an operation finishes are batched so // that the minimum number of relayouts are required. function endOperations(group) { let ops = group.ops for (let i = 0; i < ops.length; i++) // Read DOM endOperation_R1(ops[i]) for (let i = 0; i < ops.length; i++) // Write DOM (maybe) endOperation_W1(ops[i]) for (let i = 0; i < ops.length; i++) // Read DOM endOperation_R2(ops[i]) for (let i = 0; i < ops.length; i++) // Write DOM (maybe) endOperation_W2(ops[i]) for (let i = 0; i < ops.length; i++) // Read DOM endOperation_finish(ops[i]) } function endOperation_R1(op) { let cm = op.cm, display = cm.display maybeClipScrollbars(cm) if (op.updateMaxLine) findMaxLine(cm) op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || op.scrollToPos.to.line >= display.viewTo) || display.maxLineChanged && cm.options.lineWrapping op.update = op.mustUpdate && new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate) } function endOperation_W1(op) { op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update) } function endOperation_R2(op) { let cm = op.cm, display = cm.display if (op.updatedDisplay) updateHeightsInViewport(cm) op.barMeasure = measureForScrollbars(cm) // If the max line changed since it was last measured, measure it, // and ensure the document's width matches it. // updateDisplay_W2 will use these properties to do the actual resizing if (display.maxLineChanged && !cm.options.lineWrapping) { op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3 cm.display.sizerWidth = op.adjustWidthTo op.barMeasure.scrollWidth = Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth) op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)) } if (op.updatedDisplay || op.selectionChanged) op.preparedSelection = display.input.prepareSelection() } function endOperation_W2(op) { let cm = op.cm if (op.adjustWidthTo != null) { cm.display.sizer.style.minWidth = op.adjustWidthTo + "px" if (op.maxScrollLeft < cm.doc.scrollLeft) setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true) cm.display.maxLineChanged = false } let takeFocus = op.focus && op.focus == activeElt() if (op.preparedSelection) cm.display.input.showSelection(op.preparedSelection, takeFocus) if (op.updatedDisplay || op.startHeight != cm.doc.height) updateScrollbars(cm, op.barMeasure) if (op.updatedDisplay) setDocumentHeight(cm, op.barMeasure) if (op.selectionChanged) restartBlink(cm) if (cm.state.focused && op.updateInput) cm.display.input.reset(op.typing) if (takeFocus) ensureFocus(op.cm) } function endOperation_finish(op) { let cm = op.cm, display = cm.display, doc = cm.doc if (op.updatedDisplay) postUpdateDisplay(cm, op.update) // Abort mouse wheel delta measurement, when scrolling explicitly if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) display.wheelStartX = display.wheelStartY = null // Propagate the scroll position to the actual DOM scroller if (op.scrollTop != null) setScrollTop(cm, op.scrollTop, op.forceScroll) if (op.scrollLeft != null) setScrollLeft(cm, op.scrollLeft, true, true) // If we need to scroll a specific position into view, do so. if (op.scrollToPos) { let rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin) maybeScrollWindow(cm, rect) } // Fire events for markers that are hidden/unidden by editing or // undoing let hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers if (hidden) for (let i = 0; i < hidden.length; ++i) if (!hidden[i].lines.length) signal(hidden[i], "hide") if (unhidden) for (let i = 0; i < unhidden.length; ++i) if (unhidden[i].lines.length) signal(unhidden[i], "unhide") if (display.wrapper.offsetHeight) doc.scrollTop = cm.display.scroller.scrollTop // Fire change events, and delayed event handlers if (op.changeObjs) signal(cm, "changes", cm, op.changeObjs) if (op.update) op.update.finish() } // Run the given function in an operation export function runInOp(cm, f) { if (cm.curOp) return f() startOperation(cm) try { return f() } finally { endOperation(cm) } } // Wraps a function in an operation. Returns the wrapped function. export function operation(cm, f) { return function() { if (cm.curOp) return f.apply(cm, arguments) startOperation(cm) try { return f.apply(cm, arguments) } finally { endOperation(cm) } } } // Used to add methods to editor and doc instances, wrapping them in // operations. export function methodOp(f) { return function() { if (this.curOp) return f.apply(this, arguments) startOperation(this) try { return f.apply(this, arguments) } finally { endOperation(this) } } } export function docMethodOp(f) { return function() { let cm = this.cm if (!cm || cm.curOp) return f.apply(this, arguments) startOperation(cm) try { return f.apply(this, arguments) } finally { endOperation(cm) } } } ================================================ FILE: third_party/CodeMirror/src/display/scroll_events.js ================================================ import { chrome, gecko, ie, mac, presto, safari, webkit } from "../util/browser.js" import { e_preventDefault } from "../util/event.js" import { updateDisplaySimple } from "./update_display.js" import { setScrollLeft, updateScrollTop } from "./scrolling.js" // Since the delta values reported on mouse wheel events are // unstandardized between browsers and even browser versions, and // generally horribly unpredictable, this code starts by measuring // the scroll effect that the first few mouse wheel events have, // and, from that, detects the way it can convert deltas to pixel // offsets afterwards. // // The reason we want to know the amount a wheel event will scroll // is that it gives us a chance to update the display before the // actual scrolling happens, reducing flickering. let wheelSamples = 0, wheelPixelsPerUnit = null // Fill in a browser-detected starting value on browsers where we // know one. These don't have to be accurate -- the result of them // being wrong would just be a slight flicker on the first wheel // scroll (if it is large enough). if (ie) wheelPixelsPerUnit = -.53 else if (gecko) wheelPixelsPerUnit = 15 else if (chrome) wheelPixelsPerUnit = -.7 else if (safari) wheelPixelsPerUnit = -1/3 function wheelEventDelta(e) { let dx = e.wheelDeltaX, dy = e.wheelDeltaY if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail else if (dy == null) dy = e.wheelDelta return {x: dx, y: dy} } export function wheelEventPixels(e) { let delta = wheelEventDelta(e) delta.x *= wheelPixelsPerUnit delta.y *= wheelPixelsPerUnit return delta } export function onScrollWheel(cm, e) { let delta = wheelEventDelta(e), dx = delta.x, dy = delta.y let display = cm.display, scroll = display.scroller // Quit if there's nothing to scroll here let canScrollX = scroll.scrollWidth > scroll.clientWidth let canScrollY = scroll.scrollHeight > scroll.clientHeight if (!(dx && canScrollX || dy && canScrollY)) return // Webkit browsers on OS X abort momentum scrolls when the target // of the scroll event is removed from the scrollable element. // This hack (see related code in patchDisplay) makes sure the // element is kept around. if (dy && mac && webkit) { outer: for (let cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { for (let i = 0; i < view.length; i++) { if (view[i].node == cur) { cm.display.currentWheelTarget = cur break outer } } } } // On some browsers, horizontal scrolling will cause redraws to // happen before the gutter has been realigned, causing it to // wriggle around in a most unseemly way. When we have an // estimated pixels/delta value, we just handle horizontal // scrolling entirely here. It'll be slightly off from native, but // better than glitching out. if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { if (dy && canScrollY) updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)) setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)) // Only prevent default scrolling if vertical scrolling is // actually possible. Otherwise, it causes vertical scroll // jitter on OSX trackpads when deltaX is small and deltaY // is large (issue #3579) if (!dy || (dy && canScrollY)) e_preventDefault(e) display.wheelStartX = null // Abort measurement, if in progress return } // 'Project' the visible viewport to cover the area that is being // scrolled into view (if we know enough to estimate it). if (dy && wheelPixelsPerUnit != null) { let pixels = dy * wheelPixelsPerUnit let top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight if (pixels < 0) top = Math.max(0, top + pixels - 50) else bot = Math.min(cm.doc.height, bot + pixels + 50) updateDisplaySimple(cm, {top: top, bottom: bot}) } if (wheelSamples < 20) { if (display.wheelStartX == null) { display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop display.wheelDX = dx; display.wheelDY = dy setTimeout(() => { if (display.wheelStartX == null) return let movedX = scroll.scrollLeft - display.wheelStartX let movedY = scroll.scrollTop - display.wheelStartY let sample = (movedY && display.wheelDY && movedY / display.wheelDY) || (movedX && display.wheelDX && movedX / display.wheelDX) display.wheelStartX = display.wheelStartY = null if (!sample) return wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1) ++wheelSamples }, 200) } else { display.wheelDX += dx; display.wheelDY += dy } } } ================================================ FILE: third_party/CodeMirror/src/display/scrollbars.js ================================================ import { addClass, elt, rmClass } from "../util/dom.js" import { on } from "../util/event.js" import { scrollGap, paddingVert } from "../measurement/position_measurement.js" import { ie, ie_version, mac, mac_geMountainLion } from "../util/browser.js" import { updateHeightsInViewport } from "./update_lines.js" import { Delayed } from "../util/misc.js" import { setScrollLeft, updateScrollTop } from "./scrolling.js" // SCROLLBARS // Prepare DOM reads needed to update the scrollbars. Done in one // shot to minimize update/measure roundtrips. export function measureForScrollbars(cm) { let d = cm.display, gutterW = d.gutters.offsetWidth let docH = Math.round(cm.doc.height + paddingVert(cm.display)) return { clientHeight: d.scroller.clientHeight, viewHeight: d.wrapper.clientHeight, scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, viewWidth: d.wrapper.clientWidth, barLeft: cm.options.fixedGutter ? gutterW : 0, docHeight: docH, scrollHeight: docH + scrollGap(cm) + d.barHeight, nativeBarWidth: d.nativeBarWidth, gutterWidth: gutterW } } class NativeScrollbars { constructor(place, scroll, cm) { this.cm = cm let vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar") let horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar") vert.tabIndex = horiz.tabIndex = -1 place(vert); place(horiz) on(vert, "scroll", () => { if (vert.clientHeight) scroll(vert.scrollTop, "vertical") }) on(horiz, "scroll", () => { if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal") }) this.checkedZeroWidth = false // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px" } update(measure) { let needsH = measure.scrollWidth > measure.clientWidth + 1 let needsV = measure.scrollHeight > measure.clientHeight + 1 let sWidth = measure.nativeBarWidth if (needsV) { this.vert.style.display = "block" this.vert.style.bottom = needsH ? sWidth + "px" : "0" let totalHeight = measure.viewHeight - (needsH ? sWidth : 0) // A bug in IE8 can cause this value to be negative, so guard it. this.vert.firstChild.style.height = Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px" } else { this.vert.style.display = "" this.vert.firstChild.style.height = "0" } if (needsH) { this.horiz.style.display = "block" this.horiz.style.right = needsV ? sWidth + "px" : "0" this.horiz.style.left = measure.barLeft + "px" let totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0) this.horiz.firstChild.style.width = Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px" } else { this.horiz.style.display = "" this.horiz.firstChild.style.width = "0" } if (!this.checkedZeroWidth && measure.clientHeight > 0) { if (sWidth == 0) this.zeroWidthHack() this.checkedZeroWidth = true } return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} } setScrollLeft(pos) { if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos if (this.disableHoriz) this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz") } setScrollTop(pos) { if (this.vert.scrollTop != pos) this.vert.scrollTop = pos if (this.disableVert) this.enableZeroWidthBar(this.vert, this.disableVert, "vert") } zeroWidthHack() { let w = mac && !mac_geMountainLion ? "12px" : "18px" this.horiz.style.height = this.vert.style.width = w this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none" this.disableHoriz = new Delayed this.disableVert = new Delayed } enableZeroWidthBar(bar, delay, type) { bar.style.pointerEvents = "auto" function maybeDisable() { // To find out whether the scrollbar is still visible, we // check whether the element under the pixel in the bottom // right corner of the scrollbar box is the scrollbar box // itself (when the bar is still visible) or its filler child // (when the bar is hidden). If it is still visible, we keep // it enabled, if it's hidden, we disable pointer events. let box = bar.getBoundingClientRect() let elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1) if (elt != bar) bar.style.pointerEvents = "none" else delay.set(1000, maybeDisable) } delay.set(1000, maybeDisable) } clear() { let parent = this.horiz.parentNode parent.removeChild(this.horiz) parent.removeChild(this.vert) } } class NullScrollbars { update() { return {bottom: 0, right: 0} } setScrollLeft() {} setScrollTop() {} clear() {} } export function updateScrollbars(cm, measure) { if (!measure) measure = measureForScrollbars(cm) let startWidth = cm.display.barWidth, startHeight = cm.display.barHeight updateScrollbarsInner(cm, measure) for (let i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { if (startWidth != cm.display.barWidth && cm.options.lineWrapping) updateHeightsInViewport(cm) updateScrollbarsInner(cm, measureForScrollbars(cm)) startWidth = cm.display.barWidth; startHeight = cm.display.barHeight } } // Re-synchronize the fake scrollbars with the actual size of the // content. function updateScrollbarsInner(cm, measure) { let d = cm.display let sizes = d.scrollbars.update(measure) d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px" d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px" d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent" if (sizes.right && sizes.bottom) { d.scrollbarFiller.style.display = "block" d.scrollbarFiller.style.height = sizes.bottom + "px" d.scrollbarFiller.style.width = sizes.right + "px" } else d.scrollbarFiller.style.display = "" if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { d.gutterFiller.style.display = "block" d.gutterFiller.style.height = sizes.bottom + "px" d.gutterFiller.style.width = measure.gutterWidth + "px" } else d.gutterFiller.style.display = "" } export let scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars} export function initScrollbars(cm) { if (cm.display.scrollbars) { cm.display.scrollbars.clear() if (cm.display.scrollbars.addClass) rmClass(cm.display.wrapper, cm.display.scrollbars.addClass) } cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](node => { cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller) // Prevent clicks in the scrollbars from killing focus on(node, "mousedown", () => { if (cm.state.focused) setTimeout(() => cm.display.input.focus(), 0) }) node.setAttribute("cm-not-content", "true") }, (pos, axis) => { if (axis == "horizontal") setScrollLeft(cm, pos) else updateScrollTop(cm, pos) }, cm) if (cm.display.scrollbars.addClass) addClass(cm.display.wrapper, cm.display.scrollbars.addClass) } ================================================ FILE: third_party/CodeMirror/src/display/scrolling.js ================================================ import { Pos } from "../line/pos.js" import { cursorCoords, displayHeight, displayWidth, estimateCoords, paddingTop, paddingVert, scrollGap, textHeight } from "../measurement/position_measurement.js" import { gecko, phantom } from "../util/browser.js" import { elt } from "../util/dom.js" import { signalDOMEvent } from "../util/event.js" import { startWorker } from "./highlight_worker.js" import { alignHorizontally } from "./line_numbers.js" import { updateDisplaySimple } from "./update_display.js" // SCROLLING THINGS INTO VIEW // If an editor sits on the top or bottom of the window, partially // scrolled out of view, this ensures that the cursor is visible. export function maybeScrollWindow(cm, rect) { if (signalDOMEvent(cm, "scrollCursorIntoView")) return let display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null if (rect.top + box.top < 0) doScroll = true else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false if (doScroll != null && !phantom) { let scrollNode = elt("div", "\u200b", null, `position: absolute; top: ${rect.top - display.viewOffset - paddingTop(cm.display)}px; height: ${rect.bottom - rect.top + scrollGap(cm) + display.barHeight}px; left: ${rect.left}px; width: ${Math.max(2, rect.right - rect.left)}px;`) cm.display.lineSpace.appendChild(scrollNode) scrollNode.scrollIntoView(doScroll) cm.display.lineSpace.removeChild(scrollNode) } } // Scroll a given position into view (immediately), verifying that // it actually became visible (as line heights are accurately // measured, the position of something may 'drift' during drawing). export function scrollPosIntoView(cm, pos, end, margin) { if (margin == null) margin = 0 let rect if (!cm.options.lineWrapping && pos == end) { // Set pos and end to the cursor positions around the character pos sticks to // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch // If pos == Pos(_, 0, "before"), pos and end are unchanged pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos } for (let limit = 0; limit < 5; limit++) { let changed = false let coords = cursorCoords(cm, pos) let endCoords = !end || end == pos ? coords : cursorCoords(cm, end) rect = {left: Math.min(coords.left, endCoords.left), top: Math.min(coords.top, endCoords.top) - margin, right: Math.max(coords.left, endCoords.left), bottom: Math.max(coords.bottom, endCoords.bottom) + margin} let scrollPos = calculateScrollPos(cm, rect) let startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop) if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true } if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft) if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true } if (!changed) break } return rect } // Scroll a given set of coordinates into view (immediately). export function scrollIntoView(cm, rect) { let scrollPos = calculateScrollPos(cm, rect) if (scrollPos.scrollTop != null) updateScrollTop(cm, scrollPos.scrollTop) if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft) } // Calculate a new scroll position needed to scroll the given // rectangle into view. Returns an object with scrollTop and // scrollLeft properties. When these are undefined, the // vertical/horizontal position does not need to be adjusted. function calculateScrollPos(cm, rect) { let display = cm.display, snapMargin = textHeight(cm.display) if (rect.top < 0) rect.top = 0 let screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop let screen = displayHeight(cm), result = {} if (rect.bottom - rect.top > screen) rect.bottom = rect.top + screen let docBottom = cm.doc.height + paddingVert(display) let atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin if (rect.top < screentop) { result.scrollTop = atTop ? 0 : rect.top } else if (rect.bottom > screentop + screen) { let newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen) if (newTop != screentop) result.scrollTop = newTop } let screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft let screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0) let tooWide = rect.right - rect.left > screenw if (tooWide) rect.right = rect.left + screenw if (rect.left < 10) result.scrollLeft = 0 else if (rect.left < screenleft) result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)) else if (rect.right > screenw + screenleft - 3) result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw return result } // Store a relative adjustment to the scroll position in the current // operation (to be applied when the operation finishes). export function addToScrollTop(cm, top) { if (top == null) return resolveScrollToPos(cm) cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top } // Make sure that at the end of the operation the current cursor is // shown. export function ensureCursorVisible(cm) { resolveScrollToPos(cm) let cur = cm.getCursor() cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin} } export function scrollToCoords(cm, x, y) { if (x != null || y != null) resolveScrollToPos(cm) if (x != null) cm.curOp.scrollLeft = x if (y != null) cm.curOp.scrollTop = y } export function scrollToRange(cm, range) { resolveScrollToPos(cm) cm.curOp.scrollToPos = range } // When an operation has its scrollToPos property set, and another // scroll action is applied before the end of the operation, this // 'simulates' scrolling that position into view in a cheap way, so // that the effect of intermediate scroll commands is not ignored. function resolveScrollToPos(cm) { let range = cm.curOp.scrollToPos if (range) { cm.curOp.scrollToPos = null let from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to) scrollToCoordsRange(cm, from, to, range.margin) } } export function scrollToCoordsRange(cm, from, to, margin) { let sPos = calculateScrollPos(cm, { left: Math.min(from.left, to.left), top: Math.min(from.top, to.top) - margin, right: Math.max(from.right, to.right), bottom: Math.max(from.bottom, to.bottom) + margin }) scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop) } // Sync the scrollable area and scrollbars, ensure the viewport // covers the visible area. export function updateScrollTop(cm, val) { if (Math.abs(cm.doc.scrollTop - val) < 2) return if (!gecko) updateDisplaySimple(cm, {top: val}) setScrollTop(cm, val, true) if (gecko) updateDisplaySimple(cm) startWorker(cm, 100) } export function setScrollTop(cm, val, forceScroll) { val = Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val) if (cm.display.scroller.scrollTop == val && !forceScroll) return cm.doc.scrollTop = val cm.display.scrollbars.setScrollTop(val) if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val } // Sync scroller and scrollbar, ensure the gutter elements are // aligned. export function setScrollLeft(cm, val, isScroller, forceScroll) { val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth) if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) return cm.doc.scrollLeft = val alignHorizontally(cm) if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val cm.display.scrollbars.setScrollLeft(val) } ================================================ FILE: third_party/CodeMirror/src/display/selection.js ================================================ import { Pos } from "../line/pos.js" import { visualLine } from "../line/spans.js" import { getLine } from "../line/utils_line.js" import { charCoords, cursorCoords, displayWidth, paddingH, wrappedLineExtentChar } from "../measurement/position_measurement.js" import { getOrder, iterateBidiSections } from "../util/bidi.js" import { elt } from "../util/dom.js" export function updateSelection(cm) { cm.display.input.showSelection(cm.display.input.prepareSelection()) } export function prepareSelection(cm, primary = true) { let doc = cm.doc, result = {} let curFragment = result.cursors = document.createDocumentFragment() let selFragment = result.selection = document.createDocumentFragment() for (let i = 0; i < doc.sel.ranges.length; i++) { if (!primary && i == doc.sel.primIndex) continue let range = doc.sel.ranges[i] if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) continue let collapsed = range.empty() if (collapsed || cm.options.showCursorWhenSelecting) drawSelectionCursor(cm, range.head, curFragment) if (!collapsed) drawSelectionRange(cm, range, selFragment) } return result } // Draws a cursor for the given range export function drawSelectionCursor(cm, head, output) { let pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine) let cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")) cursor.style.left = pos.left + "px" cursor.style.top = pos.top + "px" cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px" if (pos.other) { // Secondary cursor, shown when on a 'jump' in bi-directional text let otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")) otherCursor.style.display = "" otherCursor.style.left = pos.other.left + "px" otherCursor.style.top = pos.other.top + "px" otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px" } } function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } // Draws the given range as a highlighted selection function drawSelectionRange(cm, range, output) { let display = cm.display, doc = cm.doc let fragment = document.createDocumentFragment() let padding = paddingH(cm.display), leftSide = padding.left let rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right let docLTR = doc.direction == "ltr" function add(left, top, width, bottom) { if (top < 0) top = 0 top = Math.round(top) bottom = Math.round(bottom) fragment.appendChild(elt("div", null, "CodeMirror-selected", `position: absolute; left: ${left}px; top: ${top}px; width: ${width == null ? rightSide - left : width}px; height: ${bottom - top}px`)) } function drawForLine(line, fromArg, toArg) { let lineObj = getLine(doc, line) let lineLen = lineObj.text.length let start, end function coords(ch, bias) { return charCoords(cm, Pos(line, ch), "div", lineObj, bias) } function wrapX(pos, dir, side) { let extent = wrappedLineExtentChar(cm, lineObj, null, pos) let prop = (dir == "ltr") == (side == "after") ? "left" : "right" let ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1) return coords(ch, prop)[prop] } let order = getOrder(lineObj, doc.direction) iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, (from, to, dir, i) => { let ltr = dir == "ltr" let fromPos = coords(from, ltr ? "left" : "right") let toPos = coords(to - 1, ltr ? "right" : "left") let openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen let first = i == 0, last = !order || i == order.length - 1 if (toPos.top - fromPos.top <= 3) { // Single line let openLeft = (docLTR ? openStart : openEnd) && first let openRight = (docLTR ? openEnd : openStart) && last let left = openLeft ? leftSide : (ltr ? fromPos : toPos).left let right = openRight ? rightSide : (ltr ? toPos : fromPos).right add(left, fromPos.top, right - left, fromPos.bottom) } else { // Multiple lines let topLeft, topRight, botLeft, botRight if (ltr) { topLeft = docLTR && openStart && first ? leftSide : fromPos.left topRight = docLTR ? rightSide : wrapX(from, dir, "before") botLeft = docLTR ? leftSide : wrapX(to, dir, "after") botRight = docLTR && openEnd && last ? rightSide : toPos.right } else { topLeft = !docLTR ? leftSide : wrapX(from, dir, "before") topRight = !docLTR && openStart && first ? rightSide : fromPos.right botLeft = !docLTR && openEnd && last ? leftSide : toPos.left botRight = !docLTR ? rightSide : wrapX(to, dir, "after") } add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom) if (fromPos.bottom < toPos.top) add(leftSide, fromPos.bottom, null, toPos.top) add(botLeft, toPos.top, botRight - botLeft, toPos.bottom) } if (!start || cmpCoords(fromPos, start) < 0) start = fromPos if (cmpCoords(toPos, start) < 0) start = toPos if (!end || cmpCoords(fromPos, end) < 0) end = fromPos if (cmpCoords(toPos, end) < 0) end = toPos }) return {start: start, end: end} } let sFrom = range.from(), sTo = range.to() if (sFrom.line == sTo.line) { drawForLine(sFrom.line, sFrom.ch, sTo.ch) } else { let fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line) let singleVLine = visualLine(fromLine) == visualLine(toLine) let leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end let rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start if (singleVLine) { if (leftEnd.top < rightStart.top - 2) { add(leftEnd.right, leftEnd.top, null, leftEnd.bottom) add(leftSide, rightStart.top, rightStart.left, rightStart.bottom) } else { add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom) } } if (leftEnd.bottom < rightStart.top) add(leftSide, leftEnd.bottom, null, rightStart.top) } output.appendChild(fragment) } // Cursor-blinking export function restartBlink(cm) { if (!cm.state.focused) return let display = cm.display clearInterval(display.blinker) let on = true display.cursorDiv.style.visibility = "" if (cm.options.cursorBlinkRate > 0) display.blinker = setInterval(() => display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden", cm.options.cursorBlinkRate) else if (cm.options.cursorBlinkRate < 0) display.cursorDiv.style.visibility = "hidden" } ================================================ FILE: third_party/CodeMirror/src/display/update_display.js ================================================ import { sawCollapsedSpans } from "../line/saw_special_spans.js" import { heightAtLine, visualLineEndNo, visualLineNo } from "../line/spans.js" import { getLine, lineNumberFor } from "../line/utils_line.js" import { displayHeight, displayWidth, getDimensions, paddingVert, scrollGap } from "../measurement/position_measurement.js" import { mac, webkit } from "../util/browser.js" import { activeElt, removeChildren, contains } from "../util/dom.js" import { hasHandler, signal } from "../util/event.js" import { indexOf } from "../util/misc.js" import { buildLineElement, updateLineForChanges } from "./update_line.js" import { startWorker } from "./highlight_worker.js" import { maybeUpdateLineNumberWidth } from "./line_numbers.js" import { measureForScrollbars, updateScrollbars } from "./scrollbars.js" import { updateSelection } from "./selection.js" import { updateHeightsInViewport, visibleLines } from "./update_lines.js" import { adjustView, countDirtyView, resetView } from "./view_tracking.js" // DISPLAY DRAWING export class DisplayUpdate { constructor(cm, viewport, force) { let display = cm.display this.viewport = viewport // Store some values that we'll need later (but don't want to force a relayout for) this.visible = visibleLines(display, cm.doc, viewport) this.editorIsHidden = !display.wrapper.offsetWidth this.wrapperHeight = display.wrapper.clientHeight this.wrapperWidth = display.wrapper.clientWidth this.oldDisplayWidth = displayWidth(cm) this.force = force this.dims = getDimensions(cm) this.events = [] } signal(emitter, type) { if (hasHandler(emitter, type)) this.events.push(arguments) } finish() { for (let i = 0; i < this.events.length; i++) signal.apply(null, this.events[i]) } } export function maybeClipScrollbars(cm) { let display = cm.display if (!display.scrollbarsClipped && display.scroller.offsetWidth) { display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth display.heightForcer.style.height = scrollGap(cm) + "px" display.sizer.style.marginBottom = -display.nativeBarWidth + "px" display.sizer.style.borderRightWidth = scrollGap(cm) + "px" display.scrollbarsClipped = true } } function selectionSnapshot(cm) { if (cm.hasFocus()) return null let active = activeElt() if (!active || !contains(cm.display.lineDiv, active)) return null let result = {activeElt: active} if (window.getSelection) { let sel = window.getSelection() if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { result.anchorNode = sel.anchorNode result.anchorOffset = sel.anchorOffset result.focusNode = sel.focusNode result.focusOffset = sel.focusOffset } } return result } function restoreSelection(snapshot) { if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) return snapshot.activeElt.focus() if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { let sel = window.getSelection(), range = document.createRange() range.setEnd(snapshot.anchorNode, snapshot.anchorOffset) range.collapse(false) sel.removeAllRanges() sel.addRange(range) sel.extend(snapshot.focusNode, snapshot.focusOffset) } } // Does the actual updating of the line display. Bails out // (returning false) when there is nothing to be done and forced is // false. export function updateDisplayIfNeeded(cm, update) { let display = cm.display, doc = cm.doc if (update.editorIsHidden) { resetView(cm) return false } // Bail out if the visible area is already rendered and nothing changed. if (!update.force && update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && display.renderedView == display.view && countDirtyView(cm) == 0) return false if (maybeUpdateLineNumberWidth(cm)) { resetView(cm) update.dims = getDimensions(cm) } // Compute a suitable new viewport (from & to) let end = doc.first + doc.size let from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first) let to = Math.min(end, update.visible.to + cm.options.viewportMargin) if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom) if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo) if (sawCollapsedSpans) { from = visualLineNo(cm.doc, from) to = visualLineEndNo(cm.doc, to) } let different = from != display.viewFrom || to != display.viewTo || display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth adjustView(cm, from, to) display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)) // Position the mover div to align with the current scroll position cm.display.mover.style.top = display.viewOffset + "px" let toUpdate = countDirtyView(cm) if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) return false // For big changes, we hide the enclosing element during the // update, since that speeds up the operations on most browsers. let selSnapshot = selectionSnapshot(cm) if (toUpdate > 4) display.lineDiv.style.display = "none" patchDisplay(cm, display.updateLineNumbers, update.dims) if (toUpdate > 4) display.lineDiv.style.display = "" display.renderedView = display.view // There might have been a widget with a focused element that got // hidden or updated, if so re-focus it. restoreSelection(selSnapshot) // Prevent selection and cursors from interfering with the scroll // width and height. removeChildren(display.cursorDiv) removeChildren(display.selectionDiv) display.gutters.style.height = display.sizer.style.minHeight = 0 if (different) { display.lastWrapHeight = update.wrapperHeight display.lastWrapWidth = update.wrapperWidth startWorker(cm, 400) } display.updateLineNumbers = null return true } export function postUpdateDisplay(cm, update) { let viewport = update.viewport for (let first = true;; first = false) { if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { // Clip forced viewport to actual scrollable area. if (viewport && viewport.top != null) viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)} // Updated line heights might result in the drawn area not // actually covering the viewport. Keep looping until it does. update.visible = visibleLines(cm.display, cm.doc, viewport) if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) break } if (!updateDisplayIfNeeded(cm, update)) break updateHeightsInViewport(cm) let barMeasure = measureForScrollbars(cm) updateSelection(cm) updateScrollbars(cm, barMeasure) setDocumentHeight(cm, barMeasure) update.force = false } update.signal(cm, "update", cm) if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo) cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo } } export function updateDisplaySimple(cm, viewport) { let update = new DisplayUpdate(cm, viewport) if (updateDisplayIfNeeded(cm, update)) { updateHeightsInViewport(cm) postUpdateDisplay(cm, update) let barMeasure = measureForScrollbars(cm) updateSelection(cm) updateScrollbars(cm, barMeasure) setDocumentHeight(cm, barMeasure) update.finish() } } // Sync the actual display DOM structure with display.view, removing // nodes for lines that are no longer in view, and creating the ones // that are not there yet, and updating the ones that are out of // date. function patchDisplay(cm, updateNumbersFrom, dims) { let display = cm.display, lineNumbers = cm.options.lineNumbers let container = display.lineDiv, cur = container.firstChild function rm(node) { let next = node.nextSibling // Works around a throw-scroll bug in OS X Webkit if (webkit && mac && cm.display.currentWheelTarget == node) node.style.display = "none" else node.parentNode.removeChild(node) return next } let view = display.view, lineN = display.viewFrom // Loop over the elements in the view, syncing cur (the DOM nodes // in display.lineDiv) with the view as we go. for (let i = 0; i < view.length; i++) { let lineView = view[i] if (lineView.hidden) { } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet let node = buildLineElement(cm, lineView, lineN, dims) container.insertBefore(node, cur) } else { // Already drawn while (cur != lineView.node) cur = rm(cur) let updateNumber = lineNumbers && updateNumbersFrom != null && updateNumbersFrom <= lineN && lineView.lineNumber if (lineView.changes) { if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false updateLineForChanges(cm, lineView, lineN, dims) } if (updateNumber) { removeChildren(lineView.lineNumber) lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))) } cur = lineView.node.nextSibling } lineN += lineView.size } while (cur) cur = rm(cur) } export function updateGutterSpace(cm) { let width = cm.display.gutters.offsetWidth cm.display.sizer.style.marginLeft = width + "px" } export function setDocumentHeight(cm, measure) { cm.display.sizer.style.minHeight = measure.docHeight + "px" cm.display.heightForcer.style.top = measure.docHeight + "px" cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px" } ================================================ FILE: third_party/CodeMirror/src/display/update_line.js ================================================ import { buildLineContent } from "../line/line_data.js" import { lineNumberFor } from "../line/utils_line.js" import { ie, ie_version } from "../util/browser.js" import { elt } from "../util/dom.js" import { signalLater } from "../util/operation_group.js" // When an aspect of a line changes, a string is added to // lineView.changes. This updates the relevant part of the line's // DOM structure. export function updateLineForChanges(cm, lineView, lineN, dims) { for (let j = 0; j < lineView.changes.length; j++) { let type = lineView.changes[j] if (type == "text") updateLineText(cm, lineView) else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims) else if (type == "class") updateLineClasses(cm, lineView) else if (type == "widget") updateLineWidgets(cm, lineView, dims) } lineView.changes = null } // Lines with gutter elements, widgets or a background class need to // be wrapped, and have the extra elements added to the wrapper div function ensureLineWrapped(lineView) { if (lineView.node == lineView.text) { lineView.node = elt("div", null, null, "position: relative") if (lineView.text.parentNode) lineView.text.parentNode.replaceChild(lineView.node, lineView.text) lineView.node.appendChild(lineView.text) if (ie && ie_version < 8) lineView.node.style.zIndex = 2 } return lineView.node } function updateLineBackground(cm, lineView) { let cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass if (cls) cls += " CodeMirror-linebackground" if (lineView.background) { if (cls) lineView.background.className = cls else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null } } else if (cls) { let wrap = ensureLineWrapped(lineView) lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild) cm.display.input.setUneditable(lineView.background) } } // Wrapper around buildLineContent which will reuse the structure // in display.externalMeasured when possible. function getLineContent(cm, lineView) { let ext = cm.display.externalMeasured if (ext && ext.line == lineView.line) { cm.display.externalMeasured = null lineView.measure = ext.measure return ext.built } return buildLineContent(cm, lineView) } // Redraw the line's text. Interacts with the background and text // classes because the mode may output tokens that influence these // classes. function updateLineText(cm, lineView) { let cls = lineView.text.className let built = getLineContent(cm, lineView) if (lineView.text == lineView.node) lineView.node = built.pre lineView.text.parentNode.replaceChild(built.pre, lineView.text) lineView.text = built.pre if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { lineView.bgClass = built.bgClass lineView.textClass = built.textClass updateLineClasses(cm, lineView) } else if (cls) { lineView.text.className = cls } } function updateLineClasses(cm, lineView) { updateLineBackground(cm, lineView) if (lineView.line.wrapClass) ensureLineWrapped(lineView).className = lineView.line.wrapClass else if (lineView.node != lineView.text) lineView.node.className = "" let textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass lineView.text.className = textClass || "" } function updateLineGutter(cm, lineView, lineN, dims) { if (lineView.gutter) { lineView.node.removeChild(lineView.gutter) lineView.gutter = null } if (lineView.gutterBackground) { lineView.node.removeChild(lineView.gutterBackground) lineView.gutterBackground = null } if (lineView.line.gutterClass) { let wrap = ensureLineWrapped(lineView) lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, `left: ${cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth}px; width: ${dims.gutterTotalWidth}px`) cm.display.input.setUneditable(lineView.gutterBackground) wrap.insertBefore(lineView.gutterBackground, lineView.text) } let markers = lineView.line.gutterMarkers if (cm.options.lineNumbers || markers) { let wrap = ensureLineWrapped(lineView) let gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", `left: ${cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth}px`) cm.display.input.setUneditable(gutterWrap) wrap.insertBefore(gutterWrap, lineView.text) if (lineView.line.gutterClass) gutterWrap.className += " " + lineView.line.gutterClass if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) lineView.lineNumber = gutterWrap.appendChild( elt("div", lineNumberFor(cm.options, lineN), "CodeMirror-linenumber CodeMirror-gutter-elt", `left: ${dims.gutterLeft["CodeMirror-linenumbers"]}px; width: ${cm.display.lineNumInnerWidth}px`)) if (markers) for (let k = 0; k < cm.options.gutters.length; ++k) { let id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id] if (found) gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", `left: ${dims.gutterLeft[id]}px; width: ${dims.gutterWidth[id]}px`)) } } } function updateLineWidgets(cm, lineView, dims) { if (lineView.alignable) lineView.alignable = null for (let node = lineView.node.firstChild, next; node; node = next) { next = node.nextSibling if (node.className == "CodeMirror-linewidget") lineView.node.removeChild(node) } insertLineWidgets(cm, lineView, dims) } // Build a line's DOM representation from scratch export function buildLineElement(cm, lineView, lineN, dims) { let built = getLineContent(cm, lineView) lineView.text = lineView.node = built.pre if (built.bgClass) lineView.bgClass = built.bgClass if (built.textClass) lineView.textClass = built.textClass updateLineClasses(cm, lineView) updateLineGutter(cm, lineView, lineN, dims) insertLineWidgets(cm, lineView, dims) return lineView.node } // A lineView may contain multiple logical lines (when merged by // collapsed spans). The widgets for all of them need to be drawn. function insertLineWidgets(cm, lineView, dims) { insertLineWidgetsFor(cm, lineView.line, lineView, dims, true) if (lineView.rest) for (let i = 0; i < lineView.rest.length; i++) insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false) } function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { if (!line.widgets) return let wrap = ensureLineWrapped(lineView) for (let i = 0, ws = line.widgets; i < ws.length; ++i) { let widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget") if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true") positionLineWidget(widget, node, lineView, dims) cm.display.input.setUneditable(node) if (allowAbove && widget.above) wrap.insertBefore(node, lineView.gutter || lineView.text) else wrap.appendChild(node) signalLater(widget, "redraw") } } function positionLineWidget(widget, node, lineView, dims) { if (widget.noHScroll) { ;(lineView.alignable || (lineView.alignable = [])).push(node) let width = dims.wrapperWidth node.style.left = dims.fixedPos + "px" if (!widget.coverGutter) { width -= dims.gutterTotalWidth node.style.paddingLeft = dims.gutterTotalWidth + "px" } node.style.width = width + "px" } if (widget.coverGutter) { node.style.zIndex = 5 node.style.position = "relative" if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px" } } ================================================ FILE: third_party/CodeMirror/src/display/update_lines.js ================================================ import { heightAtLine } from "../line/spans.js" import { getLine, lineAtHeight, updateLineHeight } from "../line/utils_line.js" import { paddingTop, textHeight, charWidth } from "../measurement/position_measurement.js" import { ie, ie_version } from "../util/browser.js" // Read the actual heights of the rendered lines, and update their // stored heights to match. export function updateHeightsInViewport(cm) { let display = cm.display let prevBottom = display.lineDiv.offsetTop for (let i = 0; i < display.view.length; i++) { let cur = display.view[i], wrapping = cm.options.lineWrapping let height, width = 0 if (cur.hidden) continue if (ie && ie_version < 8) { let bot = cur.node.offsetTop + cur.node.offsetHeight height = bot - prevBottom prevBottom = bot } else { let box = cur.node.getBoundingClientRect() height = box.bottom - box.top // Check that lines don't extend past the right of the current // editor width if (!wrapping && cur.text.firstChild) width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1 } let diff = cur.line.height - height if (height < 2) height = textHeight(display) if (diff > .005 || diff < -.005) { updateLineHeight(cur.line, height) updateWidgetHeight(cur.line) if (cur.rest) for (let j = 0; j < cur.rest.length; j++) updateWidgetHeight(cur.rest[j]) } if (width > cm.display.sizerWidth) { let chWidth = Math.ceil(width / charWidth(cm.display)) if (chWidth > cm.display.maxLineLength) { cm.display.maxLineLength = chWidth cm.display.maxLine = cur.line cm.display.maxLineChanged = true } } } } // Read and store the height of line widgets associated with the // given line. function updateWidgetHeight(line) { if (line.widgets) for (let i = 0; i < line.widgets.length; ++i) { let w = line.widgets[i], parent = w.node.parentNode if (parent) w.height = parent.offsetHeight } } // Compute the lines that are visible in a given viewport (defaults // the the current scroll position). viewport may contain top, // height, and ensure (see op.scrollToPos) properties. export function visibleLines(display, doc, viewport) { let top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop top = Math.floor(top - paddingTop(display)) let bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight let from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom) // Ensure is a {from: {line, ch}, to: {line, ch}} object, and // forces those lines into the viewport (if possible). if (viewport && viewport.ensure) { let ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line if (ensureFrom < from) { from = ensureFrom to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight) } else if (Math.min(ensureTo, doc.lastLine()) >= to) { from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight) to = ensureTo } } return {from: from, to: Math.max(to, from + 1)} } ================================================ FILE: third_party/CodeMirror/src/display/view_tracking.js ================================================ import { buildViewArray } from "../line/line_data.js" import { sawCollapsedSpans } from "../line/saw_special_spans.js" import { visualLineEndNo, visualLineNo } from "../line/spans.js" import { findViewIndex } from "../measurement/position_measurement.js" import { indexOf } from "../util/misc.js" // Updates the display.view data structure for a given change to the // document. From and to are in pre-change coordinates. Lendiff is // the amount of lines added or subtracted by the change. This is // used for changes that span multiple lines, or change the way // lines are divided into visual lines. regLineChange (below) // registers single-line changes. export function regChange(cm, from, to, lendiff) { if (from == null) from = cm.doc.first if (to == null) to = cm.doc.first + cm.doc.size if (!lendiff) lendiff = 0 let display = cm.display if (lendiff && to < display.viewTo && (display.updateLineNumbers == null || display.updateLineNumbers > from)) display.updateLineNumbers = from cm.curOp.viewChanged = true if (from >= display.viewTo) { // Change after if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) resetView(cm) } else if (to <= display.viewFrom) { // Change before if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { resetView(cm) } else { display.viewFrom += lendiff display.viewTo += lendiff } } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap resetView(cm) } else if (from <= display.viewFrom) { // Top overlap let cut = viewCuttingPoint(cm, to, to + lendiff, 1) if (cut) { display.view = display.view.slice(cut.index) display.viewFrom = cut.lineN display.viewTo += lendiff } else { resetView(cm) } } else if (to >= display.viewTo) { // Bottom overlap let cut = viewCuttingPoint(cm, from, from, -1) if (cut) { display.view = display.view.slice(0, cut.index) display.viewTo = cut.lineN } else { resetView(cm) } } else { // Gap in the middle let cutTop = viewCuttingPoint(cm, from, from, -1) let cutBot = viewCuttingPoint(cm, to, to + lendiff, 1) if (cutTop && cutBot) { display.view = display.view.slice(0, cutTop.index) .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) .concat(display.view.slice(cutBot.index)) display.viewTo += lendiff } else { resetView(cm) } } let ext = display.externalMeasured if (ext) { if (to < ext.lineN) ext.lineN += lendiff else if (from < ext.lineN + ext.size) display.externalMeasured = null } } // Register a change to a single line. Type must be one of "text", // "gutter", "class", "widget" export function regLineChange(cm, line, type) { cm.curOp.viewChanged = true let display = cm.display, ext = cm.display.externalMeasured if (ext && line >= ext.lineN && line < ext.lineN + ext.size) display.externalMeasured = null if (line < display.viewFrom || line >= display.viewTo) return let lineView = display.view[findViewIndex(cm, line)] if (lineView.node == null) return let arr = lineView.changes || (lineView.changes = []) if (indexOf(arr, type) == -1) arr.push(type) } // Clear the view. export function resetView(cm) { cm.display.viewFrom = cm.display.viewTo = cm.doc.first cm.display.view = [] cm.display.viewOffset = 0 } function viewCuttingPoint(cm, oldN, newN, dir) { let index = findViewIndex(cm, oldN), diff, view = cm.display.view if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) return {index: index, lineN: newN} let n = cm.display.viewFrom for (let i = 0; i < index; i++) n += view[i].size if (n != oldN) { if (dir > 0) { if (index == view.length - 1) return null diff = (n + view[index].size) - oldN index++ } else { diff = n - oldN } oldN += diff; newN += diff } while (visualLineNo(cm.doc, newN) != newN) { if (index == (dir < 0 ? 0 : view.length - 1)) return null newN += dir * view[index - (dir < 0 ? 1 : 0)].size index += dir } return {index: index, lineN: newN} } // Force the view to cover a given range, adding empty view element // or clipping off existing ones as needed. export function adjustView(cm, from, to) { let display = cm.display, view = display.view if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { display.view = buildViewArray(cm, from, to) display.viewFrom = from } else { if (display.viewFrom > from) display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view) else if (display.viewFrom < from) display.view = display.view.slice(findViewIndex(cm, from)) display.viewFrom = from if (display.viewTo < to) display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)) else if (display.viewTo > to) display.view = display.view.slice(0, findViewIndex(cm, to)) } display.viewTo = to } // Count the number of lines in the view whose DOM representation is // out of date (or nonexistent). export function countDirtyView(cm) { let view = cm.display.view, dirty = 0 for (let i = 0; i < view.length; i++) { let lineView = view[i] if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty } return dirty } ================================================ FILE: third_party/CodeMirror/src/edit/CodeMirror.js ================================================ import { Display } from "../display/Display.js" import { onFocus, onBlur } from "../display/focus.js" import { setGuttersForLineNumbers, updateGutters } from "../display/gutters.js" import { maybeUpdateLineNumberWidth } from "../display/line_numbers.js" import { endOperation, operation, startOperation } from "../display/operations.js" import { initScrollbars } from "../display/scrollbars.js" import { onScrollWheel } from "../display/scroll_events.js" import { setScrollLeft, updateScrollTop } from "../display/scrolling.js" import { clipPos, Pos } from "../line/pos.js" import { posFromMouse } from "../measurement/position_measurement.js" import { eventInWidget } from "../measurement/widgets.js" import Doc from "../model/Doc.js" import { attachDoc } from "../model/document_data.js" import { Range } from "../model/selection.js" import { extendSelection } from "../model/selection_updates.js" import { ie, ie_version, mobile, webkit } from "../util/browser.js" import { e_preventDefault, e_stop, on, signal, signalDOMEvent } from "../util/event.js" import { bind, copyObj, Delayed } from "../util/misc.js" import { clearDragCursor, onDragOver, onDragStart, onDrop } from "./drop_events.js" import { ensureGlobalHandlers } from "./global_events.js" import { onKeyDown, onKeyPress, onKeyUp } from "./key_events.js" import { clickInGutter, onContextMenu, onMouseDown } from "./mouse_events.js" import { themeChanged } from "./utils.js" import { defaults, optionHandlers, Init } from "./options.js" // A CodeMirror instance represents an editor. This is the object // that user code is usually dealing with. export function CodeMirror(place, options) { if (!(this instanceof CodeMirror)) return new CodeMirror(place, options) this.options = options = options ? copyObj(options) : {} // Determine effective options based on given values and defaults. copyObj(defaults, options, false) setGuttersForLineNumbers(options) let doc = options.value if (typeof doc == "string") doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction) else if (options.mode) doc.modeOption = options.mode this.doc = doc let input = new CodeMirror.inputStyles[options.inputStyle](this) let display = this.display = new Display(place, doc, input) display.wrapper.CodeMirror = this updateGutters(this) themeChanged(this) if (options.lineWrapping) this.display.wrapper.className += " CodeMirror-wrap" initScrollbars(this) this.state = { keyMaps: [], // stores maps added by addKeyMap overlays: [], // highlighting overlays, as added by addOverlay modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info overwrite: false, delayingBlurEvent: false, focused: false, suppressEdits: false, // used to disable editing during key handlers when in readOnly mode pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll selectingText: false, draggingText: false, highlight: new Delayed(), // stores highlight worker timeout keySeq: null, // Unfinished key sequence specialChars: null } if (options.autofocus && !mobile) display.input.focus() // Override magic textarea content restore that IE sometimes does // on our hidden textarea on reload if (ie && ie_version < 11) setTimeout(() => this.display.input.reset(true), 20) registerEventHandlers(this) ensureGlobalHandlers() startOperation(this) this.curOp.forceUpdate = true attachDoc(this, doc) if ((options.autofocus && !mobile) || this.hasFocus()) setTimeout(bind(onFocus, this), 20) else onBlur(this) for (let opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) optionHandlers[opt](this, options[opt], Init) maybeUpdateLineNumberWidth(this) if (options.finishInit) options.finishInit(this) for (let i = 0; i < initHooks.length; ++i) initHooks[i](this) endOperation(this) // Suppress optimizelegibility in Webkit, since it breaks text // measuring on line wrapping boundaries. if (webkit && options.lineWrapping && getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") display.lineDiv.style.textRendering = "auto" } // The default configuration options. CodeMirror.defaults = defaults // Functions to run when options are changed. CodeMirror.optionHandlers = optionHandlers export default CodeMirror // Attach the necessary event handlers when initializing the editor function registerEventHandlers(cm) { let d = cm.display on(d.scroller, "mousedown", operation(cm, onMouseDown)) // Older IE's will not fire a second mousedown for a double click if (ie && ie_version < 11) on(d.scroller, "dblclick", operation(cm, e => { if (signalDOMEvent(cm, e)) return let pos = posFromMouse(cm, e) if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return e_preventDefault(e) let word = cm.findWordAt(pos) extendSelection(cm.doc, word.anchor, word.head) })) else on(d.scroller, "dblclick", e => signalDOMEvent(cm, e) || e_preventDefault(e)) // Some browsers fire contextmenu *after* opening the menu, at // which point we can't mess with it anymore. Context menu is // handled in onMouseDown for these browsers. on(d.scroller, "contextmenu", e => onContextMenu(cm, e)) // Used to suppress mouse event handling when a touch happens let touchFinished, prevTouch = {end: 0} function finishTouch() { if (d.activeTouch) { touchFinished = setTimeout(() => d.activeTouch = null, 1000) prevTouch = d.activeTouch prevTouch.end = +new Date } } function isMouseLikeTouchEvent(e) { if (e.touches.length != 1) return false let touch = e.touches[0] return touch.radiusX <= 1 && touch.radiusY <= 1 } function farAway(touch, other) { if (other.left == null) return true let dx = other.left - touch.left, dy = other.top - touch.top return dx * dx + dy * dy > 20 * 20 } on(d.scroller, "touchstart", e => { if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { d.input.ensurePolled() clearTimeout(touchFinished) let now = +new Date d.activeTouch = {start: now, moved: false, prev: now - prevTouch.end <= 300 ? prevTouch : null} if (e.touches.length == 1) { d.activeTouch.left = e.touches[0].pageX d.activeTouch.top = e.touches[0].pageY } } }) on(d.scroller, "touchmove", () => { if (d.activeTouch) d.activeTouch.moved = true }) on(d.scroller, "touchend", e => { let touch = d.activeTouch if (touch && !eventInWidget(d, e) && touch.left != null && !touch.moved && new Date - touch.start < 300) { let pos = cm.coordsChar(d.activeTouch, "page"), range if (!touch.prev || farAway(touch, touch.prev)) // Single tap range = new Range(pos, pos) else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap range = cm.findWordAt(pos) else // Triple tap range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) cm.setSelection(range.anchor, range.head) cm.focus() e_preventDefault(e) } finishTouch() }) on(d.scroller, "touchcancel", finishTouch) // Sync scrolling between fake scrollbars and real scrollable // area, ensure viewport is updated when scrolling. on(d.scroller, "scroll", () => { if (d.scroller.clientHeight) { updateScrollTop(cm, d.scroller.scrollTop) setScrollLeft(cm, d.scroller.scrollLeft, true) signal(cm, "scroll", cm) } }) // Listen to wheel events in order to try and update the viewport on time. on(d.scroller, "mousewheel", e => onScrollWheel(cm, e)) on(d.scroller, "DOMMouseScroll", e => onScrollWheel(cm, e)) // Prevent wrapper from ever scrolling on(d.wrapper, "scroll", () => d.wrapper.scrollTop = d.wrapper.scrollLeft = 0) d.dragFunctions = { enter: e => {if (!signalDOMEvent(cm, e)) e_stop(e)}, over: e => {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e) }}, start: e => onDragStart(cm, e), drop: operation(cm, onDrop), leave: e => {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm) }} } let inp = d.input.getField() on(inp, "keyup", e => onKeyUp.call(cm, e)) on(inp, "keydown", operation(cm, onKeyDown)) on(inp, "keypress", operation(cm, onKeyPress)) on(inp, "focus", e => onFocus(cm, e)) on(inp, "blur", e => onBlur(cm, e)) } let initHooks = [] CodeMirror.defineInitHook = f => initHooks.push(f) ================================================ FILE: third_party/CodeMirror/src/edit/commands.js ================================================ import { deleteNearSelection } from "./deleteNearSelection.js" import { runInOp } from "../display/operations.js" import { ensureCursorVisible } from "../display/scrolling.js" import { endOfLine } from "../input/movement.js" import { clipPos, Pos } from "../line/pos.js" import { visualLine, visualLineEnd } from "../line/spans.js" import { getLine, lineNo } from "../line/utils_line.js" import { Range } from "../model/selection.js" import { selectAll } from "../model/selection_updates.js" import { countColumn, sel_dontScroll, sel_move, spaceStr } from "../util/misc.js" import { getOrder } from "../util/bidi.js" // Commands are parameter-less actions that can be performed on an // editor, mostly used for keybindings. export let commands = { selectAll: selectAll, singleSelection: cm => cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll), killLine: cm => deleteNearSelection(cm, range => { if (range.empty()) { let len = getLine(cm.doc, range.head.line).text.length if (range.head.ch == len && range.head.line < cm.lastLine()) return {from: range.head, to: Pos(range.head.line + 1, 0)} else return {from: range.head, to: Pos(range.head.line, len)} } else { return {from: range.from(), to: range.to()} } }), deleteLine: cm => deleteNearSelection(cm, range => ({ from: Pos(range.from().line, 0), to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) })), delLineLeft: cm => deleteNearSelection(cm, range => ({ from: Pos(range.from().line, 0), to: range.from() })), delWrappedLineLeft: cm => deleteNearSelection(cm, range => { let top = cm.charCoords(range.head, "div").top + 5 let leftPos = cm.coordsChar({left: 0, top: top}, "div") return {from: leftPos, to: range.from()} }), delWrappedLineRight: cm => deleteNearSelection(cm, range => { let top = cm.charCoords(range.head, "div").top + 5 let rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") return {from: range.from(), to: rightPos } }), undo: cm => cm.undo(), redo: cm => cm.redo(), undoSelection: cm => cm.undoSelection(), redoSelection: cm => cm.redoSelection(), goDocStart: cm => cm.extendSelection(Pos(cm.firstLine(), 0)), goDocEnd: cm => cm.extendSelection(Pos(cm.lastLine())), goLineStart: cm => cm.extendSelectionsBy(range => lineStart(cm, range.head.line), {origin: "+move", bias: 1} ), goLineStartSmart: cm => cm.extendSelectionsBy(range => lineStartSmart(cm, range.head), {origin: "+move", bias: 1} ), goLineEnd: cm => cm.extendSelectionsBy(range => lineEnd(cm, range.head.line), {origin: "+move", bias: -1} ), goLineRight: cm => cm.extendSelectionsBy(range => { let top = cm.cursorCoords(range.head, "div").top + 5 return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") }, sel_move), goLineLeft: cm => cm.extendSelectionsBy(range => { let top = cm.cursorCoords(range.head, "div").top + 5 return cm.coordsChar({left: 0, top: top}, "div") }, sel_move), goLineLeftSmart: cm => cm.extendSelectionsBy(range => { let top = cm.cursorCoords(range.head, "div").top + 5 let pos = cm.coordsChar({left: 0, top: top}, "div") if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head) return pos }, sel_move), goLineUp: cm => cm.moveV(-1, "line"), goLineDown: cm => cm.moveV(1, "line"), goPageUp: cm => cm.moveV(-1, "page"), goPageDown: cm => cm.moveV(1, "page"), goCharLeft: cm => cm.moveH(-1, "char"), goCharRight: cm => cm.moveH(1, "char"), goColumnLeft: cm => cm.moveH(-1, "column"), goColumnRight: cm => cm.moveH(1, "column"), goWordLeft: cm => cm.moveH(-1, "word"), goGroupRight: cm => cm.moveH(1, "group"), goGroupLeft: cm => cm.moveH(-1, "group"), goWordRight: cm => cm.moveH(1, "word"), delCharBefore: cm => cm.deleteH(-1, "char"), delCharAfter: cm => cm.deleteH(1, "char"), delWordBefore: cm => cm.deleteH(-1, "word"), delWordAfter: cm => cm.deleteH(1, "word"), delGroupBefore: cm => cm.deleteH(-1, "group"), delGroupAfter: cm => cm.deleteH(1, "group"), indentAuto: cm => cm.indentSelection("smart"), indentMore: cm => cm.indentSelection("add"), indentLess: cm => cm.indentSelection("subtract"), insertTab: cm => cm.replaceSelection("\t"), insertSoftTab: cm => { let spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize for (let i = 0; i < ranges.length; i++) { let pos = ranges[i].from() let col = countColumn(cm.getLine(pos.line), pos.ch, tabSize) spaces.push(spaceStr(tabSize - col % tabSize)) } cm.replaceSelections(spaces) }, defaultTab: cm => { if (cm.somethingSelected()) cm.indentSelection("add") else cm.execCommand("insertTab") }, // Swap the two chars left and right of each selection's head. // Move cursor behind the two swapped characters afterwards. // // Doesn't consider line feeds a character. // Doesn't scan more than one line above to find a character. // Doesn't do anything on an empty line. // Doesn't do anything with non-empty selections. transposeChars: cm => runInOp(cm, () => { let ranges = cm.listSelections(), newSel = [] for (let i = 0; i < ranges.length; i++) { if (!ranges[i].empty()) continue let cur = ranges[i].head, line = getLine(cm.doc, cur.line).text if (line) { if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1) if (cur.ch > 0) { cur = new Pos(cur.line, cur.ch + 1) cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), Pos(cur.line, cur.ch - 2), cur, "+transpose") } else if (cur.line > cm.doc.first) { let prev = getLine(cm.doc, cur.line - 1).text if (prev) { cur = new Pos(cur.line, 1) cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + prev.charAt(prev.length - 1), Pos(cur.line - 1, prev.length - 1), cur, "+transpose") } } } newSel.push(new Range(cur, cur)) } cm.setSelections(newSel) }), newlineAndIndent: cm => runInOp(cm, () => { let sels = cm.listSelections() for (let i = sels.length - 1; i >= 0; i--) cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input") sels = cm.listSelections() for (let i = 0; i < sels.length; i++) cm.indentLine(sels[i].from().line, null, true) ensureCursorVisible(cm) }), openLine: cm => cm.replaceSelection("\n", "start"), toggleOverwrite: cm => cm.toggleOverwrite() } function lineStart(cm, lineN) { let line = getLine(cm.doc, lineN) let visual = visualLine(line) if (visual != line) lineN = lineNo(visual) return endOfLine(true, cm, visual, lineN, 1) } function lineEnd(cm, lineN) { let line = getLine(cm.doc, lineN) let visual = visualLineEnd(line) if (visual != line) lineN = lineNo(visual) return endOfLine(true, cm, line, lineN, -1) } function lineStartSmart(cm, pos) { let start = lineStart(cm, pos.line) let line = getLine(cm.doc, start.line) let order = getOrder(line, cm.doc.direction) if (!order || order[0].level == 0) { let firstNonWS = Math.max(0, line.text.search(/\S/)) let inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) } return start } ================================================ FILE: third_party/CodeMirror/src/edit/deleteNearSelection.js ================================================ import { runInOp } from "../display/operations.js" import { ensureCursorVisible } from "../display/scrolling.js" import { cmp } from "../line/pos.js" import { replaceRange } from "../model/changes.js" import { lst } from "../util/misc.js" // Helper for deleting text near the selection(s), used to implement // backspace, delete, and similar functionality. export function deleteNearSelection(cm, compute) { let ranges = cm.doc.sel.ranges, kill = [] // Build up a set of ranges to kill first, merging overlapping // ranges. for (let i = 0; i < ranges.length; i++) { let toKill = compute(ranges[i]) while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { let replaced = kill.pop() if (cmp(replaced.from, toKill.from) < 0) { toKill.from = replaced.from break } } kill.push(toKill) } // Next, remove those actual ranges. runInOp(cm, () => { for (let i = kill.length - 1; i >= 0; i--) replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete") ensureCursorVisible(cm) }) } ================================================ FILE: third_party/CodeMirror/src/edit/drop_events.js ================================================ import { drawSelectionCursor } from "../display/selection.js" import { operation } from "../display/operations.js" import { clipPos } from "../line/pos.js" import { posFromMouse } from "../measurement/position_measurement.js" import { eventInWidget } from "../measurement/widgets.js" import { makeChange, replaceRange } from "../model/changes.js" import { changeEnd } from "../model/change_measurement.js" import { simpleSelection } from "../model/selection.js" import { setSelectionNoUndo, setSelectionReplaceHistory } from "../model/selection_updates.js" import { ie, presto, safari } from "../util/browser.js" import { elt, removeChildrenAndAdd } from "../util/dom.js" import { e_preventDefault, e_stop, signalDOMEvent } from "../util/event.js" import { indexOf } from "../util/misc.js" // Kludge to work around strange IE behavior where it'll sometimes // re-fire a series of drag-related events right after the drop (#1551) let lastDrop = 0 export function onDrop(e) { let cm = this clearDragCursor(cm) if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return e_preventDefault(e) if (ie) lastDrop = +new Date let pos = posFromMouse(cm, e, true), files = e.dataTransfer.files if (!pos || cm.isReadOnly()) return // Might be a file drop, in which case we simply extract the text // and insert it. if (files && files.length && window.FileReader && window.File) { let n = files.length, text = Array(n), read = 0 let loadFile = (file, i) => { if (cm.options.allowDropFileTypes && indexOf(cm.options.allowDropFileTypes, file.type) == -1) return let reader = new FileReader reader.onload = operation(cm, () => { let content = reader.result if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) content = "" text[i] = content if (++read == n) { pos = clipPos(cm.doc, pos) let change = {from: pos, to: pos, text: cm.doc.splitLines(text.join(cm.doc.lineSeparator())), origin: "paste"} makeChange(cm.doc, change) setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))) } }) reader.readAsText(file) } for (let i = 0; i < n; ++i) loadFile(files[i], i) } else { // Normal drop // Don't do a replace if the drop happened inside of the selected text. if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { cm.state.draggingText(e) // Ensure the editor is re-focused setTimeout(() => cm.display.input.focus(), 20) return } try { let text = e.dataTransfer.getData("Text") if (text) { let selected if (cm.state.draggingText && !cm.state.draggingText.copy) selected = cm.listSelections() setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)) if (selected) for (let i = 0; i < selected.length; ++i) replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag") cm.replaceSelection(text, "around", "paste") cm.display.input.focus() } } catch(e){} } } export function onDragStart(cm, e) { if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return e.dataTransfer.setData("Text", cm.getSelection()) e.dataTransfer.effectAllowed = "copyMove" // Use dummy image instead of default browsers image. // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. if (e.dataTransfer.setDragImage && !safari) { let img = elt("img", null, null, "position: fixed; left: 0; top: 0;") img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" if (presto) { img.width = img.height = 1 cm.display.wrapper.appendChild(img) // Force a relayout, or Opera won't use our image for some obscure reason img._top = img.offsetTop } e.dataTransfer.setDragImage(img, 0, 0) if (presto) img.parentNode.removeChild(img) } } export function onDragOver(cm, e) { let pos = posFromMouse(cm, e) if (!pos) return let frag = document.createDocumentFragment() drawSelectionCursor(cm, pos, frag) if (!cm.display.dragCursor) { cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors") cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv) } removeChildrenAndAdd(cm.display.dragCursor, frag) } export function clearDragCursor(cm) { if (cm.display.dragCursor) { cm.display.lineSpace.removeChild(cm.display.dragCursor) cm.display.dragCursor = null } } ================================================ FILE: third_party/CodeMirror/src/edit/fromTextArea.js ================================================ import { CodeMirror } from "./CodeMirror.js" import { activeElt } from "../util/dom.js" import { off, on } from "../util/event.js" import { copyObj } from "../util/misc.js" export function fromTextArea(textarea, options) { options = options ? copyObj(options) : {} options.value = textarea.value if (!options.tabindex && textarea.tabIndex) options.tabindex = textarea.tabIndex if (!options.placeholder && textarea.placeholder) options.placeholder = textarea.placeholder // Set autofocus to true if this textarea is focused, or if it has // autofocus and no other element is focused. if (options.autofocus == null) { let hasFocus = activeElt() options.autofocus = hasFocus == textarea || textarea.getAttribute("autofocus") != null && hasFocus == document.body } function save() {textarea.value = cm.getValue()} let realSubmit if (textarea.form) { on(textarea.form, "submit", save) // Deplorable hack to make the submit method do the right thing. if (!options.leaveSubmitMethodAlone) { let form = textarea.form realSubmit = form.submit try { let wrappedSubmit = form.submit = () => { save() form.submit = realSubmit form.submit() form.submit = wrappedSubmit } } catch(e) {} } } options.finishInit = cm => { cm.save = save cm.getTextArea = () => textarea cm.toTextArea = () => { cm.toTextArea = isNaN // Prevent this from being ran twice save() textarea.parentNode.removeChild(cm.getWrapperElement()) textarea.style.display = "" if (textarea.form) { off(textarea.form, "submit", save) if (typeof textarea.form.submit == "function") textarea.form.submit = realSubmit } } } textarea.style.display = "none" let cm = CodeMirror(node => textarea.parentNode.insertBefore(node, textarea.nextSibling), options) return cm } ================================================ FILE: third_party/CodeMirror/src/edit/global_events.js ================================================ import { onBlur } from "../display/focus.js" import { on } from "../util/event.js" // These must be handled carefully, because naively registering a // handler for each editor will cause the editors to never be // garbage collected. function forEachCodeMirror(f) { if (!document.getElementsByClassName) return let byClass = document.getElementsByClassName("CodeMirror"), editors = [] for (let i = 0; i < byClass.length; i++) { let cm = byClass[i].CodeMirror if (cm) editors.push(cm) } if (editors.length) editors[0].operation(() => { for (let i = 0; i < editors.length; i++) f(editors[i]) }) } let globalsRegistered = false export function ensureGlobalHandlers() { if (globalsRegistered) return registerGlobalHandlers() globalsRegistered = true } function registerGlobalHandlers() { // When the window resizes, we need to refresh active editors. let resizeTimer on(window, "resize", () => { if (resizeTimer == null) resizeTimer = setTimeout(() => { resizeTimer = null forEachCodeMirror(onResize) }, 100) }) // When the window loses focus, we want to show the editor as blurred on(window, "blur", () => forEachCodeMirror(onBlur)) } // Called when the window resizes function onResize(cm) { let d = cm.display // Might be a text scaling operation, clear size caches. d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null d.scrollbarsClipped = false cm.setSize() } ================================================ FILE: third_party/CodeMirror/src/edit/key_events.js ================================================ import { signalLater } from "../util/operation_group.js" import { restartBlink } from "../display/selection.js" import { isModifierKey, keyName, lookupKey } from "../input/keymap.js" import { eventInWidget } from "../measurement/widgets.js" import { ie, ie_version, mac, presto } from "../util/browser.js" import { activeElt, addClass, rmClass } from "../util/dom.js" import { e_preventDefault, off, on, signalDOMEvent } from "../util/event.js" import { hasCopyEvent } from "../util/feature_detection.js" import { Delayed, Pass } from "../util/misc.js" import { commands } from "./commands.js" // Run a handler that was bound to a key. function doHandleBinding(cm, bound, dropShift) { if (typeof bound == "string") { bound = commands[bound] if (!bound) return false } // Ensure previous input has been read, so that the handler sees a // consistent view of the document cm.display.input.ensurePolled() let prevShift = cm.display.shift, done = false try { if (cm.isReadOnly()) cm.state.suppressEdits = true if (dropShift) cm.display.shift = false done = bound(cm) != Pass } finally { cm.display.shift = prevShift cm.state.suppressEdits = false } return done } function lookupKeyForEditor(cm, name, handle) { for (let i = 0; i < cm.state.keyMaps.length; i++) { let result = lookupKey(name, cm.state.keyMaps[i], handle, cm) if (result) return result } return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) || lookupKey(name, cm.options.keyMap, handle, cm) } // Note that, despite the name, this function is also used to check // for bound mouse clicks. let stopSeq = new Delayed export function dispatchKey(cm, name, e, handle) { let seq = cm.state.keySeq if (seq) { if (isModifierKey(name)) return "handled" if (/\'$/.test(name)) cm.state.keySeq = null else stopSeq.set(50, () => { if (cm.state.keySeq == seq) { cm.state.keySeq = null cm.display.input.reset() } }) if (dispatchKeyInner(cm, seq + " " + name, e, handle)) return true } return dispatchKeyInner(cm, name, e, handle) } function dispatchKeyInner(cm, name, e, handle) { let result = lookupKeyForEditor(cm, name, handle) if (result == "multi") cm.state.keySeq = name if (result == "handled") signalLater(cm, "keyHandled", cm, name, e) if (result == "handled" || result == "multi") { e_preventDefault(e) restartBlink(cm) } return !!result } // Handle a key from the keydown event. function handleKeyBinding(cm, e) { let name = keyName(e, true) if (!name) return false if (e.shiftKey && !cm.state.keySeq) { // First try to resolve full name (including 'Shift-'). Failing // that, see if there is a cursor-motion command (starting with // 'go') bound to the keyname without 'Shift-'. return dispatchKey(cm, "Shift-" + name, e, b => doHandleBinding(cm, b, true)) || dispatchKey(cm, name, e, b => { if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) return doHandleBinding(cm, b) }) } else { return dispatchKey(cm, name, e, b => doHandleBinding(cm, b)) } } // Handle a key from the keypress event function handleCharBinding(cm, e, ch) { return dispatchKey(cm, "'" + ch + "'", e, b => doHandleBinding(cm, b, true)) } let lastStoppedKey = null export function onKeyDown(e) { let cm = this cm.curOp.focus = activeElt() if (signalDOMEvent(cm, e)) return // IE does strange things with escape. if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false let code = e.keyCode cm.display.shift = code == 16 || e.shiftKey let handled = handleKeyBinding(cm, e) if (presto) { lastStoppedKey = handled ? code : null // Opera has no cut event... we try to at least catch the key combo if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) cm.replaceSelection("", null, "cut") } // Turn mouse into crosshair when Alt is held on Mac. if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) showCrossHair(cm) } function showCrossHair(cm) { let lineDiv = cm.display.lineDiv addClass(lineDiv, "CodeMirror-crosshair") function up(e) { if (e.keyCode == 18 || !e.altKey) { rmClass(lineDiv, "CodeMirror-crosshair") off(document, "keyup", up) off(document, "mouseover", up) } } on(document, "keyup", up) on(document, "mouseover", up) } export function onKeyUp(e) { if (e.keyCode == 16) this.doc.sel.shift = false signalDOMEvent(this, e) } export function onKeyPress(e) { let cm = this if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return let keyCode = e.keyCode, charCode = e.charCode if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return let ch = String.fromCharCode(charCode == null ? keyCode : charCode) // Some browsers fire keypress events for backspace if (ch == "\x08") return if (handleCharBinding(cm, e, ch)) return cm.display.input.onKeyPress(e) } ================================================ FILE: third_party/CodeMirror/src/edit/legacy.js ================================================ import { scrollbarModel } from "../display/scrollbars.js" import { wheelEventPixels } from "../display/scroll_events.js" import { keyMap, keyName, isModifierKey, lookupKey, normalizeKeyMap } from "../input/keymap.js" import { keyNames } from "../input/keynames.js" import { Line } from "../line/line_data.js" import { cmp, Pos } from "../line/pos.js" import { changeEnd } from "../model/change_measurement.js" import Doc from "../model/Doc.js" import { LineWidget } from "../model/line_widget.js" import { SharedTextMarker, TextMarker } from "../model/mark_text.js" import { copyState, extendMode, getMode, innerMode, mimeModes, modeExtensions, modes, resolveMode, startState } from "../modes.js" import { addClass, contains, rmClass } from "../util/dom.js" import { e_preventDefault, e_stop, e_stopPropagation, off, on, signal } from "../util/event.js" import { splitLinesAuto } from "../util/feature_detection.js" import { countColumn, findColumn, isWordCharBasic, Pass } from "../util/misc.js" import StringStream from "../util/StringStream.js" import { commands } from "./commands.js" export function addLegacyProps(CodeMirror) { CodeMirror.off = off CodeMirror.on = on CodeMirror.wheelEventPixels = wheelEventPixels CodeMirror.Doc = Doc CodeMirror.splitLines = splitLinesAuto CodeMirror.countColumn = countColumn CodeMirror.findColumn = findColumn CodeMirror.isWordChar = isWordCharBasic CodeMirror.Pass = Pass CodeMirror.signal = signal CodeMirror.Line = Line CodeMirror.changeEnd = changeEnd CodeMirror.scrollbarModel = scrollbarModel CodeMirror.Pos = Pos CodeMirror.cmpPos = cmp CodeMirror.modes = modes CodeMirror.mimeModes = mimeModes CodeMirror.resolveMode = resolveMode CodeMirror.getMode = getMode CodeMirror.modeExtensions = modeExtensions CodeMirror.extendMode = extendMode CodeMirror.copyState = copyState CodeMirror.startState = startState CodeMirror.innerMode = innerMode CodeMirror.commands = commands CodeMirror.keyMap = keyMap CodeMirror.keyName = keyName CodeMirror.isModifierKey = isModifierKey CodeMirror.lookupKey = lookupKey CodeMirror.normalizeKeyMap = normalizeKeyMap CodeMirror.StringStream = StringStream CodeMirror.SharedTextMarker = SharedTextMarker CodeMirror.TextMarker = TextMarker CodeMirror.LineWidget = LineWidget CodeMirror.e_preventDefault = e_preventDefault CodeMirror.e_stopPropagation = e_stopPropagation CodeMirror.e_stop = e_stop CodeMirror.addClass = addClass CodeMirror.contains = contains CodeMirror.rmClass = rmClass CodeMirror.keyNames = keyNames } ================================================ FILE: third_party/CodeMirror/src/edit/main.js ================================================ // EDITOR CONSTRUCTOR import { CodeMirror } from "./CodeMirror.js" export { CodeMirror } from "./CodeMirror.js" import { eventMixin } from "../util/event.js" import { indexOf } from "../util/misc.js" import { defineOptions } from "./options.js" defineOptions(CodeMirror) import addEditorMethods from "./methods.js" addEditorMethods(CodeMirror) import Doc from "../model/Doc.js" // Set up methods on CodeMirror's prototype to redirect to the editor's document. let dontDelegate = "iter insert remove copy getEditor constructor".split(" ") for (let prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) CodeMirror.prototype[prop] = (function(method) { return function() {return method.apply(this.doc, arguments)} })(Doc.prototype[prop]) eventMixin(Doc) // INPUT HANDLING import ContentEditableInput from "../input/ContentEditableInput.js" import TextareaInput from "../input/TextareaInput.js" CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput} // MODE DEFINITION AND QUERYING import { defineMIME, defineMode } from "../modes.js" // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) CodeMirror.defineMode = function(name/*, mode, …*/) { if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name defineMode.apply(this, arguments) } CodeMirror.defineMIME = defineMIME // Minimal default mode. CodeMirror.defineMode("null", () => ({token: stream => stream.skipToEnd()})) CodeMirror.defineMIME("text/plain", "null") // EXTENSIONS CodeMirror.defineExtension = (name, func) => { CodeMirror.prototype[name] = func } CodeMirror.defineDocExtension = (name, func) => { Doc.prototype[name] = func } import { fromTextArea } from "./fromTextArea.js" CodeMirror.fromTextArea = fromTextArea import { addLegacyProps } from "./legacy.js" addLegacyProps(CodeMirror) CodeMirror.version = "5.43.0" ================================================ FILE: third_party/CodeMirror/src/edit/methods.js ================================================ import { deleteNearSelection } from "./deleteNearSelection.js" import { commands } from "./commands.js" import { attachDoc } from "../model/document_data.js" import { activeElt, addClass, rmClass } from "../util/dom.js" import { eventMixin, signal } from "../util/event.js" import { getLineStyles, getContextBefore, takeToken } from "../line/highlight.js" import { indentLine } from "../input/indent.js" import { triggerElectric } from "../input/input.js" import { onKeyDown, onKeyPress, onKeyUp } from "./key_events.js" import { onMouseDown } from "./mouse_events.js" import { getKeyMap } from "../input/keymap.js" import { endOfLine, moveLogically, moveVisually } from "../input/movement.js" import { endOperation, methodOp, operation, runInOp, startOperation } from "../display/operations.js" import { clipLine, clipPos, equalCursorPos, Pos } from "../line/pos.js" import { charCoords, charWidth, clearCaches, clearLineMeasurementCache, coordsChar, cursorCoords, displayHeight, displayWidth, estimateLineHeights, fromCoordSystem, intoCoordSystem, scrollGap, textHeight } from "../measurement/position_measurement.js" import { Range } from "../model/selection.js" import { replaceOneSelection, skipAtomic } from "../model/selection_updates.js" import { addToScrollTop, ensureCursorVisible, scrollIntoView, scrollToCoords, scrollToCoordsRange, scrollToRange } from "../display/scrolling.js" import { heightAtLine } from "../line/spans.js" import { updateGutterSpace } from "../display/update_display.js" import { indexOf, insertSorted, isWordChar, sel_dontScroll, sel_move } from "../util/misc.js" import { signalLater } from "../util/operation_group.js" import { getLine, isLine, lineAtHeight } from "../line/utils_line.js" import { regChange, regLineChange } from "../display/view_tracking.js" // The publicly visible API. Note that methodOp(f) means // 'wrap f in an operation, performed on its `this` parameter'. // This is not the complete set of editor methods. Most of the // methods defined on the Doc type are also injected into // CodeMirror.prototype, for backwards compatibility and // convenience. export default function(CodeMirror) { let optionHandlers = CodeMirror.optionHandlers let helpers = CodeMirror.helpers = {} CodeMirror.prototype = { constructor: CodeMirror, focus: function(){window.focus(); this.display.input.focus()}, setOption: function(option, value) { let options = this.options, old = options[option] if (options[option] == value && option != "mode") return options[option] = value if (optionHandlers.hasOwnProperty(option)) operation(this, optionHandlers[option])(this, value, old) signal(this, "optionChange", this, option) }, getOption: function(option) {return this.options[option]}, getDoc: function() {return this.doc}, addKeyMap: function(map, bottom) { this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)) }, removeKeyMap: function(map) { let maps = this.state.keyMaps for (let i = 0; i < maps.length; ++i) if (maps[i] == map || maps[i].name == map) { maps.splice(i, 1) return true } }, addOverlay: methodOp(function(spec, options) { let mode = spec.token ? spec : CodeMirror.getMode(this.options, spec) if (mode.startState) throw new Error("Overlays may not be stateful.") insertSorted(this.state.overlays, {mode: mode, modeSpec: spec, opaque: options && options.opaque, priority: (options && options.priority) || 0}, overlay => overlay.priority) this.state.modeGen++ regChange(this) }), removeOverlay: methodOp(function(spec) { let overlays = this.state.overlays for (let i = 0; i < overlays.length; ++i) { let cur = overlays[i].modeSpec if (cur == spec || typeof spec == "string" && cur.name == spec) { overlays.splice(i, 1) this.state.modeGen++ regChange(this) return } } }), indentLine: methodOp(function(n, dir, aggressive) { if (typeof dir != "string" && typeof dir != "number") { if (dir == null) dir = this.options.smartIndent ? "smart" : "prev" else dir = dir ? "add" : "subtract" } if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive) }), indentSelection: methodOp(function(how) { let ranges = this.doc.sel.ranges, end = -1 for (let i = 0; i < ranges.length; i++) { let range = ranges[i] if (!range.empty()) { let from = range.from(), to = range.to() let start = Math.max(end, from.line) end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1 for (let j = start; j < end; ++j) indentLine(this, j, how) let newRanges = this.doc.sel.ranges if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll) } else if (range.head.line > end) { indentLine(this, range.head.line, how, true) end = range.head.line if (i == this.doc.sel.primIndex) ensureCursorVisible(this) } } }), // Fetch the parser token for a given character. Useful for hacks // that want to inspect the mode state (say, for completion). getTokenAt: function(pos, precise) { return takeToken(this, pos, precise) }, getLineTokens: function(line, precise) { return takeToken(this, Pos(line), precise, true) }, getTokenTypeAt: function(pos) { pos = clipPos(this.doc, pos) let styles = getLineStyles(this, getLine(this.doc, pos.line)) let before = 0, after = (styles.length - 1) / 2, ch = pos.ch let type if (ch == 0) type = styles[2] else for (;;) { let mid = (before + after) >> 1 if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid else if (styles[mid * 2 + 1] < ch) before = mid + 1 else { type = styles[mid * 2 + 2]; break } } let cut = type ? type.indexOf("overlay ") : -1 return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) }, getModeAt: function(pos) { let mode = this.doc.mode if (!mode.innerMode) return mode return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode }, getHelper: function(pos, type) { return this.getHelpers(pos, type)[0] }, getHelpers: function(pos, type) { let found = [] if (!helpers.hasOwnProperty(type)) return found let help = helpers[type], mode = this.getModeAt(pos) if (typeof mode[type] == "string") { if (help[mode[type]]) found.push(help[mode[type]]) } else if (mode[type]) { for (let i = 0; i < mode[type].length; i++) { let val = help[mode[type][i]] if (val) found.push(val) } } else if (mode.helperType && help[mode.helperType]) { found.push(help[mode.helperType]) } else if (help[mode.name]) { found.push(help[mode.name]) } for (let i = 0; i < help._global.length; i++) { let cur = help._global[i] if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) found.push(cur.val) } return found }, getStateAfter: function(line, precise) { let doc = this.doc line = clipLine(doc, line == null ? doc.first + doc.size - 1: line) return getContextBefore(this, line + 1, precise).state }, cursorCoords: function(start, mode) { let pos, range = this.doc.sel.primary() if (start == null) pos = range.head else if (typeof start == "object") pos = clipPos(this.doc, start) else pos = start ? range.from() : range.to() return cursorCoords(this, pos, mode || "page") }, charCoords: function(pos, mode) { return charCoords(this, clipPos(this.doc, pos), mode || "page") }, coordsChar: function(coords, mode) { coords = fromCoordSystem(this, coords, mode || "page") return coordsChar(this, coords.left, coords.top) }, lineAtHeight: function(height, mode) { height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top return lineAtHeight(this.doc, height + this.display.viewOffset) }, heightAtLine: function(line, mode, includeWidgets) { let end = false, lineObj if (typeof line == "number") { let last = this.doc.first + this.doc.size - 1 if (line < this.doc.first) line = this.doc.first else if (line > last) { line = last; end = true } lineObj = getLine(this.doc, line) } else { lineObj = line } return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + (end ? this.doc.height - heightAtLine(lineObj) : 0) }, defaultTextHeight: function() { return textHeight(this.display) }, defaultCharWidth: function() { return charWidth(this.display) }, getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, addWidget: function(pos, node, scroll, vert, horiz) { let display = this.display pos = cursorCoords(this, clipPos(this.doc, pos)) let top = pos.bottom, left = pos.left node.style.position = "absolute" node.setAttribute("cm-ignore-events", "true") this.display.input.setUneditable(node) display.sizer.appendChild(node) if (vert == "over") { top = pos.top } else if (vert == "above" || vert == "near") { let vspace = Math.max(display.wrapper.clientHeight, this.doc.height), hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth) // Default to positioning above (if specified and possible); otherwise default to positioning below if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) top = pos.top - node.offsetHeight else if (pos.bottom + node.offsetHeight <= vspace) top = pos.bottom if (left + node.offsetWidth > hspace) left = hspace - node.offsetWidth } node.style.top = top + "px" node.style.left = node.style.right = "" if (horiz == "right") { left = display.sizer.clientWidth - node.offsetWidth node.style.right = "0px" } else { if (horiz == "left") left = 0 else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2 node.style.left = left + "px" } if (scroll) scrollIntoView(this, {left, top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}) }, triggerOnKeyDown: methodOp(onKeyDown), triggerOnKeyPress: methodOp(onKeyPress), triggerOnKeyUp: onKeyUp, triggerOnMouseDown: methodOp(onMouseDown), execCommand: function(cmd) { if (commands.hasOwnProperty(cmd)) return commands[cmd].call(null, this) }, triggerElectric: methodOp(function(text) { triggerElectric(this, text) }), findPosH: function(from, amount, unit, visually) { let dir = 1 if (amount < 0) { dir = -1; amount = -amount } let cur = clipPos(this.doc, from) for (let i = 0; i < amount; ++i) { cur = findPosH(this.doc, cur, dir, unit, visually) if (cur.hitSide) break } return cur }, moveH: methodOp(function(dir, unit) { this.extendSelectionsBy(range => { if (this.display.shift || this.doc.extend || range.empty()) return findPosH(this.doc, range.head, dir, unit, this.options.rtlMoveVisually) else return dir < 0 ? range.from() : range.to() }, sel_move) }), deleteH: methodOp(function(dir, unit) { let sel = this.doc.sel, doc = this.doc if (sel.somethingSelected()) doc.replaceSelection("", null, "+delete") else deleteNearSelection(this, range => { let other = findPosH(doc, range.head, dir, unit, false) return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other} }) }), findPosV: function(from, amount, unit, goalColumn) { let dir = 1, x = goalColumn if (amount < 0) { dir = -1; amount = -amount } let cur = clipPos(this.doc, from) for (let i = 0; i < amount; ++i) { let coords = cursorCoords(this, cur, "div") if (x == null) x = coords.left else coords.left = x cur = findPosV(this, coords, dir, unit) if (cur.hitSide) break } return cur }, moveV: methodOp(function(dir, unit) { let doc = this.doc, goals = [] let collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected() doc.extendSelectionsBy(range => { if (collapse) return dir < 0 ? range.from() : range.to() let headPos = cursorCoords(this, range.head, "div") if (range.goalColumn != null) headPos.left = range.goalColumn goals.push(headPos.left) let pos = findPosV(this, headPos, dir, unit) if (unit == "page" && range == doc.sel.primary()) addToScrollTop(this, charCoords(this, pos, "div").top - headPos.top) return pos }, sel_move) if (goals.length) for (let i = 0; i < doc.sel.ranges.length; i++) doc.sel.ranges[i].goalColumn = goals[i] }), // Find the word at the given position (as returned by coordsChar). findWordAt: function(pos) { let doc = this.doc, line = getLine(doc, pos.line).text let start = pos.ch, end = pos.ch if (line) { let helper = this.getHelper(pos, "wordChars") if ((pos.sticky == "before" || end == line.length) && start) --start; else ++end let startChar = line.charAt(start) let check = isWordChar(startChar, helper) ? ch => isWordChar(ch, helper) : /\s/.test(startChar) ? ch => /\s/.test(ch) : ch => (!/\s/.test(ch) && !isWordChar(ch)) while (start > 0 && check(line.charAt(start - 1))) --start while (end < line.length && check(line.charAt(end))) ++end } return new Range(Pos(pos.line, start), Pos(pos.line, end)) }, toggleOverwrite: function(value) { if (value != null && value == this.state.overwrite) return if (this.state.overwrite = !this.state.overwrite) addClass(this.display.cursorDiv, "CodeMirror-overwrite") else rmClass(this.display.cursorDiv, "CodeMirror-overwrite") signal(this, "overwriteToggle", this, this.state.overwrite) }, hasFocus: function() { return this.display.input.getField() == activeElt() }, isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y) }), getScrollInfo: function() { let scroller = this.display.scroller return {left: scroller.scrollLeft, top: scroller.scrollTop, height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, clientHeight: displayHeight(this), clientWidth: displayWidth(this)} }, scrollIntoView: methodOp(function(range, margin) { if (range == null) { range = {from: this.doc.sel.primary().head, to: null} if (margin == null) margin = this.options.cursorScrollMargin } else if (typeof range == "number") { range = {from: Pos(range, 0), to: null} } else if (range.from == null) { range = {from: range, to: null} } if (!range.to) range.to = range.from range.margin = margin || 0 if (range.from.line != null) { scrollToRange(this, range) } else { scrollToCoordsRange(this, range.from, range.to, range.margin) } }), setSize: methodOp(function(width, height) { let interpret = val => typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val if (width != null) this.display.wrapper.style.width = interpret(width) if (height != null) this.display.wrapper.style.height = interpret(height) if (this.options.lineWrapping) clearLineMeasurementCache(this) let lineNo = this.display.viewFrom this.doc.iter(lineNo, this.display.viewTo, line => { if (line.widgets) for (let i = 0; i < line.widgets.length; i++) if (line.widgets[i].noHScroll) { regLineChange(this, lineNo, "widget"); break } ++lineNo }) this.curOp.forceUpdate = true signal(this, "refresh", this) }), operation: function(f){return runInOp(this, f)}, startOperation: function(){return startOperation(this)}, endOperation: function(){return endOperation(this)}, refresh: methodOp(function() { let oldHeight = this.display.cachedTextHeight regChange(this) this.curOp.forceUpdate = true clearCaches(this) scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop) updateGutterSpace(this) if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) estimateLineHeights(this) signal(this, "refresh", this) }), swapDoc: methodOp(function(doc) { let old = this.doc old.cm = null attachDoc(this, doc) clearCaches(this) this.display.input.reset() scrollToCoords(this, doc.scrollLeft, doc.scrollTop) this.curOp.forceScroll = true signalLater(this, "swapDoc", this, old) return old }), phrase: function(phraseText) { let phrases = this.options.phrases return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText }, getInputField: function(){return this.display.input.getField()}, getWrapperElement: function(){return this.display.wrapper}, getScrollerElement: function(){return this.display.scroller}, getGutterElement: function(){return this.display.gutters} } eventMixin(CodeMirror) CodeMirror.registerHelper = function(type, name, value) { if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []} helpers[type][name] = value } CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { CodeMirror.registerHelper(type, name, value) helpers[type]._global.push({pred: predicate, val: value}) } } // Used for horizontal relative motion. Dir is -1 or 1 (left or // right), unit can be "char", "column" (like char, but doesn't // cross line boundaries), "word" (across next word), or "group" (to // the start of next group of word or non-word-non-whitespace // chars). The visually param controls whether, in right-to-left // text, direction 1 means to move towards the next index in the // string, or towards the character to the right of the current // position. The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosH(doc, pos, dir, unit, visually) { let oldPos = pos let origDir = dir let lineObj = getLine(doc, pos.line) function findNextLine() { let l = pos.line + dir if (l < doc.first || l >= doc.first + doc.size) return false pos = new Pos(l, pos.ch, pos.sticky) return lineObj = getLine(doc, l) } function moveOnce(boundToLine) { let next if (visually) { next = moveVisually(doc.cm, lineObj, pos, dir) } else { next = moveLogically(lineObj, pos, dir) } if (next == null) { if (!boundToLine && findNextLine()) pos = endOfLine(visually, doc.cm, lineObj, pos.line, dir) else return false } else { pos = next } return true } if (unit == "char") { moveOnce() } else if (unit == "column") { moveOnce(true) } else if (unit == "word" || unit == "group") { let sawType = null, group = unit == "group" let helper = doc.cm && doc.cm.getHelper(pos, "wordChars") for (let first = true;; first = false) { if (dir < 0 && !moveOnce(!first)) break let cur = lineObj.text.charAt(pos.ch) || "\n" let type = isWordChar(cur, helper) ? "w" : group && cur == "\n" ? "n" : !group || /\s/.test(cur) ? null : "p" if (group && !first && !type) type = "s" if (sawType && sawType != type) { if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after"} break } if (type) sawType = type if (dir > 0 && !moveOnce(!first)) break } } let result = skipAtomic(doc, pos, oldPos, origDir, true) if (equalCursorPos(oldPos, result)) result.hitSide = true return result } // For relative vertical movement. Dir may be -1 or 1. Unit can be // "page" or "line". The resulting position will have a hitSide=true // property if it reached the end of the document. function findPosV(cm, pos, dir, unit) { let doc = cm.doc, x = pos.left, y if (unit == "page") { let pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight) let moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3) y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount } else if (unit == "line") { y = dir > 0 ? pos.bottom + 3 : pos.top - 3 } let target for (;;) { target = coordsChar(cm, x, y) if (!target.outside) break if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } y += dir * 5 } return target } ================================================ FILE: third_party/CodeMirror/src/edit/mouse_events.js ================================================ import { delayBlurEvent, ensureFocus } from "../display/focus.js" import { operation } from "../display/operations.js" import { visibleLines } from "../display/update_lines.js" import { clipPos, cmp, maxPos, minPos, Pos } from "../line/pos.js" import { getLine, lineAtHeight } from "../line/utils_line.js" import { posFromMouse } from "../measurement/position_measurement.js" import { eventInWidget } from "../measurement/widgets.js" import { normalizeSelection, Range, Selection } from "../model/selection.js" import { extendRange, extendSelection, replaceOneSelection, setSelection } from "../model/selection_updates.js" import { captureRightClick, chromeOS, ie, ie_version, mac, webkit } from "../util/browser.js" import { getOrder, getBidiPartAt } from "../util/bidi.js" import { activeElt } from "../util/dom.js" import { e_button, e_defaultPrevented, e_preventDefault, e_target, hasHandler, off, on, signal, signalDOMEvent } from "../util/event.js" import { dragAndDrop } from "../util/feature_detection.js" import { bind, countColumn, findColumn, sel_mouse } from "../util/misc.js" import { addModifierNames } from "../input/keymap.js" import { Pass } from "../util/misc.js" import { dispatchKey } from "./key_events.js" import { commands } from "./commands.js" const DOUBLECLICK_DELAY = 400 class PastClick { constructor(time, pos, button) { this.time = time this.pos = pos this.button = button } compare(time, pos, button) { return this.time + DOUBLECLICK_DELAY > time && cmp(pos, this.pos) == 0 && button == this.button } } let lastClick, lastDoubleClick function clickRepeat(pos, button) { let now = +new Date if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { lastClick = lastDoubleClick = null return "triple" } else if (lastClick && lastClick.compare(now, pos, button)) { lastDoubleClick = new PastClick(now, pos, button) lastClick = null return "double" } else { lastClick = new PastClick(now, pos, button) lastDoubleClick = null return "single" } } // A mouse down can be a single click, double click, triple click, // start of selection drag, start of text drag, new cursor // (ctrl-click), rectangle drag (alt-drag), or xwin // middle-click-paste. Or it might be a click on something we should // not interfere with, such as a scrollbar or widget. export function onMouseDown(e) { let cm = this, display = cm.display if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) return display.input.ensurePolled() display.shift = e.shiftKey if (eventInWidget(display, e)) { if (!webkit) { // Briefly turn off draggability, to allow widgets to do // normal dragging things. display.scroller.draggable = false setTimeout(() => display.scroller.draggable = true, 100) } return } if (clickInGutter(cm, e)) return let pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single" window.focus() // #3261: make sure, that we're not starting a second selection if (button == 1 && cm.state.selectingText) cm.state.selectingText(e) if (pos && handleMappedButton(cm, button, pos, repeat, e)) return if (button == 1) { if (pos) leftButtonDown(cm, pos, repeat, e) else if (e_target(e) == display.scroller) e_preventDefault(e) } else if (button == 2) { if (pos) extendSelection(cm.doc, pos) setTimeout(() => display.input.focus(), 20) } else if (button == 3) { if (captureRightClick) cm.display.input.onContextMenu(e) else delayBlurEvent(cm) } } function handleMappedButton(cm, button, pos, repeat, event) { let name = "Click" if (repeat == "double") name = "Double" + name else if (repeat == "triple") name = "Triple" + name name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name return dispatchKey(cm, addModifierNames(name, event), event, bound => { if (typeof bound == "string") bound = commands[bound] if (!bound) return false let done = false try { if (cm.isReadOnly()) cm.state.suppressEdits = true done = bound(cm, pos) != Pass } finally { cm.state.suppressEdits = false } return done }) } function configureMouse(cm, repeat, event) { let option = cm.getOption("configureMouse") let value = option ? option(cm, repeat, event) : {} if (value.unit == null) { let rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line" } if (value.extend == null || cm.doc.extend) value.extend = cm.doc.extend || event.shiftKey if (value.addNew == null) value.addNew = mac ? event.metaKey : event.ctrlKey if (value.moveOnDrag == null) value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey) return value } function leftButtonDown(cm, pos, repeat, event) { if (ie) setTimeout(bind(ensureFocus, cm), 0) else cm.curOp.focus = activeElt() let behavior = configureMouse(cm, repeat, event) let sel = cm.doc.sel, contained if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && repeat == "single" && (contained = sel.contains(pos)) > -1 && (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) leftButtonStartDrag(cm, event, pos, behavior) else leftButtonSelect(cm, event, pos, behavior) } // Start a text drag. When it ends, see if any dragging actually // happen, and treat as a click if it didn't. function leftButtonStartDrag(cm, event, pos, behavior) { let display = cm.display, moved = false let dragEnd = operation(cm, e => { if (webkit) display.scroller.draggable = false cm.state.draggingText = false off(display.wrapper.ownerDocument, "mouseup", dragEnd) off(display.wrapper.ownerDocument, "mousemove", mouseMove) off(display.scroller, "dragstart", dragStart) off(display.scroller, "drop", dragEnd) if (!moved) { e_preventDefault(e) if (!behavior.addNew) extendSelection(cm.doc, pos, null, null, behavior.extend) // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) if (webkit || ie && ie_version == 9) setTimeout(() => {display.wrapper.ownerDocument.body.focus(); display.input.focus()}, 20) else display.input.focus() } }) let mouseMove = function(e2) { moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10 } let dragStart = () => moved = true // Let the drag handler handle this. if (webkit) display.scroller.draggable = true cm.state.draggingText = dragEnd dragEnd.copy = !behavior.moveOnDrag // IE's approach to draggable if (display.scroller.dragDrop) display.scroller.dragDrop() on(display.wrapper.ownerDocument, "mouseup", dragEnd) on(display.wrapper.ownerDocument, "mousemove", mouseMove) on(display.scroller, "dragstart", dragStart) on(display.scroller, "drop", dragEnd) delayBlurEvent(cm) setTimeout(() => display.input.focus(), 20) } function rangeForUnit(cm, pos, unit) { if (unit == "char") return new Range(pos, pos) if (unit == "word") return cm.findWordAt(pos) if (unit == "line") return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) let result = unit(cm, pos) return new Range(result.from, result.to) } // Normal selection, as opposed to text dragging. function leftButtonSelect(cm, event, start, behavior) { let display = cm.display, doc = cm.doc e_preventDefault(event) let ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges if (behavior.addNew && !behavior.extend) { ourIndex = doc.sel.contains(start) if (ourIndex > -1) ourRange = ranges[ourIndex] else ourRange = new Range(start, start) } else { ourRange = doc.sel.primary() ourIndex = doc.sel.primIndex } if (behavior.unit == "rectangle") { if (!behavior.addNew) ourRange = new Range(start, start) start = posFromMouse(cm, event, true, true) ourIndex = -1 } else { let range = rangeForUnit(cm, start, behavior.unit) if (behavior.extend) ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend) else ourRange = range } if (!behavior.addNew) { ourIndex = 0 setSelection(doc, new Selection([ourRange], 0), sel_mouse) startSel = doc.sel } else if (ourIndex == -1) { ourIndex = ranges.length setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), {scroll: false, origin: "*mouse"}) } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), {scroll: false, origin: "*mouse"}) startSel = doc.sel } else { replaceOneSelection(doc, ourIndex, ourRange, sel_mouse) } let lastPos = start function extendTo(pos) { if (cmp(lastPos, pos) == 0) return lastPos = pos if (behavior.unit == "rectangle") { let ranges = [], tabSize = cm.options.tabSize let startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize) let posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize) let left = Math.min(startCol, posCol), right = Math.max(startCol, posCol) for (let line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); line <= end; line++) { let text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize) if (left == right) ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))) else if (text.length > leftPos) ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))) } if (!ranges.length) ranges.push(new Range(start, start)) setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), {origin: "*mouse", scroll: false}) cm.scrollIntoView(pos) } else { let oldRange = ourRange let range = rangeForUnit(cm, pos, behavior.unit) let anchor = oldRange.anchor, head if (cmp(range.anchor, anchor) > 0) { head = range.head anchor = minPos(oldRange.from(), range.anchor) } else { head = range.anchor anchor = maxPos(oldRange.to(), range.head) } let ranges = startSel.ranges.slice(0) ranges[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)) setSelection(doc, normalizeSelection(cm, ranges, ourIndex), sel_mouse) } } let editorSize = display.wrapper.getBoundingClientRect() // Used to ensure timeout re-tries don't fire when another extend // happened in the meantime (clearTimeout isn't reliable -- at // least on Chrome, the timeouts still happen even when cleared, // if the clear happens after their scheduled firing time). let counter = 0 function extend(e) { let curCount = ++counter let cur = posFromMouse(cm, e, true, behavior.unit == "rectangle") if (!cur) return if (cmp(cur, lastPos) != 0) { cm.curOp.focus = activeElt() extendTo(cur) let visible = visibleLines(display, doc) if (cur.line >= visible.to || cur.line < visible.from) setTimeout(operation(cm, () => {if (counter == curCount) extend(e)}), 150) } else { let outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0 if (outside) setTimeout(operation(cm, () => { if (counter != curCount) return display.scroller.scrollTop += outside extend(e) }), 50) } } function done(e) { cm.state.selectingText = false counter = Infinity e_preventDefault(e) display.input.focus() off(display.wrapper.ownerDocument, "mousemove", move) off(display.wrapper.ownerDocument, "mouseup", up) doc.history.lastSelOrigin = null } let move = operation(cm, e => { if (e.buttons === 0 || !e_button(e)) done(e) else extend(e) }) let up = operation(cm, done) cm.state.selectingText = up on(display.wrapper.ownerDocument, "mousemove", move) on(display.wrapper.ownerDocument, "mouseup", up) } // Used when mouse-selecting to adjust the anchor to the proper side // of a bidi jump depending on the visual position of the head. function bidiSimplify(cm, range) { let {anchor, head} = range, anchorLine = getLine(cm.doc, anchor.line) if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) return range let order = getOrder(anchorLine) if (!order) return range let index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index] if (part.from != anchor.ch && part.to != anchor.ch) return range let boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1) if (boundary == 0 || boundary == order.length) return range // Compute the relative visual position of the head compared to the // anchor (<0 is to the left, >0 to the right) let leftSide if (head.line != anchor.line) { leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0 } else { let headIndex = getBidiPartAt(order, head.ch, head.sticky) let dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1) if (headIndex == boundary - 1 || headIndex == boundary) leftSide = dir < 0 else leftSide = dir > 0 } let usePart = order[boundary + (leftSide ? -1 : 0)] let from = leftSide == (usePart.level == 1) let ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before" return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head) } // Determines whether an event happened in the gutter, and fires the // handlers for the corresponding event. function gutterEvent(cm, e, type, prevent) { let mX, mY if (e.touches) { mX = e.touches[0].clientX mY = e.touches[0].clientY } else { try { mX = e.clientX; mY = e.clientY } catch(e) { return false } } if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false if (prevent) e_preventDefault(e) let display = cm.display let lineBox = display.lineDiv.getBoundingClientRect() if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e) mY -= lineBox.top - display.viewOffset for (let i = 0; i < cm.options.gutters.length; ++i) { let g = display.gutters.childNodes[i] if (g && g.getBoundingClientRect().right >= mX) { let line = lineAtHeight(cm.doc, mY) let gutter = cm.options.gutters[i] signal(cm, type, cm, line, gutter, e) return e_defaultPrevented(e) } } } export function clickInGutter(cm, e) { return gutterEvent(cm, e, "gutterClick", true) } // CONTEXT MENU HANDLING // To make the context menu work, we need to briefly unhide the // textarea (making it as unobtrusive as possible) to let the // right-click take effect on it. export function onContextMenu(cm, e) { if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return if (signalDOMEvent(cm, e, "contextmenu")) return if (!captureRightClick) cm.display.input.onContextMenu(e) } function contextMenuInGutter(cm, e) { if (!hasHandler(cm, "gutterContextMenu")) return false return gutterEvent(cm, e, "gutterContextMenu", false) } ================================================ FILE: third_party/CodeMirror/src/edit/options.js ================================================ import { onBlur } from "../display/focus.js" import { setGuttersForLineNumbers, updateGutters } from "../display/gutters.js" import { alignHorizontally } from "../display/line_numbers.js" import { loadMode, resetModeState } from "../display/mode_state.js" import { initScrollbars, updateScrollbars } from "../display/scrollbars.js" import { updateSelection } from "../display/selection.js" import { regChange } from "../display/view_tracking.js" import { getKeyMap } from "../input/keymap.js" import { defaultSpecialCharPlaceholder } from "../line/line_data.js" import { Pos } from "../line/pos.js" import { findMaxLine } from "../line/spans.js" import { clearCaches, compensateForHScroll, estimateLineHeights } from "../measurement/position_measurement.js" import { replaceRange } from "../model/changes.js" import { mobile, windows } from "../util/browser.js" import { addClass, rmClass } from "../util/dom.js" import { off, on } from "../util/event.js" import { themeChanged } from "./utils.js" export let Init = {toString: function(){return "CodeMirror.Init"}} export let defaults = {} export let optionHandlers = {} export function defineOptions(CodeMirror) { let optionHandlers = CodeMirror.optionHandlers function option(name, deflt, handle, notOnInit) { CodeMirror.defaults[name] = deflt if (handle) optionHandlers[name] = notOnInit ? (cm, val, old) => {if (old != Init) handle(cm, val, old)} : handle } CodeMirror.defineOption = option // Passed to option handlers when there is no old value. CodeMirror.Init = Init // These two are, on init, called from the constructor because they // have to be initialized before the editor can start at all. option("value", "", (cm, val) => cm.setValue(val), true) option("mode", null, (cm, val) => { cm.doc.modeOption = val loadMode(cm) }, true) option("indentUnit", 2, loadMode, true) option("indentWithTabs", false) option("smartIndent", true) option("tabSize", 4, cm => { resetModeState(cm) clearCaches(cm) regChange(cm) }, true) option("lineSeparator", null, (cm, val) => { cm.doc.lineSep = val if (!val) return let newBreaks = [], lineNo = cm.doc.first cm.doc.iter(line => { for (let pos = 0;;) { let found = line.text.indexOf(val, pos) if (found == -1) break pos = found + val.length newBreaks.push(Pos(lineNo, found)) } lineNo++ }) for (let i = newBreaks.length - 1; i >= 0; i--) replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)) }) option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/g, (cm, val, old) => { cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g") if (old != Init) cm.refresh() }) option("specialCharPlaceholder", defaultSpecialCharPlaceholder, cm => cm.refresh(), true) option("electricChars", true) option("inputStyle", mobile ? "contenteditable" : "textarea", () => { throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME }, true) option("spellcheck", false, (cm, val) => cm.getInputField().spellcheck = val, true) option("autocorrect", false, (cm, val) => cm.getInputField().autocorrect = val, true) option("autocapitalize", false, (cm, val) => cm.getInputField().autocapitalize = val, true) option("rtlMoveVisually", !windows) option("wholeLineUpdateBefore", true) option("theme", "default", cm => { themeChanged(cm) guttersChanged(cm) }, true) option("keyMap", "default", (cm, val, old) => { let next = getKeyMap(val) let prev = old != Init && getKeyMap(old) if (prev && prev.detach) prev.detach(cm, next) if (next.attach) next.attach(cm, prev || null) }) option("extraKeys", null) option("configureMouse", null) option("lineWrapping", false, wrappingChanged, true) option("gutters", [], cm => { setGuttersForLineNumbers(cm.options) guttersChanged(cm) }, true) option("fixedGutter", true, (cm, val) => { cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0" cm.refresh() }, true) option("coverGutterNextToScrollbar", false, cm => updateScrollbars(cm), true) option("scrollbarStyle", "native", cm => { initScrollbars(cm) updateScrollbars(cm) cm.display.scrollbars.setScrollTop(cm.doc.scrollTop) cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft) }, true) option("lineNumbers", false, cm => { setGuttersForLineNumbers(cm.options) guttersChanged(cm) }, true) option("firstLineNumber", 1, guttersChanged, true) option("lineNumberFormatter", integer => integer, guttersChanged, true) option("showCursorWhenSelecting", false, updateSelection, true) option("resetSelectionOnContextMenu", true) option("lineWiseCopyCut", true) option("pasteLinesPerSelection", true) option("selectionsMayTouch", false) option("readOnly", false, (cm, val) => { if (val == "nocursor") { onBlur(cm) cm.display.input.blur() } cm.display.input.readOnlyChanged(val) }) option("disableInput", false, (cm, val) => {if (!val) cm.display.input.reset()}, true) option("dragDrop", true, dragDropChanged) option("allowDropFileTypes", null) option("cursorBlinkRate", 530) option("cursorScrollMargin", 0) option("cursorHeight", 1, updateSelection, true) option("singleCursorHeightPerLine", true, updateSelection, true) option("workTime", 100) option("workDelay", 100) option("flattenSpans", true, resetModeState, true) option("addModeClass", false, resetModeState, true) option("pollInterval", 100) option("undoDepth", 200, (cm, val) => cm.doc.history.undoDepth = val) option("historyEventDelay", 1250) option("viewportMargin", 10, cm => cm.refresh(), true) option("maxHighlightLength", 10000, resetModeState, true) option("moveInputWithCursor", true, (cm, val) => { if (!val) cm.display.input.resetPosition() }) option("tabindex", null, (cm, val) => cm.display.input.getField().tabIndex = val || "") option("autofocus", null) option("direction", "ltr", (cm, val) => cm.doc.setDirection(val), true) option("phrases", null) } function guttersChanged(cm) { updateGutters(cm) regChange(cm) alignHorizontally(cm) } function dragDropChanged(cm, value, old) { let wasOn = old && old != Init if (!value != !wasOn) { let funcs = cm.display.dragFunctions let toggle = value ? on : off toggle(cm.display.scroller, "dragstart", funcs.start) toggle(cm.display.scroller, "dragenter", funcs.enter) toggle(cm.display.scroller, "dragover", funcs.over) toggle(cm.display.scroller, "dragleave", funcs.leave) toggle(cm.display.scroller, "drop", funcs.drop) } } function wrappingChanged(cm) { if (cm.options.lineWrapping) { addClass(cm.display.wrapper, "CodeMirror-wrap") cm.display.sizer.style.minWidth = "" cm.display.sizerWidth = null } else { rmClass(cm.display.wrapper, "CodeMirror-wrap") findMaxLine(cm) } estimateLineHeights(cm) regChange(cm) clearCaches(cm) setTimeout(() => updateScrollbars(cm), 100) } ================================================ FILE: third_party/CodeMirror/src/edit/utils.js ================================================ import { clearCaches } from "../measurement/position_measurement.js" export function themeChanged(cm) { cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-") clearCaches(cm) } ================================================ FILE: third_party/CodeMirror/src/input/ContentEditableInput.js ================================================ import { operation, runInOp } from "../display/operations.js" import { prepareSelection } from "../display/selection.js" import { regChange } from "../display/view_tracking.js" import { applyTextInput, copyableRanges, disableBrowserMagic, handlePaste, hiddenTextarea, lastCopied, setLastCopied } from "./input.js" import { cmp, maxPos, minPos, Pos } from "../line/pos.js" import { getBetween, getLine, lineNo } from "../line/utils_line.js" import { findViewForLine, findViewIndex, mapFromLineView, nodeAndOffsetInLineMap } from "../measurement/position_measurement.js" import { replaceRange } from "../model/changes.js" import { simpleSelection } from "../model/selection.js" import { setSelection } from "../model/selection_updates.js" import { getBidiPartAt, getOrder } from "../util/bidi.js" import { android, chrome, gecko, ie_version } from "../util/browser.js" import { contains, range, removeChildrenAndAdd, selectInput } from "../util/dom.js" import { on, signalDOMEvent } from "../util/event.js" import { Delayed, lst, sel_dontScroll } from "../util/misc.js" // CONTENTEDITABLE INPUT STYLE export default class ContentEditableInput { constructor(cm) { this.cm = cm this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null this.polling = new Delayed() this.composing = null this.gracePeriod = false this.readDOMTimeout = null } init(display) { let input = this, cm = input.cm let div = input.div = display.lineDiv disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize) on(div, "paste", e => { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return // IE doesn't fire input events, so we schedule a read for the pasted content in this way if (ie_version <= 11) setTimeout(operation(cm, () => this.updateFromDOM()), 20) }) on(div, "compositionstart", e => { this.composing = {data: e.data, done: false} }) on(div, "compositionupdate", e => { if (!this.composing) this.composing = {data: e.data, done: false} }) on(div, "compositionend", e => { if (this.composing) { if (e.data != this.composing.data) this.readFromDOMSoon() this.composing.done = true } }) on(div, "touchstart", () => input.forceCompositionEnd()) on(div, "input", () => { if (!this.composing) this.readFromDOMSoon() }) function onCopyCut(e) { if (signalDOMEvent(cm, e)) return if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}) if (e.type == "cut") cm.replaceSelection("", null, "cut") } else if (!cm.options.lineWiseCopyCut) { return } else { let ranges = copyableRanges(cm) setLastCopied({lineWise: true, text: ranges.text}) if (e.type == "cut") { cm.operation(() => { cm.setSelections(ranges.ranges, 0, sel_dontScroll) cm.replaceSelection("", null, "cut") }) } } if (e.clipboardData) { e.clipboardData.clearData() let content = lastCopied.text.join("\n") // iOS exposes the clipboard API, but seems to discard content inserted into it e.clipboardData.setData("Text", content) if (e.clipboardData.getData("Text") == content) { e.preventDefault() return } } // Old-fashioned briefly-focus-a-textarea hack let kludge = hiddenTextarea(), te = kludge.firstChild cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild) te.value = lastCopied.text.join("\n") let hadFocus = document.activeElement selectInput(te) setTimeout(() => { cm.display.lineSpace.removeChild(kludge) hadFocus.focus() if (hadFocus == div) input.showPrimarySelection() }, 50) } on(div, "copy", onCopyCut) on(div, "cut", onCopyCut) } prepareSelection() { let result = prepareSelection(this.cm, false) result.focus = this.cm.state.focused return result } showSelection(info, takeFocus) { if (!info || !this.cm.display.view.length) return if (info.focus || takeFocus) this.showPrimarySelection() this.showMultipleSelections(info) } getSelection() { return this.cm.display.wrapper.ownerDocument.getSelection() } showPrimarySelection() { let sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary() let from = prim.from(), to = prim.to() if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { sel.removeAllRanges() return } let curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) let curFocus = domToPos(cm, sel.focusNode, sel.focusOffset) if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && cmp(minPos(curAnchor, curFocus), from) == 0 && cmp(maxPos(curAnchor, curFocus), to) == 0) return let view = cm.display.view let start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || {node: view[0].measure.map[2], offset: 0} let end = to.line < cm.display.viewTo && posToDOM(cm, to) if (!end) { let measure = view[view.length - 1].measure let map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]} } if (!start || !end) { sel.removeAllRanges() return } let old = sel.rangeCount && sel.getRangeAt(0), rng try { rng = range(start.node, start.offset, end.offset, end.node) } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible if (rng) { if (!gecko && cm.state.focused) { sel.collapse(start.node, start.offset) if (!rng.collapsed) { sel.removeAllRanges() sel.addRange(rng) } } else { sel.removeAllRanges() sel.addRange(rng) } if (old && sel.anchorNode == null) sel.addRange(old) else if (gecko) this.startGracePeriod() } this.rememberSelection() } startGracePeriod() { clearTimeout(this.gracePeriod) this.gracePeriod = setTimeout(() => { this.gracePeriod = false if (this.selectionChanged()) this.cm.operation(() => this.cm.curOp.selectionChanged = true) }, 20) } showMultipleSelections(info) { removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors) removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection) } rememberSelection() { let sel = this.getSelection() this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset } selectionInEditor() { let sel = this.getSelection() if (!sel.rangeCount) return false let node = sel.getRangeAt(0).commonAncestorContainer return contains(this.div, node) } focus() { if (this.cm.options.readOnly != "nocursor") { if (!this.selectionInEditor()) this.showSelection(this.prepareSelection(), true) this.div.focus() } } blur() { this.div.blur() } getField() { return this.div } supportsTouch() { return true } receivedFocus() { let input = this if (this.selectionInEditor()) this.pollSelection() else runInOp(this.cm, () => input.cm.curOp.selectionChanged = true) function poll() { if (input.cm.state.focused) { input.pollSelection() input.polling.set(input.cm.options.pollInterval, poll) } } this.polling.set(this.cm.options.pollInterval, poll) } selectionChanged() { let sel = this.getSelection() return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset } pollSelection() { if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) return let sel = this.getSelection(), cm = this.cm // On Android Chrome (version 56, at least), backspacing into an // uneditable block element will put the cursor in that element, // and then, because it's not editable, hide the virtual keyboard. // Because Android doesn't allow us to actually detect backspace // presses in a sane way, this code checks for when that happens // and simulates a backspace press in this case. if (android && chrome && this.cm.options.gutters.length && isInGutter(sel.anchorNode)) { this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}) this.blur() this.focus() return } if (this.composing) return this.rememberSelection() let anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset) let head = domToPos(cm, sel.focusNode, sel.focusOffset) if (anchor && head) runInOp(cm, () => { setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll) if (anchor.bad || head.bad) cm.curOp.selectionChanged = true }) } pollContent() { if (this.readDOMTimeout != null) { clearTimeout(this.readDOMTimeout) this.readDOMTimeout = null } let cm = this.cm, display = cm.display, sel = cm.doc.sel.primary() let from = sel.from(), to = sel.to() if (from.ch == 0 && from.line > cm.firstLine()) from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length) if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) to = Pos(to.line + 1, 0) if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false let fromIndex, fromLine, fromNode if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { fromLine = lineNo(display.view[0].line) fromNode = display.view[0].node } else { fromLine = lineNo(display.view[fromIndex].line) fromNode = display.view[fromIndex - 1].node.nextSibling } let toIndex = findViewIndex(cm, to.line) let toLine, toNode if (toIndex == display.view.length - 1) { toLine = display.viewTo - 1 toNode = display.lineDiv.lastChild } else { toLine = lineNo(display.view[toIndex + 1].line) - 1 toNode = display.view[toIndex + 1].node.previousSibling } if (!fromNode) return false let newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)) let oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)) while (newText.length > 1 && oldText.length > 1) { if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine-- } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++ } else break } let cutFront = 0, cutEnd = 0 let newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length) while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) ++cutFront let newBot = lst(newText), oldBot = lst(oldText) let maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), oldBot.length - (oldText.length == 1 ? cutFront : 0)) while (cutEnd < maxCutEnd && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) ++cutEnd // Try to move start of change to start of selection if ambiguous if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { while (cutFront && cutFront > from.ch && newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { cutFront-- cutEnd++ } } newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "") newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "") let chFrom = Pos(fromLine, cutFront) let chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0) if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { replaceRange(cm.doc, newText, chFrom, chTo, "+input") return true } } ensurePolled() { this.forceCompositionEnd() } reset() { this.forceCompositionEnd() } forceCompositionEnd() { if (!this.composing) return clearTimeout(this.readDOMTimeout) this.composing = null this.updateFromDOM() this.div.blur() this.div.focus() } readFromDOMSoon() { if (this.readDOMTimeout != null) return this.readDOMTimeout = setTimeout(() => { this.readDOMTimeout = null if (this.composing) { if (this.composing.done) this.composing = null else return } this.updateFromDOM() }, 80) } updateFromDOM() { if (this.cm.isReadOnly() || !this.pollContent()) runInOp(this.cm, () => regChange(this.cm)) } setUneditable(node) { node.contentEditable = "false" } onKeyPress(e) { if (e.charCode == 0 || this.composing) return e.preventDefault() if (!this.cm.isReadOnly()) operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0) } readOnlyChanged(val) { this.div.contentEditable = String(val != "nocursor") } onContextMenu() {} resetPosition() {} } ContentEditableInput.prototype.needsContentAttribute = true function posToDOM(cm, pos) { let view = findViewForLine(cm, pos.line) if (!view || view.hidden) return null let line = getLine(cm.doc, pos.line) let info = mapFromLineView(view, line, pos.line) let order = getOrder(line, cm.doc.direction), side = "left" if (order) { let partPos = getBidiPartAt(order, pos.ch) side = partPos % 2 ? "right" : "left" } let result = nodeAndOffsetInLineMap(info.map, pos.ch, side) result.offset = result.collapse == "right" ? result.end : result.start return result } function isInGutter(node) { for (let scan = node; scan; scan = scan.parentNode) if (/CodeMirror-gutter-wrapper/.test(scan.className)) return true return false } function badPos(pos, bad) { if (bad) pos.bad = true; return pos } function domTextBetween(cm, from, to, fromLine, toLine) { let text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false function recognizeMarker(id) { return marker => marker.id == id } function close() { if (closing) { text += lineSep if (extraLinebreak) text += lineSep closing = extraLinebreak = false } } function addText(str) { if (str) { close() text += str } } function walk(node) { if (node.nodeType == 1) { let cmText = node.getAttribute("cm-text") if (cmText) { addText(cmText) return } let markerID = node.getAttribute("cm-marker"), range if (markerID) { let found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)) if (found.length && (range = found[0].find(0))) addText(getBetween(cm.doc, range.from, range.to).join(lineSep)) return } if (node.getAttribute("contenteditable") == "false") return let isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName) if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) return if (isBlock) close() for (let i = 0; i < node.childNodes.length; i++) walk(node.childNodes[i]) if (/^(pre|p)$/i.test(node.nodeName)) extraLinebreak = true if (isBlock) closing = true } else if (node.nodeType == 3) { addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")) } } for (;;) { walk(from) if (from == to) break from = from.nextSibling extraLinebreak = false } return text } function domToPos(cm, node, offset) { let lineNode if (node == cm.display.lineDiv) { lineNode = cm.display.lineDiv.childNodes[offset] if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) node = null; offset = 0 } else { for (lineNode = node;; lineNode = lineNode.parentNode) { if (!lineNode || lineNode == cm.display.lineDiv) return null if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break } } for (let i = 0; i < cm.display.view.length; i++) { let lineView = cm.display.view[i] if (lineView.node == lineNode) return locateNodeInLineView(lineView, node, offset) } } function locateNodeInLineView(lineView, node, offset) { let wrapper = lineView.text.firstChild, bad = false if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true) if (node == wrapper) { bad = true node = wrapper.childNodes[offset] offset = 0 if (!node) { let line = lineView.rest ? lst(lineView.rest) : lineView.line return badPos(Pos(lineNo(line), line.text.length), bad) } } let textNode = node.nodeType == 3 ? node : null, topNode = node if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { textNode = node.firstChild if (offset) offset = textNode.nodeValue.length } while (topNode.parentNode != wrapper) topNode = topNode.parentNode let measure = lineView.measure, maps = measure.maps function find(textNode, topNode, offset) { for (let i = -1; i < (maps ? maps.length : 0); i++) { let map = i < 0 ? measure.map : maps[i] for (let j = 0; j < map.length; j += 3) { let curNode = map[j + 2] if (curNode == textNode || curNode == topNode) { let line = lineNo(i < 0 ? lineView.line : lineView.rest[i]) let ch = map[j] + offset if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)] return Pos(line, ch) } } } } let found = find(textNode, topNode, offset) if (found) return badPos(found, bad) // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems for (let after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { found = find(after, after.firstChild, 0) if (found) return badPos(Pos(found.line, found.ch - dist), bad) else dist += after.textContent.length } for (let before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { found = find(before, before.firstChild, -1) if (found) return badPos(Pos(found.line, found.ch + dist), bad) else dist += before.textContent.length } } ================================================ FILE: third_party/CodeMirror/src/input/TextareaInput.js ================================================ import { operation, runInOp } from "../display/operations.js" import { prepareSelection } from "../display/selection.js" import { applyTextInput, copyableRanges, handlePaste, hiddenTextarea, setLastCopied } from "./input.js" import { cursorCoords, posFromMouse } from "../measurement/position_measurement.js" import { eventInWidget } from "../measurement/widgets.js" import { simpleSelection } from "../model/selection.js" import { selectAll, setSelection } from "../model/selection_updates.js" import { captureRightClick, ie, ie_version, ios, mac, mobile, presto, webkit } from "../util/browser.js" import { activeElt, removeChildrenAndAdd, selectInput } from "../util/dom.js" import { e_preventDefault, e_stop, off, on, signalDOMEvent } from "../util/event.js" import { hasSelection } from "../util/feature_detection.js" import { Delayed, sel_dontScroll } from "../util/misc.js" // TEXTAREA INPUT STYLE export default class TextareaInput { constructor(cm) { this.cm = cm // See input.poll and input.reset this.prevInput = "" // Flag that indicates whether we expect input to appear real soon // now (after some event like 'keypress' or 'input') and are // polling intensively. this.pollingFast = false // Self-resetting timeout for the poller this.polling = new Delayed() // Used to work around IE issue with selection being forgotten when focus moves away from textarea this.hasSelection = false this.composing = null } init(display) { let input = this, cm = this.cm this.createField(display) const te = this.textarea display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild) // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) if (ios) te.style.width = "0px" on(te, "input", () => { if (ie && ie_version >= 9 && this.hasSelection) this.hasSelection = null input.poll() }) on(te, "paste", e => { if (signalDOMEvent(cm, e) || handlePaste(e, cm)) return cm.state.pasteIncoming = true input.fastPoll() }) function prepareCopyCut(e) { if (signalDOMEvent(cm, e)) return if (cm.somethingSelected()) { setLastCopied({lineWise: false, text: cm.getSelections()}) } else if (!cm.options.lineWiseCopyCut) { return } else { let ranges = copyableRanges(cm) setLastCopied({lineWise: true, text: ranges.text}) if (e.type == "cut") { cm.setSelections(ranges.ranges, null, sel_dontScroll) } else { input.prevInput = "" te.value = ranges.text.join("\n") selectInput(te) } } if (e.type == "cut") cm.state.cutIncoming = true } on(te, "cut", prepareCopyCut) on(te, "copy", prepareCopyCut) on(display.scroller, "paste", e => { if (eventInWidget(display, e) || signalDOMEvent(cm, e)) return cm.state.pasteIncoming = true input.focus() }) // Prevent normal selection in the editor (we handle our own) on(display.lineSpace, "selectstart", e => { if (!eventInWidget(display, e)) e_preventDefault(e) }) on(te, "compositionstart", () => { let start = cm.getCursor("from") if (input.composing) input.composing.range.clear() input.composing = { start: start, range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) } }) on(te, "compositionend", () => { if (input.composing) { input.poll() input.composing.range.clear() input.composing = null } }) } createField(_display) { // Wraps and hides input textarea this.wrapper = hiddenTextarea() // The semihidden textarea that is focused when the editor is // focused, and receives input. this.textarea = this.wrapper.firstChild } prepareSelection() { // Redraw the selection and/or cursor let cm = this.cm, display = cm.display, doc = cm.doc let result = prepareSelection(cm) // Move the hidden textarea near the cursor to prevent scrolling artifacts if (cm.options.moveInputWithCursor) { let headPos = cursorCoords(cm, doc.sel.primary().head, "div") let wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect() result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, headPos.top + lineOff.top - wrapOff.top)) result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, headPos.left + lineOff.left - wrapOff.left)) } return result } showSelection(drawn) { let cm = this.cm, display = cm.display removeChildrenAndAdd(display.cursorDiv, drawn.cursors) removeChildrenAndAdd(display.selectionDiv, drawn.selection) if (drawn.teTop != null) { this.wrapper.style.top = drawn.teTop + "px" this.wrapper.style.left = drawn.teLeft + "px" } } // Reset the input to correspond to the selection (or to be empty, // when not typing and nothing is selected) reset(typing) { if (this.contextMenuPending || this.composing) return let cm = this.cm if (cm.somethingSelected()) { this.prevInput = "" let content = cm.getSelection() this.textarea.value = content if (cm.state.focused) selectInput(this.textarea) if (ie && ie_version >= 9) this.hasSelection = content } else if (!typing) { this.prevInput = this.textarea.value = "" if (ie && ie_version >= 9) this.hasSelection = null } } getField() { return this.textarea } supportsTouch() { return false } focus() { if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { try { this.textarea.focus() } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM } } blur() { this.textarea.blur() } resetPosition() { this.wrapper.style.top = this.wrapper.style.left = 0 } receivedFocus() { this.slowPoll() } // Poll for input changes, using the normal rate of polling. This // runs as long as the editor is focused. slowPoll() { if (this.pollingFast) return this.polling.set(this.cm.options.pollInterval, () => { this.poll() if (this.cm.state.focused) this.slowPoll() }) } // When an event has just come in that is likely to add or change // something in the input textarea, we poll faster, to ensure that // the change appears on the screen quickly. fastPoll() { let missed = false, input = this input.pollingFast = true function p() { let changed = input.poll() if (!changed && !missed) {missed = true; input.polling.set(60, p)} else {input.pollingFast = false; input.slowPoll()} } input.polling.set(20, p) } // Read input from the textarea, and update the document to match. // When something is selected, it is present in the textarea, and // selected (unless it is huge, in which case a placeholder is // used). When nothing is selected, the cursor sits after previously // seen text (can be empty), which is stored in prevInput (we must // not reset the textarea when typing, because that breaks IME). poll() { let cm = this.cm, input = this.textarea, prevInput = this.prevInput // Since this is called a *lot*, try to bail out as cheaply as // possible when it is clear that nothing happened. hasSelection // will be the case when there is a lot of text in the textarea, // in which case reading its value would be expensive. if (this.contextMenuPending || !cm.state.focused || (hasSelection(input) && !prevInput && !this.composing) || cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) return false let text = input.value // If nothing changed, bail. if (text == prevInput && !cm.somethingSelected()) return false // Work around nonsensical selection resetting in IE9/10, and // inexplicable appearance of private area unicode characters on // some key combos in Mac (#2689). if (ie && ie_version >= 9 && this.hasSelection === text || mac && /[\uf700-\uf7ff]/.test(text)) { cm.display.input.reset() return false } if (cm.doc.sel == cm.display.selForContextMenu) { let first = text.charCodeAt(0) if (first == 0x200b && !prevInput) prevInput = "\u200b" if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } } // Find the part of the input that is actually new let same = 0, l = Math.min(prevInput.length, text.length) while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same runInOp(cm, () => { applyTextInput(cm, text.slice(same), prevInput.length - same, null, this.composing ? "*compose" : null) // Don't leave long text in the textarea, since it makes further polling slow if (text.length > 1000 || text.indexOf("\n") > -1) input.value = this.prevInput = "" else this.prevInput = text if (this.composing) { this.composing.range.clear() this.composing.range = cm.markText(this.composing.start, cm.getCursor("to"), {className: "CodeMirror-composing"}) } }) return true } ensurePolled() { if (this.pollingFast && this.poll()) this.pollingFast = false } onKeyPress() { if (ie && ie_version >= 9) this.hasSelection = null this.fastPoll() } onContextMenu(e) { let input = this, cm = input.cm, display = cm.display, te = input.textarea if (input.contextMenuPending) input.contextMenuPending() let pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop if (!pos || presto) return // Opera is difficult. // Reset the current text selection only if the click is done outside of the selection // and 'resetSelectionOnContextMenu' option is true. let reset = cm.options.resetSelectionOnContextMenu if (reset && cm.doc.sel.contains(pos) == -1) operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll) let oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText let wrapperBox = input.wrapper.offsetParent.getBoundingClientRect() input.wrapper.style.cssText = "position: static" te.style.cssText = `position: absolute; width: 30px; height: 30px; top: ${e.clientY - wrapperBox.top - 5}px; left: ${e.clientX - wrapperBox.left - 5}px; z-index: 1000; background: ${ie ? "rgba(255, 255, 255, .05)" : "transparent"}; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);` let oldScrollY if (webkit) oldScrollY = window.scrollY // Work around Chrome issue (#2712) display.input.focus() if (webkit) window.scrollTo(null, oldScrollY) display.input.reset() // Adds "Select all" to context menu in FF if (!cm.somethingSelected()) te.value = input.prevInput = " " input.contextMenuPending = rehide display.selForContextMenu = cm.doc.sel clearTimeout(display.detectingSelectAll) // Select-all will be greyed out if there's nothing to select, so // this adds a zero-width space so that we can later check whether // it got selected. function prepareSelectAllHack() { if (te.selectionStart != null) { let selected = cm.somethingSelected() let extval = "\u200b" + (selected ? te.value : "") te.value = "\u21da" // Used to catch context-menu undo te.value = extval input.prevInput = selected ? "" : "\u200b" te.selectionStart = 1; te.selectionEnd = extval.length // Re-set this, in case some other handler touched the // selection in the meantime. display.selForContextMenu = cm.doc.sel } } function rehide() { if (input.contextMenuPending != rehide) return input.contextMenuPending = false input.wrapper.style.cssText = oldWrapperCSS te.style.cssText = oldCSS if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos) // Try to detect the user choosing select-all if (te.selectionStart != null) { if (!ie || (ie && ie_version < 9)) prepareSelectAllHack() let i = 0, poll = () => { if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && te.selectionEnd > 0 && input.prevInput == "\u200b") { operation(cm, selectAll)(cm) } else if (i++ < 10) { display.detectingSelectAll = setTimeout(poll, 500) } else { display.selForContextMenu = null display.input.reset() } } display.detectingSelectAll = setTimeout(poll, 200) } } if (ie && ie_version >= 9) prepareSelectAllHack() if (captureRightClick) { e_stop(e) let mouseup = () => { off(window, "mouseup", mouseup) setTimeout(rehide, 20) } on(window, "mouseup", mouseup) } else { setTimeout(rehide, 50) } } readOnlyChanged(val) { if (!val) this.reset() this.textarea.disabled = val == "nocursor" } setUneditable() {} } TextareaInput.prototype.needsContentAttribute = false ================================================ FILE: third_party/CodeMirror/src/input/indent.js ================================================ import { getContextBefore } from "../line/highlight.js" import { Pos } from "../line/pos.js" import { getLine } from "../line/utils_line.js" import { replaceRange } from "../model/changes.js" import { Range } from "../model/selection.js" import { replaceOneSelection } from "../model/selection_updates.js" import { countColumn, Pass, spaceStr } from "../util/misc.js" // Indent the given line. The how parameter can be "smart", // "add"/null, "subtract", or "prev". When aggressive is false // (typically set to true for forced single-line indents), empty // lines are not indented, and places where the mode returns Pass // are left alone. export function indentLine(cm, n, how, aggressive) { let doc = cm.doc, state if (how == null) how = "add" if (how == "smart") { // Fall back to "prev" when the mode doesn't have an indentation // method. if (!doc.mode.indent) how = "prev" else state = getContextBefore(cm, n).state } let tabSize = cm.options.tabSize let line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize) if (line.stateAfter) line.stateAfter = null let curSpaceString = line.text.match(/^\s*/)[0], indentation if (!aggressive && !/\S/.test(line.text)) { indentation = 0 how = "not" } else if (how == "smart") { indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text) if (indentation == Pass || indentation > 150) { if (!aggressive) return how = "prev" } } if (how == "prev") { if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize) else indentation = 0 } else if (how == "add") { indentation = curSpace + cm.options.indentUnit } else if (how == "subtract") { indentation = curSpace - cm.options.indentUnit } else if (typeof how == "number") { indentation = curSpace + how } indentation = Math.max(0, indentation) let indentString = "", pos = 0 if (cm.options.indentWithTabs) for (let i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t"} if (pos < indentation) indentString += spaceStr(indentation - pos) if (indentString != curSpaceString) { replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input") line.stateAfter = null return true } else { // Ensure that, if the cursor was in the whitespace at the start // of the line, it is moved to the end of that space. for (let i = 0; i < doc.sel.ranges.length; i++) { let range = doc.sel.ranges[i] if (range.head.line == n && range.head.ch < curSpaceString.length) { let pos = Pos(n, curSpaceString.length) replaceOneSelection(doc, i, new Range(pos, pos)) break } } } } ================================================ FILE: third_party/CodeMirror/src/input/input.js ================================================ import { runInOp } from "../display/operations.js" import { ensureCursorVisible } from "../display/scrolling.js" import { Pos } from "../line/pos.js" import { getLine } from "../line/utils_line.js" import { makeChange } from "../model/changes.js" import { ios, webkit } from "../util/browser.js" import { elt } from "../util/dom.js" import { lst, map } from "../util/misc.js" import { signalLater } from "../util/operation_group.js" import { splitLinesAuto } from "../util/feature_detection.js" import { indentLine } from "./indent.js" // This will be set to a {lineWise: bool, text: [string]} object, so // that, when pasting, we know what kind of selections the copied // text was made out of. export let lastCopied = null export function setLastCopied(newLastCopied) { lastCopied = newLastCopied } export function applyTextInput(cm, inserted, deleted, sel, origin) { let doc = cm.doc cm.display.shift = false if (!sel) sel = doc.sel let paste = cm.state.pasteIncoming || origin == "paste" let textLines = splitLinesAuto(inserted), multiPaste = null // When pasting N lines into N selections, insert one line per selection if (paste && sel.ranges.length > 1) { if (lastCopied && lastCopied.text.join("\n") == inserted) { if (sel.ranges.length % lastCopied.text.length == 0) { multiPaste = [] for (let i = 0; i < lastCopied.text.length; i++) multiPaste.push(doc.splitLines(lastCopied.text[i])) } } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { multiPaste = map(textLines, l => [l]) } } let updateInput = cm.curOp.updateInput // Normal behavior is to insert the new text into every selection for (let i = sel.ranges.length - 1; i >= 0; i--) { let range = sel.ranges[i] let from = range.from(), to = range.to() if (range.empty()) { if (deleted && deleted > 0) // Handle deletion from = Pos(from.line, from.ch - deleted) else if (cm.state.overwrite && !paste) // Handle overwrite to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)) else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) from = to = Pos(from.line, 0) } let changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")} makeChange(cm.doc, changeEvent) signalLater(cm, "inputRead", cm, changeEvent) } if (inserted && !paste) triggerElectric(cm, inserted) ensureCursorVisible(cm) if (cm.curOp.updateInput < 2) cm.curOp.updateInput = updateInput cm.curOp.typing = true cm.state.pasteIncoming = cm.state.cutIncoming = false } export function handlePaste(e, cm) { let pasted = e.clipboardData && e.clipboardData.getData("Text") if (pasted) { e.preventDefault() if (!cm.isReadOnly() && !cm.options.disableInput) runInOp(cm, () => applyTextInput(cm, pasted, 0, null, "paste")) return true } } export function triggerElectric(cm, inserted) { // When an 'electric' character is inserted, immediately trigger a reindent if (!cm.options.electricChars || !cm.options.smartIndent) return let sel = cm.doc.sel for (let i = sel.ranges.length - 1; i >= 0; i--) { let range = sel.ranges[i] if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue let mode = cm.getModeAt(range.head) let indented = false if (mode.electricChars) { for (let j = 0; j < mode.electricChars.length; j++) if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { indented = indentLine(cm, range.head.line, "smart") break } } else if (mode.electricInput) { if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) indented = indentLine(cm, range.head.line, "smart") } if (indented) signalLater(cm, "electricInput", cm, range.head.line) } } export function copyableRanges(cm) { let text = [], ranges = [] for (let i = 0; i < cm.doc.sel.ranges.length; i++) { let line = cm.doc.sel.ranges[i].head.line let lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)} ranges.push(lineRange) text.push(cm.getRange(lineRange.anchor, lineRange.head)) } return {text: text, ranges: ranges} } export function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { field.setAttribute("autocorrect", !!autocorrect) field.setAttribute("autocapitalize", !!autocapitalize) field.setAttribute("spellcheck", !!spellcheck) } export function hiddenTextarea() { let te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none") let div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;") // The textarea is kept positioned near the cursor to prevent the // fact that it'll be scrolled into view on input from scrolling // our fake cursor out of view. On webkit, when wrap=off, paste is // very slow. So make the area wide instead. if (webkit) te.style.width = "1000px" else te.setAttribute("wrap", "off") // If border: 0; -- iOS fails to open keyboard (issue #1287) if (ios) te.style.border = "1px solid black" disableBrowserMagic(te) return div } ================================================ FILE: third_party/CodeMirror/src/input/keymap.js ================================================ import { flipCtrlCmd, mac, presto } from "../util/browser.js" import { map } from "../util/misc.js" import { keyNames } from "./keynames.js" export let keyMap = {} keyMap.basic = { "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", "Tab": "defaultTab", "Shift-Tab": "indentAuto", "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", "Esc": "singleSelection" } // Note that the save and find-related commands aren't defined by // default. User code or addons can define them. Unknown commands // are simply ignored. keyMap.pcDefault = { "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", "fallthrough": "basic" } // Very basic readline/emacs-style bindings, which are standard on Mac. keyMap.emacsy = { "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", "Ctrl-O": "openLine" } keyMap.macDefault = { "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", "fallthrough": ["basic", "emacsy"] } keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault // KEYMAP DISPATCH function normalizeKeyName(name) { let parts = name.split(/-(?!$)/) name = parts[parts.length - 1] let alt, ctrl, shift, cmd for (let i = 0; i < parts.length - 1; i++) { let mod = parts[i] if (/^(cmd|meta|m)$/i.test(mod)) cmd = true else if (/^a(lt)?$/i.test(mod)) alt = true else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true else if (/^s(hift)?$/i.test(mod)) shift = true else throw new Error("Unrecognized modifier name: " + mod) } if (alt) name = "Alt-" + name if (ctrl) name = "Ctrl-" + name if (cmd) name = "Cmd-" + name if (shift) name = "Shift-" + name return name } // This is a kludge to keep keymaps mostly working as raw objects // (backwards compatibility) while at the same time support features // like normalization and multi-stroke key bindings. It compiles a // new normalized keymap, and then updates the old object to reflect // this. export function normalizeKeyMap(keymap) { let copy = {} for (let keyname in keymap) if (keymap.hasOwnProperty(keyname)) { let value = keymap[keyname] if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue if (value == "...") { delete keymap[keyname]; continue } let keys = map(keyname.split(" "), normalizeKeyName) for (let i = 0; i < keys.length; i++) { let val, name if (i == keys.length - 1) { name = keys.join(" ") val = value } else { name = keys.slice(0, i + 1).join(" ") val = "..." } let prev = copy[name] if (!prev) copy[name] = val else if (prev != val) throw new Error("Inconsistent bindings for " + name) } delete keymap[keyname] } for (let prop in copy) keymap[prop] = copy[prop] return keymap } export function lookupKey(key, map, handle, context) { map = getKeyMap(map) let found = map.call ? map.call(key, context) : map[key] if (found === false) return "nothing" if (found === "...") return "multi" if (found != null && handle(found)) return "handled" if (map.fallthrough) { if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") return lookupKey(key, map.fallthrough, handle, context) for (let i = 0; i < map.fallthrough.length; i++) { let result = lookupKey(key, map.fallthrough[i], handle, context) if (result) return result } } } // Modifier key presses don't count as 'real' key presses for the // purpose of keymap fallthrough. export function isModifierKey(value) { let name = typeof value == "string" ? value : keyNames[value.keyCode] return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" } export function addModifierNames(name, event, noShift) { let base = name if (event.altKey && base != "Alt") name = "Alt-" + name if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name return name } // Look up the name of a key as indicated by an event object. export function keyName(event, noShift) { if (presto && event.keyCode == 34 && event["char"]) return false let name = keyNames[event.keyCode] if (name == null || event.altGraphKey) return false // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) if (event.keyCode == 3 && event.code) name = event.code return addModifierNames(name, event, noShift) } export function getKeyMap(val) { return typeof val == "string" ? keyMap[val] : val } ================================================ FILE: third_party/CodeMirror/src/input/keynames.js ================================================ export let keyNames = { 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 127: "Delete", 145: "ScrollLock", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" } // Number keys for (let i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i) // Alphabetic keys for (let i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i) // Function keys for (let i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i ================================================ FILE: third_party/CodeMirror/src/input/movement.js ================================================ import { Pos } from "../line/pos.js" import { prepareMeasureForLine, measureCharPrepared, wrappedLineExtentChar } from "../measurement/position_measurement.js" import { getBidiPartAt, getOrder } from "../util/bidi.js" import { findFirst, lst, skipExtendingChars } from "../util/misc.js" function moveCharLogically(line, ch, dir) { let target = skipExtendingChars(line.text, ch + dir, dir) return target < 0 || target > line.text.length ? null : target } export function moveLogically(line, start, dir) { let ch = moveCharLogically(line, start.ch, dir) return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") } export function endOfLine(visually, cm, lineObj, lineNo, dir) { if (visually) { let order = getOrder(lineObj, cm.doc.direction) if (order) { let part = dir < 0 ? lst(order) : order[0] let moveInStorageOrder = (dir < 0) == (part.level == 1) let sticky = moveInStorageOrder ? "after" : "before" let ch // With a wrapped rtl chunk (possibly spanning multiple bidi parts), // it could be that the last bidi part is not on the last visual line, // since visual lines contain content order-consecutive chunks. // Thus, in rtl, we are looking for the first (content-order) character // in the rtl chunk that is on the last line (that is, the same line // as the last (content-order) character). if (part.level > 0 || cm.doc.direction == "rtl") { let prep = prepareMeasureForLine(cm, lineObj) ch = dir < 0 ? lineObj.text.length - 1 : 0 let targetTop = measureCharPrepared(cm, prep, ch).top ch = findFirst(ch => measureCharPrepared(cm, prep, ch).top == targetTop, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch) if (sticky == "before") ch = moveCharLogically(lineObj, ch, 1) } else ch = dir < 0 ? part.to : part.from return new Pos(lineNo, ch, sticky) } } return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") } export function moveVisually(cm, line, start, dir) { let bidi = getOrder(line, cm.doc.direction) if (!bidi) return moveLogically(line, start, dir) if (start.ch >= line.text.length) { start.ch = line.text.length start.sticky = "before" } else if (start.ch <= 0) { start.ch = 0 start.sticky = "after" } let partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos] if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, // nothing interesting happens. return moveLogically(line, start, dir) } let mv = (pos, dir) => moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir) let prep let getWrappedLineExtent = ch => { if (!cm.options.lineWrapping) return {begin: 0, end: line.text.length} prep = prep || prepareMeasureForLine(cm, line) return wrappedLineExtentChar(cm, line, prep, ch) } let wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch) if (cm.doc.direction == "rtl" || part.level == 1) { let moveInStorageOrder = (part.level == 1) == (dir < 0) let ch = mv(start, moveInStorageOrder ? 1 : -1) if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { // Case 2: We move within an rtl part or in an rtl editor on the same visual line let sticky = moveInStorageOrder ? "before" : "after" return new Pos(start.line, ch, sticky) } } // Case 3: Could not move within this bidi part in this visual line, so leave // the current bidi part let searchInVisualLine = (partPos, dir, wrappedLineExtent) => { let getRes = (ch, moveInStorageOrder) => moveInStorageOrder ? new Pos(start.line, mv(ch, 1), "before") : new Pos(start.line, ch, "after") for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { let part = bidi[partPos] let moveInStorageOrder = (dir > 0) == (part.level != 1) let ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1) if (part.from <= ch && ch < part.to) return getRes(ch, moveInStorageOrder) ch = moveInStorageOrder ? part.from : mv(part.to, -1) if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) return getRes(ch, moveInStorageOrder) } } // Case 3a: Look for other bidi parts on the same visual line let res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent) if (res) return res // Case 3b: Look for other bidi parts on the next visual line let nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1) if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)) if (res) return res } // Case 4: Nowhere to move return null } ================================================ FILE: third_party/CodeMirror/src/line/highlight.js ================================================ import { countColumn } from "../util/misc.js" import { copyState, innerMode, startState } from "../modes.js" import StringStream from "../util/StringStream.js" import { getLine, lineNo } from "./utils_line.js" import { clipPos } from "./pos.js" class SavedContext { constructor(state, lookAhead) { this.state = state this.lookAhead = lookAhead } } class Context { constructor(doc, state, line, lookAhead) { this.state = state this.doc = doc this.line = line this.maxLookAhead = lookAhead || 0 this.baseTokens = null this.baseTokenPos = 1 } lookAhead(n) { let line = this.doc.getLine(this.line + n) if (line != null && n > this.maxLookAhead) this.maxLookAhead = n return line } baseToken(n) { if (!this.baseTokens) return null while (this.baseTokens[this.baseTokenPos] <= n) this.baseTokenPos += 2 let type = this.baseTokens[this.baseTokenPos + 1] return {type: type && type.replace(/( |^)overlay .*/, ""), size: this.baseTokens[this.baseTokenPos] - n} } nextLine() { this.line++ if (this.maxLookAhead > 0) this.maxLookAhead-- } static fromSaved(doc, saved, line) { if (saved instanceof SavedContext) return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) else return new Context(doc, copyState(doc.mode, saved), line) } save(copy) { let state = copy !== false ? copyState(this.doc.mode, this.state) : this.state return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state } } // Compute a style array (an array starting with a mode generation // -- for invalidation -- followed by pairs of end positions and // style strings), which is used to highlight the tokens on the // line. export function highlightLine(cm, line, context, forceToEnd) { // A styles array always starts with a number identifying the // mode/overlays that it is based on (for easy invalidation). let st = [cm.state.modeGen], lineClasses = {} // Compute the base array of styles runMode(cm, line.text, cm.doc.mode, context, (end, style) => st.push(end, style), lineClasses, forceToEnd) let state = context.state // Run overlays, adjust style array. for (let o = 0; o < cm.state.overlays.length; ++o) { context.baseTokens = st let overlay = cm.state.overlays[o], i = 1, at = 0 context.state = true runMode(cm, line.text, overlay.mode, context, (end, style) => { let start = i // Ensure there's a token end at the current position, and that i points at it while (at < end) { let i_end = st[i] if (i_end > end) st.splice(i, 1, end, st[i+1], i_end) i += 2 at = Math.min(end, i_end) } if (!style) return if (overlay.opaque) { st.splice(start, i - start, end, "overlay " + style) i = start + 2 } else { for (; start < i; start += 2) { let cur = st[start+1] st[start+1] = (cur ? cur + " " : "") + "overlay " + style } } }, lineClasses) context.state = state context.baseTokens = null context.baseTokenPos = 1 } return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} } export function getLineStyles(cm, line, updateFrontier) { if (!line.styles || line.styles[0] != cm.state.modeGen) { let context = getContextBefore(cm, lineNo(line)) let resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state) let result = highlightLine(cm, line, context) if (resetState) context.state = resetState line.stateAfter = context.save(!resetState) line.styles = result.styles if (result.classes) line.styleClasses = result.classes else if (line.styleClasses) line.styleClasses = null if (updateFrontier === cm.doc.highlightFrontier) cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier) } return line.styles } export function getContextBefore(cm, n, precise) { let doc = cm.doc, display = cm.display if (!doc.mode.startState) return new Context(doc, true, n) let start = findStartLine(cm, n, precise) let saved = start > doc.first && getLine(doc, start - 1).stateAfter let context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start) doc.iter(start, n, line => { processLine(cm, line.text, context) let pos = context.line line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null context.nextLine() }) if (precise) doc.modeFrontier = context.line return context } // Lightweight form of highlight -- proceed over this line and // update state, but don't save a style array. Used for lines that // aren't currently visible. export function processLine(cm, text, context, startAt) { let mode = cm.doc.mode let stream = new StringStream(text, cm.options.tabSize, context) stream.start = stream.pos = startAt || 0 if (text == "") callBlankLine(mode, context.state) while (!stream.eol()) { readToken(mode, stream, context.state) stream.start = stream.pos } } function callBlankLine(mode, state) { if (mode.blankLine) return mode.blankLine(state) if (!mode.innerMode) return let inner = innerMode(mode, state) if (inner.mode.blankLine) return inner.mode.blankLine(inner.state) } function readToken(mode, stream, state, inner) { for (let i = 0; i < 10; i++) { if (inner) inner[0] = innerMode(mode, state).mode let style = mode.token(stream, state) if (stream.pos > stream.start) return style } throw new Error("Mode " + mode.name + " failed to advance stream.") } class Token { constructor(stream, type, state) { this.start = stream.start; this.end = stream.pos this.string = stream.current() this.type = type || null this.state = state } } // Utility for getTokenAt and getLineTokens export function takeToken(cm, pos, precise, asArray) { let doc = cm.doc, mode = doc.mode, style pos = clipPos(doc, pos) let line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise) let stream = new StringStream(line.text, cm.options.tabSize, context), tokens if (asArray) tokens = [] while ((asArray || stream.pos < pos.ch) && !stream.eol()) { stream.start = stream.pos style = readToken(mode, stream, context.state) if (asArray) tokens.push(new Token(stream, style, copyState(doc.mode, context.state))) } return asArray ? tokens : new Token(stream, style, context.state) } function extractLineClasses(type, output) { if (type) for (;;) { let lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/) if (!lineClass) break type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length) let prop = lineClass[1] ? "bgClass" : "textClass" if (output[prop] == null) output[prop] = lineClass[2] else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) output[prop] += " " + lineClass[2] } return type } // Run the given mode's parser over a line, calling f for each token. function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { let flattenSpans = mode.flattenSpans if (flattenSpans == null) flattenSpans = cm.options.flattenSpans let curStart = 0, curStyle = null let stream = new StringStream(text, cm.options.tabSize, context), style let inner = cm.options.addModeClass && [null] if (text == "") extractLineClasses(callBlankLine(mode, context.state), lineClasses) while (!stream.eol()) { if (stream.pos > cm.options.maxHighlightLength) { flattenSpans = false if (forceToEnd) processLine(cm, text, context, stream.pos) stream.pos = text.length style = null } else { style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses) } if (inner) { let mName = inner[0].name if (mName) style = "m-" + (style ? mName + " " + style : mName) } if (!flattenSpans || curStyle != style) { while (curStart < stream.start) { curStart = Math.min(stream.start, curStart + 5000) f(curStart, curStyle) } curStyle = style } stream.start = stream.pos } while (curStart < stream.pos) { // Webkit seems to refuse to render text nodes longer than 57444 // characters, and returns inaccurate measurements in nodes // starting around 5000 chars. let pos = Math.min(stream.pos, curStart + 5000) f(pos, curStyle) curStart = pos } } // Finds the line to start with when starting a parse. Tries to // find a line with a stateAfter, so that it can start with a // valid state. If that fails, it returns the line with the // smallest indentation, which tends to need the least context to // parse correctly. function findStartLine(cm, n, precise) { let minindent, minline, doc = cm.doc let lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100) for (let search = n; search > lim; --search) { if (search <= doc.first) return doc.first let line = getLine(doc, search - 1), after = line.stateAfter if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) return search let indented = countColumn(line.text, null, cm.options.tabSize) if (minline == null || minindent > indented) { minline = search - 1 minindent = indented } } return minline } export function retreatFrontier(doc, n) { doc.modeFrontier = Math.min(doc.modeFrontier, n) if (doc.highlightFrontier < n - 10) return let start = doc.first for (let line = n - 1; line > start; line--) { let saved = getLine(doc, line).stateAfter // change is on 3 // state on line 1 looked ahead 2 -- so saw 3 // test 1 + 2 < 3 should cover this if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { start = line + 1 break } } doc.highlightFrontier = Math.min(doc.highlightFrontier, start) } ================================================ FILE: third_party/CodeMirror/src/line/line_data.js ================================================ import { getOrder } from "../util/bidi.js" import { ie, ie_version, webkit } from "../util/browser.js" import { elt, eltP, joinClasses } from "../util/dom.js" import { eventMixin, signal } from "../util/event.js" import { hasBadBidiRects, zeroWidthElement } from "../util/feature_detection.js" import { lst, spaceStr } from "../util/misc.js" import { getLineStyles } from "./highlight.js" import { attachMarkedSpans, compareCollapsedMarkers, detachMarkedSpans, lineIsHidden, visualLineContinued } from "./spans.js" import { getLine, lineNo, updateLineHeight } from "./utils_line.js" // LINE DATA STRUCTURE // Line objects. These hold state related to a line, including // highlighting info (the styles array). export class Line { constructor(text, markedSpans, estimateHeight) { this.text = text attachMarkedSpans(this, markedSpans) this.height = estimateHeight ? estimateHeight(this) : 1 } lineNo() { return lineNo(this) } } eventMixin(Line) // Change the content (text, markers) of a line. Automatically // invalidates cached information and tries to re-estimate the // line's height. export function updateLine(line, text, markedSpans, estimateHeight) { line.text = text if (line.stateAfter) line.stateAfter = null if (line.styles) line.styles = null if (line.order != null) line.order = null detachMarkedSpans(line) attachMarkedSpans(line, markedSpans) let estHeight = estimateHeight ? estimateHeight(line) : 1 if (estHeight != line.height) updateLineHeight(line, estHeight) } // Detach a line from the document tree and its markers. export function cleanUpLine(line) { line.parent = null detachMarkedSpans(line) } // Convert a style as returned by a mode (either null, or a string // containing one or more styles) to a CSS style. This is cached, // and also looks for line-wide styles. let styleToClassCache = {}, styleToClassCacheWithMode = {} function interpretTokenStyle(style, options) { if (!style || /^\s*$/.test(style)) return null let cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache return cache[style] || (cache[style] = style.replace(/\S+/g, "cm-$&")) } // Render the DOM representation of the text of a line. Also builds // up a 'line map', which points at the DOM nodes that represent // specific stretches of text, and is used by the measuring code. // The returned object contains the DOM node, this map, and // information about line-wide styles that were set by the mode. export function buildLineContent(cm, lineView) { // The padding-right forces the element to have a 'border', which // is needed on Webkit to be able to get line-level bounding // rectangles for it (in measureChar). let content = eltP("span", null, null, webkit ? "padding-right: .1px" : null) let builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, col: 0, pos: 0, cm: cm, trailingSpace: false, splitSpaces: cm.getOption("lineWrapping")} lineView.measure = {} // Iterate over the logical lines that make up this visual line. for (let i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { let line = i ? lineView.rest[i - 1] : lineView.line, order builder.pos = 0 builder.addToken = buildToken // Optionally wire in some hacks into the token-rendering // algorithm, to deal with browser quirks. if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) builder.addToken = buildTokenBadBidi(builder.addToken, order) builder.map = [] let allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line) insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)) if (line.styleClasses) { if (line.styleClasses.bgClass) builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "") if (line.styleClasses.textClass) builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "") } // Ensure at least a single node is present, for measuring. if (builder.map.length == 0) builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))) // Store the map and a cache object for the current logical line if (i == 0) { lineView.measure.map = builder.map lineView.measure.cache = {} } else { ;(lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}) } } // See issue #2901 if (webkit) { let last = builder.content.lastChild if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) builder.content.className = "cm-tab-wrap-hack" } signal(cm, "renderLine", cm, lineView.line, builder.pre) if (builder.pre.className) builder.textClass = joinClasses(builder.pre.className, builder.textClass || "") return builder } export function defaultSpecialCharPlaceholder(ch) { let token = elt("span", "\u2022", "cm-invalidchar") token.title = "\\u" + ch.charCodeAt(0).toString(16) token.setAttribute("aria-label", token.title) return token } // Build up the DOM representation for a single token, and add it to // the line map. Takes care to render special characters separately. function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { if (!text) return let displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text let special = builder.cm.state.specialChars, mustWrap = false let content if (!special.test(text)) { builder.col += text.length content = document.createTextNode(displayText) builder.map.push(builder.pos, builder.pos + text.length, content) if (ie && ie_version < 9) mustWrap = true builder.pos += text.length } else { content = document.createDocumentFragment() let pos = 0 while (true) { special.lastIndex = pos let m = special.exec(text) let skipped = m ? m.index - pos : text.length - pos if (skipped) { let txt = document.createTextNode(displayText.slice(pos, pos + skipped)) if (ie && ie_version < 9) content.appendChild(elt("span", [txt])) else content.appendChild(txt) builder.map.push(builder.pos, builder.pos + skipped, txt) builder.col += skipped builder.pos += skipped } if (!m) break pos += skipped + 1 let txt if (m[0] == "\t") { let tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")) txt.setAttribute("role", "presentation") txt.setAttribute("cm-text", "\t") builder.col += tabWidth } else if (m[0] == "\r" || m[0] == "\n") { txt = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")) txt.setAttribute("cm-text", m[0]) builder.col += 1 } else { txt = builder.cm.options.specialCharPlaceholder(m[0]) txt.setAttribute("cm-text", m[0]) if (ie && ie_version < 9) content.appendChild(elt("span", [txt])) else content.appendChild(txt) builder.col += 1 } builder.map.push(builder.pos, builder.pos + 1, txt) builder.pos++ } } builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32 if (style || startStyle || endStyle || mustWrap || css) { let fullStyle = style || "" if (startStyle) fullStyle += startStyle if (endStyle) fullStyle += endStyle let token = elt("span", [content], fullStyle, css) if (attributes) { for (let attr in attributes) if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") token.setAttribute(attr, attributes[attr]) } return builder.content.appendChild(token) } builder.content.appendChild(content) } // Change some spaces to NBSP to prevent the browser from collapsing // trailing spaces at the end of a line when rendering text (issue #1362). function splitSpaces(text, trailingBefore) { if (text.length > 1 && !/ /.test(text)) return text let spaceBefore = trailingBefore, result = "" for (let i = 0; i < text.length; i++) { let ch = text.charAt(i) if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) ch = "\u00a0" result += ch spaceBefore = ch == " " } return result } // Work around nonsense dimensions being reported for stretches of // right-to-left text. function buildTokenBadBidi(inner, order) { return (builder, text, style, startStyle, endStyle, css, attributes) => { style = style ? style + " cm-force-border" : "cm-force-border" let start = builder.pos, end = start + text.length for (;;) { // Find the part that overlaps with the start of this text let part for (let i = 0; i < order.length; i++) { part = order[i] if (part.to > start && part.from <= start) break } if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, css, attributes) inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes) startStyle = null text = text.slice(part.to - start) start = part.to } } } function buildCollapsedSpan(builder, size, marker, ignoreWidget) { let widget = !ignoreWidget && marker.widgetNode if (widget) builder.map.push(builder.pos, builder.pos + size, widget) if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { if (!widget) widget = builder.content.appendChild(document.createElement("span")) widget.setAttribute("cm-marker", marker.id) } if (widget) { builder.cm.display.input.setUneditable(widget) builder.content.appendChild(widget) } builder.pos += size builder.trailingSpace = false } // Outputs a number of spans to make up a line, taking highlighting // and marked text into account. function insertLineContent(line, builder, styles) { let spans = line.markedSpans, allText = line.text, at = 0 if (!spans) { for (let i = 1; i < styles.length; i+=2) builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)) return } let len = allText.length, pos = 0, i = 1, text = "", style, css let nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes for (;;) { if (nextChange == pos) { // Update current marker set spanStyle = spanEndStyle = spanStartStyle = css = "" attributes = null collapsed = null; nextChange = Infinity let foundBookmarks = [], endStyles for (let j = 0; j < spans.length; ++j) { let sp = spans[j], m = sp.marker if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { foundBookmarks.push(m) } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { if (sp.to != null && sp.to != pos && nextChange > sp.to) { nextChange = sp.to spanEndStyle = "" } if (m.className) spanStyle += " " + m.className if (m.css) css = (css ? css + ";" : "") + m.css if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle if (m.endStyle && sp.to == nextChange) (endStyles || (endStyles = [])).push(m.endStyle, sp.to) // support for the old title property // https://github.com/codemirror/CodeMirror/pull/5673 if (m.title) (attributes || (attributes = {})).title = m.title if (m.attributes) { for (let attr in m.attributes) (attributes || (attributes = {}))[attr] = m.attributes[attr] } if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) collapsed = sp } else if (sp.from > pos && nextChange > sp.from) { nextChange = sp.from } } if (endStyles) for (let j = 0; j < endStyles.length; j += 2) if (endStyles[j + 1] == nextChange) spanEndStyle += " " + endStyles[j] if (!collapsed || collapsed.from == pos) for (let j = 0; j < foundBookmarks.length; ++j) buildCollapsedSpan(builder, 0, foundBookmarks[j]) if (collapsed && (collapsed.from || 0) == pos) { buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, collapsed.marker, collapsed.from == null) if (collapsed.to == null) return if (collapsed.to == pos) collapsed = false } } if (pos >= len) break let upto = Math.min(len, nextChange) while (true) { if (text) { let end = pos + text.length if (!collapsed) { let tokenText = end > upto ? text.slice(0, upto - pos) : text builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes) } if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} pos = end spanStartStyle = "" } text = allText.slice(at, at = styles[i++]) style = interpretTokenStyle(styles[i++], builder.cm.options) } } } // These objects are used to represent the visible (currently drawn) // part of the document. A LineView may correspond to multiple // logical lines, if those are connected by collapsed ranges. export function LineView(doc, line, lineN) { // The starting line this.line = line // Continuing lines, if any this.rest = visualLineContinued(line) // Number of logical lines in this visual line this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1 this.node = this.text = null this.hidden = lineIsHidden(doc, line) } // Create a range of LineView objects for the given lines. export function buildViewArray(cm, from, to) { let array = [], nextPos for (let pos = from; pos < to; pos = nextPos) { let view = new LineView(cm.doc, getLine(cm.doc, pos), pos) nextPos = pos + view.size array.push(view) } return array } ================================================ FILE: third_party/CodeMirror/src/line/pos.js ================================================ import { getLine } from "./utils_line.js" // A Pos instance represents a position within the text. export function Pos(line, ch, sticky = null) { if (!(this instanceof Pos)) return new Pos(line, ch, sticky) this.line = line this.ch = ch this.sticky = sticky } // Compare two positions, return 0 if they are the same, a negative // number when a is less, and a positive number otherwise. export function cmp(a, b) { return a.line - b.line || a.ch - b.ch } export function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } export function copyPos(x) {return Pos(x.line, x.ch)} export function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } export function minPos(a, b) { return cmp(a, b) < 0 ? a : b } // Most of the external API clips given positions to make sure they // actually exist within the document. export function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} export function clipPos(doc, pos) { if (pos.line < doc.first) return Pos(doc.first, 0) let last = doc.first + doc.size - 1 if (pos.line > last) return Pos(last, getLine(doc, last).text.length) return clipToLen(pos, getLine(doc, pos.line).text.length) } function clipToLen(pos, linelen) { let ch = pos.ch if (ch == null || ch > linelen) return Pos(pos.line, linelen) else if (ch < 0) return Pos(pos.line, 0) else return pos } export function clipPosArray(doc, array) { let out = [] for (let i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]) return out } ================================================ FILE: third_party/CodeMirror/src/line/saw_special_spans.js ================================================ // Optimize some code when these features are not used. export let sawReadOnlySpans = false, sawCollapsedSpans = false export function seeReadOnlySpans() { sawReadOnlySpans = true } export function seeCollapsedSpans() { sawCollapsedSpans = true } ================================================ FILE: third_party/CodeMirror/src/line/spans.js ================================================ import { indexOf, lst } from "../util/misc.js" import { cmp } from "./pos.js" import { sawCollapsedSpans } from "./saw_special_spans.js" import { getLine, isLine, lineNo } from "./utils_line.js" // TEXTMARKER SPANS export function MarkedSpan(marker, from, to) { this.marker = marker this.from = from; this.to = to } // Search an array of spans for a span matching the given marker. export function getMarkedSpanFor(spans, marker) { if (spans) for (let i = 0; i < spans.length; ++i) { let span = spans[i] if (span.marker == marker) return span } } // Remove a span from an array, returning undefined if no spans are // left (we don't store arrays for lines without spans). export function removeMarkedSpan(spans, span) { let r for (let i = 0; i < spans.length; ++i) if (spans[i] != span) (r || (r = [])).push(spans[i]) return r } // Add a span to a line. export function addMarkedSpan(line, span) { line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span] span.marker.attachLine(line) } // Used for the algorithm that adjusts markers for a change in the // document. These functions cut an array of spans at a given // character position, returning an array of remaining chunks (or // undefined if nothing remains). function markedSpansBefore(old, startCh, isInsert) { let nw if (old) for (let i = 0; i < old.length; ++i) { let span = old[i], marker = span.marker let startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh) if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { let endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)) } } return nw } function markedSpansAfter(old, endCh, isInsert) { let nw if (old) for (let i = 0; i < old.length; ++i) { let span = old[i], marker = span.marker let endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh) if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { let startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, span.to == null ? null : span.to - endCh)) } } return nw } // Given a change object, compute the new set of marker spans that // cover the line in which the change took place. Removes spans // entirely within the change, reconnects spans belonging to the // same marker that appear on both sides of the change, and cuts off // spans partially within the change. Returns an array of span // arrays with one element for each line in (after) the change. export function stretchSpansOverChange(doc, change) { if (change.full) return null let oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans let oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans if (!oldFirst && !oldLast) return null let startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0 // Get the spans that 'stick out' on both sides let first = markedSpansBefore(oldFirst, startCh, isInsert) let last = markedSpansAfter(oldLast, endCh, isInsert) // Next, merge those two ends let sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0) if (first) { // Fix up .to properties of first for (let i = 0; i < first.length; ++i) { let span = first[i] if (span.to == null) { let found = getMarkedSpanFor(last, span.marker) if (!found) span.to = startCh else if (sameLine) span.to = found.to == null ? null : found.to + offset } } } if (last) { // Fix up .from in last (or move them into first in case of sameLine) for (let i = 0; i < last.length; ++i) { let span = last[i] if (span.to != null) span.to += offset if (span.from == null) { let found = getMarkedSpanFor(first, span.marker) if (!found) { span.from = offset if (sameLine) (first || (first = [])).push(span) } } else { span.from += offset if (sameLine) (first || (first = [])).push(span) } } } // Make sure we didn't create any zero-length spans if (first) first = clearEmptySpans(first) if (last && last != first) last = clearEmptySpans(last) let newMarkers = [first] if (!sameLine) { // Fill gap with whole-line-spans let gap = change.text.length - 2, gapMarkers if (gap > 0 && first) for (let i = 0; i < first.length; ++i) if (first[i].to == null) (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)) for (let i = 0; i < gap; ++i) newMarkers.push(gapMarkers) newMarkers.push(last) } return newMarkers } // Remove spans that are empty and don't have a clearWhenEmpty // option of false. function clearEmptySpans(spans) { for (let i = 0; i < spans.length; ++i) { let span = spans[i] if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) spans.splice(i--, 1) } if (!spans.length) return null return spans } // Used to 'clip' out readOnly ranges when making a change. export function removeReadOnlyRanges(doc, from, to) { let markers = null doc.iter(from.line, to.line + 1, line => { if (line.markedSpans) for (let i = 0; i < line.markedSpans.length; ++i) { let mark = line.markedSpans[i].marker if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) (markers || (markers = [])).push(mark) } }) if (!markers) return null let parts = [{from: from, to: to}] for (let i = 0; i < markers.length; ++i) { let mk = markers[i], m = mk.find(0) for (let j = 0; j < parts.length; ++j) { let p = parts[j] if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue let newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to) if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) newParts.push({from: p.from, to: m.from}) if (dto > 0 || !mk.inclusiveRight && !dto) newParts.push({from: m.to, to: p.to}) parts.splice.apply(parts, newParts) j += newParts.length - 3 } } return parts } // Connect or disconnect spans from a line. export function detachMarkedSpans(line) { let spans = line.markedSpans if (!spans) return for (let i = 0; i < spans.length; ++i) spans[i].marker.detachLine(line) line.markedSpans = null } export function attachMarkedSpans(line, spans) { if (!spans) return for (let i = 0; i < spans.length; ++i) spans[i].marker.attachLine(line) line.markedSpans = spans } // Helpers used when computing which overlapping collapsed span // counts as the larger one. function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } // Returns a number indicating which of two overlapping collapsed // spans is larger (and thus includes the other). Falls back to // comparing ids when the spans cover exactly the same range. export function compareCollapsedMarkers(a, b) { let lenDiff = a.lines.length - b.lines.length if (lenDiff != 0) return lenDiff let aPos = a.find(), bPos = b.find() let fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b) if (fromCmp) return -fromCmp let toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b) if (toCmp) return toCmp return b.id - a.id } // Find out whether a line ends or starts in a collapsed span. If // so, return the marker for that span. function collapsedSpanAtSide(line, start) { let sps = sawCollapsedSpans && line.markedSpans, found if (sps) for (let sp, i = 0; i < sps.length; ++i) { sp = sps[i] if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) found = sp.marker } return found } export function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } export function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } export function collapsedSpanAround(line, ch) { let sps = sawCollapsedSpans && line.markedSpans, found if (sps) for (let i = 0; i < sps.length; ++i) { let sp = sps[i] if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && (!found || compareCollapsedMarkers(found, sp.marker) < 0)) found = sp.marker } return found } // Test whether there exists a collapsed span that partially // overlaps (covers the start or end, but not both) of a new span. // Such overlap is not allowed. export function conflictingCollapsedRange(doc, lineNo, from, to, marker) { let line = getLine(doc, lineNo) let sps = sawCollapsedSpans && line.markedSpans if (sps) for (let i = 0; i < sps.length; ++i) { let sp = sps[i] if (!sp.marker.collapsed) continue let found = sp.marker.find(0) let fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker) let toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker) if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) return true } } // A visual line is a line as drawn on the screen. Folding, for // example, can cause multiple logical lines to appear on the same // visual line. This finds the start of the visual line that the // given line is part of (usually that is the line itself). export function visualLine(line) { let merged while (merged = collapsedSpanAtStart(line)) line = merged.find(-1, true).line return line } export function visualLineEnd(line) { let merged while (merged = collapsedSpanAtEnd(line)) line = merged.find(1, true).line return line } // Returns an array of logical lines that continue the visual line // started by the argument, or undefined if there are no such lines. export function visualLineContinued(line) { let merged, lines while (merged = collapsedSpanAtEnd(line)) { line = merged.find(1, true).line ;(lines || (lines = [])).push(line) } return lines } // Get the line number of the start of the visual line that the // given line number is part of. export function visualLineNo(doc, lineN) { let line = getLine(doc, lineN), vis = visualLine(line) if (line == vis) return lineN return lineNo(vis) } // Get the line number of the start of the next visual line after // the given line. export function visualLineEndNo(doc, lineN) { if (lineN > doc.lastLine()) return lineN let line = getLine(doc, lineN), merged if (!lineIsHidden(doc, line)) return lineN while (merged = collapsedSpanAtEnd(line)) line = merged.find(1, true).line return lineNo(line) + 1 } // Compute whether a line is hidden. Lines count as hidden when they // are part of a visual line that starts with another line, or when // they are entirely covered by collapsed, non-widget span. export function lineIsHidden(doc, line) { let sps = sawCollapsedSpans && line.markedSpans if (sps) for (let sp, i = 0; i < sps.length; ++i) { sp = sps[i] if (!sp.marker.collapsed) continue if (sp.from == null) return true if (sp.marker.widgetNode) continue if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) return true } } function lineIsHiddenInner(doc, line, span) { if (span.to == null) { let end = span.marker.find(1, true) return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) } if (span.marker.inclusiveRight && span.to == line.text.length) return true for (let sp, i = 0; i < line.markedSpans.length; ++i) { sp = line.markedSpans[i] if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && (sp.to == null || sp.to != span.from) && (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && lineIsHiddenInner(doc, line, sp)) return true } } // Find the height above the given line. export function heightAtLine(lineObj) { lineObj = visualLine(lineObj) let h = 0, chunk = lineObj.parent for (let i = 0; i < chunk.lines.length; ++i) { let line = chunk.lines[i] if (line == lineObj) break else h += line.height } for (let p = chunk.parent; p; chunk = p, p = chunk.parent) { for (let i = 0; i < p.children.length; ++i) { let cur = p.children[i] if (cur == chunk) break else h += cur.height } } return h } // Compute the character length of a line, taking into account // collapsed ranges (see markText) that might hide parts, and join // other lines onto it. export function lineLength(line) { if (line.height == 0) return 0 let len = line.text.length, merged, cur = line while (merged = collapsedSpanAtStart(cur)) { let found = merged.find(0, true) cur = found.from.line len += found.from.ch - found.to.ch } cur = line while (merged = collapsedSpanAtEnd(cur)) { let found = merged.find(0, true) len -= cur.text.length - found.from.ch cur = found.to.line len += cur.text.length - found.to.ch } return len } // Find the longest line in the document. export function findMaxLine(cm) { let d = cm.display, doc = cm.doc d.maxLine = getLine(doc, doc.first) d.maxLineLength = lineLength(d.maxLine) d.maxLineChanged = true doc.iter(line => { let len = lineLength(line) if (len > d.maxLineLength) { d.maxLineLength = len d.maxLine = line } }) } ================================================ FILE: third_party/CodeMirror/src/line/utils_line.js ================================================ import { indexOf } from "../util/misc.js" // Find the line object corresponding to the given line number. export function getLine(doc, n) { n -= doc.first if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document.") let chunk = doc while (!chunk.lines) { for (let i = 0;; ++i) { let child = chunk.children[i], sz = child.chunkSize() if (n < sz) { chunk = child; break } n -= sz } } return chunk.lines[n] } // Get the part of a document between two positions, as an array of // strings. export function getBetween(doc, start, end) { let out = [], n = start.line doc.iter(start.line, end.line + 1, line => { let text = line.text if (n == end.line) text = text.slice(0, end.ch) if (n == start.line) text = text.slice(start.ch) out.push(text) ++n }) return out } // Get the lines between from and to, as array of strings. export function getLines(doc, from, to) { let out = [] doc.iter(from, to, line => { out.push(line.text) }) // iter aborts when callback returns truthy value return out } // Update the height of a line, propagating the height change // upwards to parent nodes. export function updateLineHeight(line, height) { let diff = height - line.height if (diff) for (let n = line; n; n = n.parent) n.height += diff } // Given a line object, find its line number by walking up through // its parent links. export function lineNo(line) { if (line.parent == null) return null let cur = line.parent, no = indexOf(cur.lines, line) for (let chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { for (let i = 0;; ++i) { if (chunk.children[i] == cur) break no += chunk.children[i].chunkSize() } } return no + cur.first } // Find the line at the given vertical position, using the height // information in the document tree. export function lineAtHeight(chunk, h) { let n = chunk.first outer: do { for (let i = 0; i < chunk.children.length; ++i) { let child = chunk.children[i], ch = child.height if (h < ch) { chunk = child; continue outer } h -= ch n += child.chunkSize() } return n } while (!chunk.lines) let i = 0 for (; i < chunk.lines.length; ++i) { let line = chunk.lines[i], lh = line.height if (h < lh) break h -= lh } return n + i } export function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} export function lineNumberFor(options, i) { return String(options.lineNumberFormatter(i + options.firstLineNumber)) } ================================================ FILE: third_party/CodeMirror/src/measurement/position_measurement.js ================================================ import { buildLineContent, LineView } from "../line/line_data.js" import { clipPos, Pos } from "../line/pos.js" import { collapsedSpanAround, heightAtLine, lineIsHidden, visualLine } from "../line/spans.js" import { getLine, lineAtHeight, lineNo, updateLineHeight } from "../line/utils_line.js" import { bidiOther, getBidiPartAt, getOrder } from "../util/bidi.js" import { chrome, android, ie, ie_version } from "../util/browser.js" import { elt, removeChildren, range, removeChildrenAndAdd } from "../util/dom.js" import { e_target } from "../util/event.js" import { hasBadZoomedRects } from "../util/feature_detection.js" import { countColumn, findFirst, isExtendingChar, scrollerGap, skipExtendingChars } from "../util/misc.js" import { updateLineForChanges } from "../display/update_line.js" import { widgetHeight } from "./widgets.js" // POSITION MEASUREMENT export function paddingTop(display) {return display.lineSpace.offsetTop} export function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} export function paddingH(display) { if (display.cachedPaddingH) return display.cachedPaddingH let e = removeChildrenAndAdd(display.measure, elt("pre", "x")) let style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle let data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)} if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data return data } export function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } export function displayWidth(cm) { return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth } export function displayHeight(cm) { return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight } // Ensure the lineView.wrapping.heights array is populated. This is // an array of bottom offsets for the lines that make up a drawn // line. When lineWrapping is on, there might be more than one // height. function ensureLineHeights(cm, lineView, rect) { let wrapping = cm.options.lineWrapping let curWidth = wrapping && displayWidth(cm) if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { let heights = lineView.measure.heights = [] if (wrapping) { lineView.measure.width = curWidth let rects = lineView.text.firstChild.getClientRects() for (let i = 0; i < rects.length - 1; i++) { let cur = rects[i], next = rects[i + 1] if (Math.abs(cur.bottom - next.bottom) > 2) heights.push((cur.bottom + next.top) / 2 - rect.top) } } heights.push(rect.bottom - rect.top) } } // Find a line map (mapping character offsets to text nodes) and a // measurement cache for the given line number. (A line view might // contain multiple lines when collapsed ranges are present.) export function mapFromLineView(lineView, line, lineN) { if (lineView.line == line) return {map: lineView.measure.map, cache: lineView.measure.cache} for (let i = 0; i < lineView.rest.length; i++) if (lineView.rest[i] == line) return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} for (let i = 0; i < lineView.rest.length; i++) if (lineNo(lineView.rest[i]) > lineN) return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true} } // Render a line into the hidden node display.externalMeasured. Used // when measurement is needed for a line that's not in the viewport. function updateExternalMeasurement(cm, line) { line = visualLine(line) let lineN = lineNo(line) let view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN) view.lineN = lineN let built = view.built = buildLineContent(cm, view) view.text = built.pre removeChildrenAndAdd(cm.display.lineMeasure, built.pre) return view } // Get a {top, bottom, left, right} box (in line-local coordinates) // for a given character. export function measureChar(cm, line, ch, bias) { return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) } // Find a line view that corresponds to the given line number. export function findViewForLine(cm, lineN) { if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) return cm.display.view[findViewIndex(cm, lineN)] let ext = cm.display.externalMeasured if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) return ext } // Measurement can be split in two steps, the set-up work that // applies to the whole line, and the measurement of the actual // character. Functions like coordsChar, that need to do a lot of // measurements in a row, can thus ensure that the set-up work is // only done once. export function prepareMeasureForLine(cm, line) { let lineN = lineNo(line) let view = findViewForLine(cm, lineN) if (view && !view.text) { view = null } else if (view && view.changes) { updateLineForChanges(cm, view, lineN, getDimensions(cm)) cm.curOp.forceUpdate = true } if (!view) view = updateExternalMeasurement(cm, line) let info = mapFromLineView(view, line, lineN) return { line: line, view: view, rect: null, map: info.map, cache: info.cache, before: info.before, hasHeights: false } } // Given a prepared measurement object, measures the position of an // actual character (or fetches it from the cache). export function measureCharPrepared(cm, prepared, ch, bias, varHeight) { if (prepared.before) ch = -1 let key = ch + (bias || ""), found if (prepared.cache.hasOwnProperty(key)) { found = prepared.cache[key] } else { if (!prepared.rect) prepared.rect = prepared.view.text.getBoundingClientRect() if (!prepared.hasHeights) { ensureLineHeights(cm, prepared.view, prepared.rect) prepared.hasHeights = true } found = measureCharInner(cm, prepared, ch, bias) if (!found.bogus) prepared.cache[key] = found } return {left: found.left, right: found.right, top: varHeight ? found.rtop : found.top, bottom: varHeight ? found.rbottom : found.bottom} } let nullRect = {left: 0, right: 0, top: 0, bottom: 0} export function nodeAndOffsetInLineMap(map, ch, bias) { let node, start, end, collapse, mStart, mEnd // First, search the line map for the text node corresponding to, // or closest to, the target character. for (let i = 0; i < map.length; i += 3) { mStart = map[i] mEnd = map[i + 1] if (ch < mStart) { start = 0; end = 1 collapse = "left" } else if (ch < mEnd) { start = ch - mStart end = start + 1 } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { end = mEnd - mStart start = end - 1 if (ch >= mEnd) collapse = "right" } if (start != null) { node = map[i + 2] if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) collapse = bias if (bias == "left" && start == 0) while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { node = map[(i -= 3) + 2] collapse = "left" } if (bias == "right" && start == mEnd - mStart) while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { node = map[(i += 3) + 2] collapse = "right" } break } } return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} } function getUsefulRect(rects, bias) { let rect = nullRect if (bias == "left") for (let i = 0; i < rects.length; i++) { if ((rect = rects[i]).left != rect.right) break } else for (let i = rects.length - 1; i >= 0; i--) { if ((rect = rects[i]).left != rect.right) break } return rect } function measureCharInner(cm, prepared, ch, bias) { let place = nodeAndOffsetInLineMap(prepared.map, ch, bias) let node = place.node, start = place.start, end = place.end, collapse = place.collapse let rect if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. for (let i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) rect = node.parentNode.getBoundingClientRect() else rect = getUsefulRect(range(node, start, end).getClientRects(), bias) if (rect.left || rect.right || start == 0) break end = start start = start - 1 collapse = "right" } if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect) } else { // If it is a widget, simply get the box for the whole widget. if (start > 0) collapse = bias = "right" let rects if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) rect = rects[bias == "right" ? rects.length - 1 : 0] else rect = node.getBoundingClientRect() } if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { let rSpan = node.parentNode.getClientRects()[0] if (rSpan) rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom} else rect = nullRect } let rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top let mid = (rtop + rbot) / 2 let heights = prepared.view.measure.heights let i = 0 for (; i < heights.length - 1; i++) if (mid < heights[i]) break let top = i ? heights[i - 1] : 0, bot = heights[i] let result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, top: top, bottom: bot} if (!rect.left && !rect.right) result.bogus = true if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot } return result } // Work around problem with bounding client rects on ranges being // returned incorrectly when zoomed on IE10 and below. function maybeUpdateRectForZooming(measure, rect) { if (!window.screen || screen.logicalXDPI == null || screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) return rect let scaleX = screen.logicalXDPI / screen.deviceXDPI let scaleY = screen.logicalYDPI / screen.deviceYDPI return {left: rect.left * scaleX, right: rect.right * scaleX, top: rect.top * scaleY, bottom: rect.bottom * scaleY} } export function clearLineMeasurementCacheFor(lineView) { if (lineView.measure) { lineView.measure.cache = {} lineView.measure.heights = null if (lineView.rest) for (let i = 0; i < lineView.rest.length; i++) lineView.measure.caches[i] = {} } } export function clearLineMeasurementCache(cm) { cm.display.externalMeasure = null removeChildren(cm.display.lineMeasure) for (let i = 0; i < cm.display.view.length; i++) clearLineMeasurementCacheFor(cm.display.view[i]) } export function clearCaches(cm) { clearLineMeasurementCache(cm) cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null if (!cm.options.lineWrapping) cm.display.maxLineChanged = true cm.display.lineNumChars = null } function pageScrollX() { // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 // which causes page_Offset and bounding client rects to use // different reference viewports and invalidate our calculations. if (chrome && android) return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) return window.pageXOffset || (document.documentElement || document.body).scrollLeft } function pageScrollY() { if (chrome && android) return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) return window.pageYOffset || (document.documentElement || document.body).scrollTop } function widgetTopHeight(lineObj) { let height = 0 if (lineObj.widgets) for (let i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) height += widgetHeight(lineObj.widgets[i]) return height } // Converts a {top, bottom, left, right} box from line-local // coordinates into another coordinate system. Context may be one of // "line", "div" (display.lineDiv), "local"./null (editor), "window", // or "page". export function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { if (!includeWidgets) { let height = widgetTopHeight(lineObj) rect.top += height; rect.bottom += height } if (context == "line") return rect if (!context) context = "local" let yOff = heightAtLine(lineObj) if (context == "local") yOff += paddingTop(cm.display) else yOff -= cm.display.viewOffset if (context == "page" || context == "window") { let lOff = cm.display.lineSpace.getBoundingClientRect() yOff += lOff.top + (context == "window" ? 0 : pageScrollY()) let xOff = lOff.left + (context == "window" ? 0 : pageScrollX()) rect.left += xOff; rect.right += xOff } rect.top += yOff; rect.bottom += yOff return rect } // Coverts a box from "div" coords to another coordinate system. // Context may be "window", "page", "div", or "local"./null. export function fromCoordSystem(cm, coords, context) { if (context == "div") return coords let left = coords.left, top = coords.top // First move into "page" coordinate system if (context == "page") { left -= pageScrollX() top -= pageScrollY() } else if (context == "local" || !context) { let localBox = cm.display.sizer.getBoundingClientRect() left += localBox.left top += localBox.top } let lineSpaceBox = cm.display.lineSpace.getBoundingClientRect() return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} } export function charCoords(cm, pos, context, lineObj, bias) { if (!lineObj) lineObj = getLine(cm.doc, pos.line) return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) } // Returns a box for a given cursor position, which may have an // 'other' property containing the position of the secondary cursor // on a bidi boundary. // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` // and after `char - 1` in writing order of `char - 1` // A cursor Pos(line, char, "after") is on the same visual line as `char` // and before `char` in writing order of `char` // Examples (upper-case letters are RTL, lower-case are LTR): // Pos(0, 1, ...) // before after // ab a|b a|b // aB a|B aB| // Ab |Ab A|b // AB B|A B|A // Every position after the last character on a line is considered to stick // to the last character on the line. export function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { lineObj = lineObj || getLine(cm.doc, pos.line) if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj) function get(ch, right) { let m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight) if (right) m.left = m.right; else m.right = m.left return intoCoordSystem(cm, lineObj, m, context) } let order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky if (ch >= lineObj.text.length) { ch = lineObj.text.length sticky = "before" } else if (ch <= 0) { ch = 0 sticky = "after" } if (!order) return get(sticky == "before" ? ch - 1 : ch, sticky == "before") function getBidi(ch, partPos, invert) { let part = order[partPos], right = part.level == 1 return get(invert ? ch - 1 : ch, right != invert) } let partPos = getBidiPartAt(order, ch, sticky) let other = bidiOther let val = getBidi(ch, partPos, sticky == "before") if (other != null) val.other = getBidi(ch, other, sticky != "before") return val } // Used to cheaply estimate the coordinates for a position. Used for // intermediate scroll updates. export function estimateCoords(cm, pos) { let left = 0 pos = clipPos(cm.doc, pos) if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch let lineObj = getLine(cm.doc, pos.line) let top = heightAtLine(lineObj) + paddingTop(cm.display) return {left: left, right: left, top: top, bottom: top + lineObj.height} } // Positions returned by coordsChar contain some extra information. // xRel is the relative x position of the input coordinates compared // to the found position (so xRel > 0 means the coordinates are to // the right of the character position, for example). When outside // is true, that means the coordinates lie outside the line's // vertical range. function PosWithInfo(line, ch, sticky, outside, xRel) { let pos = Pos(line, ch, sticky) pos.xRel = xRel if (outside) pos.outside = true return pos } // Compute the character position closest to the given coordinates. // Input must be lineSpace-local ("div" coordinate system). export function coordsChar(cm, x, y) { let doc = cm.doc y += cm.display.viewOffset if (y < 0) return PosWithInfo(doc.first, 0, null, true, -1) let lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1 if (lineN > last) return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) if (x < 0) x = 0 let lineObj = getLine(doc, lineN) for (;;) { let found = coordsCharInner(cm, lineObj, lineN, x, y) let collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0)) if (!collapsed) return found let rangeEnd = collapsed.find(1) if (rangeEnd.line == lineN) return rangeEnd lineObj = getLine(doc, lineN = rangeEnd.line) } } function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { y -= widgetTopHeight(lineObj) let end = lineObj.text.length let begin = findFirst(ch => measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y, end, 0) end = findFirst(ch => measureCharPrepared(cm, preparedMeasure, ch).top > y, begin, end) return {begin, end} } export function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj) let targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) } // Returns true if the given side of a box is after the given // coordinates, in top-to-bottom, left-to-right order. function boxIsAfter(box, x, y, left) { return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x } function coordsCharInner(cm, lineObj, lineNo, x, y) { // Move y into line-local coordinate space y -= heightAtLine(lineObj) let preparedMeasure = prepareMeasureForLine(cm, lineObj) // When directly calling `measureCharPrepared`, we have to adjust // for the widgets at this line. let widgetHeight = widgetTopHeight(lineObj) let begin = 0, end = lineObj.text.length, ltr = true let order = getOrder(lineObj, cm.doc.direction) // If the line isn't plain left-to-right text, first figure out // which bidi section the coordinates fall into. if (order) { let part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) (cm, lineObj, lineNo, preparedMeasure, order, x, y) ltr = part.level != 1 // The awkward -1 offsets are needed because findFirst (called // on these below) will treat its first bound as inclusive, // second as exclusive, but we want to actually address the // characters in the part's range begin = ltr ? part.from : part.to - 1 end = ltr ? part.to : part.from - 1 } // A binary search to find the first character whose bounding box // starts after the coordinates. If we run across any whose box wrap // the coordinates, store that. let chAround = null, boxAround = null let ch = findFirst(ch => { let box = measureCharPrepared(cm, preparedMeasure, ch) box.top += widgetHeight; box.bottom += widgetHeight if (!boxIsAfter(box, x, y, false)) return false if (box.top <= y && box.left <= x) { chAround = ch boxAround = box } return true }, begin, end) let baseX, sticky, outside = false // If a box around the coordinates was found, use that if (boxAround) { // Distinguish coordinates nearer to the left or right side of the box let atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr ch = chAround + (atStart ? 0 : 1) sticky = atStart ? "after" : "before" baseX = atLeft ? boxAround.left : boxAround.right } else { // (Adjust for extended bound, if necessary.) if (!ltr && (ch == end || ch == begin)) ch++ // To determine which side to associate with, get the box to the // left of the character and compare it's vertical position to the // coordinates sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ? "after" : "before" // Now get accurate coordinates for this place, in order to get a // base X position let coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure) baseX = coords.left outside = y < coords.top || y >= coords.bottom } ch = skipExtendingChars(lineObj.text, ch, 1) return PosWithInfo(lineNo, ch, sticky, outside, x - baseX) } function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) { // Bidi parts are sorted left-to-right, and in a non-line-wrapping // situation, we can take this ordering to correspond to the visual // ordering. This finds the first part whose end is after the given // coordinates. let index = findFirst(i => { let part = order[i], ltr = part.level != 1 return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"), "line", lineObj, preparedMeasure), x, y, true) }, 0, order.length - 1) let part = order[index] // If this isn't the first part, the part's start is also after // the coordinates, and the coordinates aren't on the same line as // that start, move one part back. if (index > 0) { let ltr = part.level != 1 let start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"), "line", lineObj, preparedMeasure) if (boxIsAfter(start, x, y, true) && start.top > y) part = order[index - 1] } return part } function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { // In a wrapped line, rtl text on wrapping boundaries can do things // that don't correspond to the ordering in our `order` array at // all, so a binary search doesn't work, and we want to return a // part that only spans one line so that the binary search in // coordsCharInner is safe. As such, we first find the extent of the // wrapped line, and then do a flat search in which we discard any // spans that aren't on the line. let {begin, end} = wrappedLineExtent(cm, lineObj, preparedMeasure, y) if (/\s/.test(lineObj.text.charAt(end - 1))) end-- let part = null, closestDist = null for (let i = 0; i < order.length; i++) { let p = order[i] if (p.from >= end || p.to <= begin) continue let ltr = p.level != 1 let endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right // Weigh against spans ending before this, so that they are only // picked if nothing ends after let dist = endX < x ? x - endX + 1e9 : endX - x if (!part || closestDist > dist) { part = p closestDist = dist } } if (!part) part = order[order.length - 1] // Clip the part to the wrapped line. if (part.from < begin) part = {from: begin, to: part.to, level: part.level} if (part.to > end) part = {from: part.from, to: end, level: part.level} return part } let measureText // Compute the default text height. export function textHeight(display) { if (display.cachedTextHeight != null) return display.cachedTextHeight if (measureText == null) { measureText = elt("pre") // Measure a bunch of lines, for browsers that compute // fractional heights. for (let i = 0; i < 49; ++i) { measureText.appendChild(document.createTextNode("x")) measureText.appendChild(elt("br")) } measureText.appendChild(document.createTextNode("x")) } removeChildrenAndAdd(display.measure, measureText) let height = measureText.offsetHeight / 50 if (height > 3) display.cachedTextHeight = height removeChildren(display.measure) return height || 1 } // Compute the default character width. export function charWidth(display) { if (display.cachedCharWidth != null) return display.cachedCharWidth let anchor = elt("span", "xxxxxxxxxx") let pre = elt("pre", [anchor]) removeChildrenAndAdd(display.measure, pre) let rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10 if (width > 2) display.cachedCharWidth = width return width || 10 } // Do a bulk-read of the DOM positions and sizes needed to draw the // view, so that we don't interleave reading and writing to the DOM. export function getDimensions(cm) { let d = cm.display, left = {}, width = {} let gutterLeft = d.gutters.clientLeft for (let n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft width[cm.options.gutters[i]] = n.clientWidth } return {fixedPos: compensateForHScroll(d), gutterTotalWidth: d.gutters.offsetWidth, gutterLeft: left, gutterWidth: width, wrapperWidth: d.wrapper.clientWidth} } // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, // but using getBoundingClientRect to get a sub-pixel-accurate // result. export function compensateForHScroll(display) { return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left } // Returns a function that estimates the height of a line, to use as // first approximation until the line becomes visible (and is thus // properly measurable). export function estimateHeight(cm) { let th = textHeight(cm.display), wrapping = cm.options.lineWrapping let perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3) return line => { if (lineIsHidden(cm.doc, line)) return 0 let widgetsHeight = 0 if (line.widgets) for (let i = 0; i < line.widgets.length; i++) { if (line.widgets[i].height) widgetsHeight += line.widgets[i].height } if (wrapping) return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th else return widgetsHeight + th } } export function estimateLineHeights(cm) { let doc = cm.doc, est = estimateHeight(cm) doc.iter(line => { let estHeight = est(line) if (estHeight != line.height) updateLineHeight(line, estHeight) }) } // Given a mouse event, find the corresponding position. If liberal // is false, it checks whether a gutter or scrollbar was clicked, // and returns null if it was. forRect is used by rectangular // selections, and tries to estimate a character position even for // coordinates beyond the right of the text. export function posFromMouse(cm, e, liberal, forRect) { let display = cm.display if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null let x, y, space = display.lineSpace.getBoundingClientRect() // Fails unpredictably on IE[67] when mouse is dragged around quickly. try { x = e.clientX - space.left; y = e.clientY - space.top } catch (e) { return null } let coords = coordsChar(cm, x, y), line if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { let colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)) } return coords } // Find the view element corresponding to a given line. Return null // when the line isn't visible. export function findViewIndex(cm, n) { if (n >= cm.display.viewTo) return null n -= cm.display.viewFrom if (n < 0) return null let view = cm.display.view for (let i = 0; i < view.length; i++) { n -= view[i].size if (n < 0) return i } } ================================================ FILE: third_party/CodeMirror/src/measurement/widgets.js ================================================ import { contains, elt, removeChildrenAndAdd } from "../util/dom.js" import { e_target } from "../util/event.js" export function widgetHeight(widget) { if (widget.height != null) return widget.height let cm = widget.doc.cm if (!cm) return 0 if (!contains(document.body, widget.node)) { let parentStyle = "position: relative;" if (widget.coverGutter) parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;" if (widget.noHScroll) parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;" removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)) } return widget.height = widget.node.parentNode.offsetHeight } // Return true when the given mouse event happened in a widget export function eventInWidget(display, e) { for (let n = e_target(e); n != display.wrapper; n = n.parentNode) { if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || (n.parentNode == display.sizer && n != display.mover)) return true } } ================================================ FILE: third_party/CodeMirror/src/model/Doc.js ================================================ import CodeMirror from "../edit/CodeMirror.js" import { docMethodOp } from "../display/operations.js" import { Line } from "../line/line_data.js" import { clipPos, clipPosArray, Pos } from "../line/pos.js" import { visualLine } from "../line/spans.js" import { getBetween, getLine, getLines, isLine, lineNo } from "../line/utils_line.js" import { classTest } from "../util/dom.js" import { splitLinesAuto } from "../util/feature_detection.js" import { createObj, map, isEmpty, sel_dontScroll } from "../util/misc.js" import { ensureCursorVisible, scrollToCoords } from "../display/scrolling.js" import { changeLine, makeChange, makeChangeFromHistory, replaceRange } from "./changes.js" import { computeReplacedSel } from "./change_measurement.js" import { BranchChunk, LeafChunk } from "./chunk.js" import { directionChanged, linkedDocs, updateDoc } from "./document_data.js" import { copyHistoryArray, History } from "./history.js" import { addLineWidget } from "./line_widget.js" import { copySharedMarkers, detachSharedMarkers, findSharedMarkers, markText } from "./mark_text.js" import { normalizeSelection, Range, simpleSelection } from "./selection.js" import { extendSelection, extendSelections, setSelection, setSelectionReplaceHistory, setSimpleSelection } from "./selection_updates.js" let nextDocId = 0 let Doc = function(text, mode, firstLine, lineSep, direction) { if (!(this instanceof Doc)) return new Doc(text, mode, firstLine, lineSep, direction) if (firstLine == null) firstLine = 0 BranchChunk.call(this, [new LeafChunk([new Line("", null)])]) this.first = firstLine this.scrollTop = this.scrollLeft = 0 this.cantEdit = false this.cleanGeneration = 1 this.modeFrontier = this.highlightFrontier = firstLine let start = Pos(firstLine, 0) this.sel = simpleSelection(start) this.history = new History(null) this.id = ++nextDocId this.modeOption = mode this.lineSep = lineSep this.direction = (direction == "rtl") ? "rtl" : "ltr" this.extend = false if (typeof text == "string") text = this.splitLines(text) updateDoc(this, {from: start, to: start, text: text}) setSelection(this, simpleSelection(start), sel_dontScroll) } Doc.prototype = createObj(BranchChunk.prototype, { constructor: Doc, // Iterate over the document. Supports two forms -- with only one // argument, it calls that for each line in the document. With // three, it iterates over the range given by the first two (with // the second being non-inclusive). iter: function(from, to, op) { if (op) this.iterN(from - this.first, to - from, op) else this.iterN(this.first, this.first + this.size, from) }, // Non-public interface for adding and removing lines. insert: function(at, lines) { let height = 0 for (let i = 0; i < lines.length; ++i) height += lines[i].height this.insertInner(at - this.first, lines, height) }, remove: function(at, n) { this.removeInner(at - this.first, n) }, // From here, the methods are part of the public interface. Most // are also available from CodeMirror (editor) instances. getValue: function(lineSep) { let lines = getLines(this, this.first, this.first + this.size) if (lineSep === false) return lines return lines.join(lineSep || this.lineSeparator()) }, setValue: docMethodOp(function(code) { let top = Pos(this.first, 0), last = this.first + this.size - 1 makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), text: this.splitLines(code), origin: "setValue", full: true}, true) if (this.cm) scrollToCoords(this.cm, 0, 0) setSelection(this, simpleSelection(top), sel_dontScroll) }), replaceRange: function(code, from, to, origin) { from = clipPos(this, from) to = to ? clipPos(this, to) : from replaceRange(this, code, from, to, origin) }, getRange: function(from, to, lineSep) { let lines = getBetween(this, clipPos(this, from), clipPos(this, to)) if (lineSep === false) return lines return lines.join(lineSep || this.lineSeparator()) }, getLine: function(line) {let l = this.getLineHandle(line); return l && l.text}, getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line)}, getLineNumber: function(line) {return lineNo(line)}, getLineHandleVisualStart: function(line) { if (typeof line == "number") line = getLine(this, line) return visualLine(line) }, lineCount: function() {return this.size}, firstLine: function() {return this.first}, lastLine: function() {return this.first + this.size - 1}, clipPos: function(pos) {return clipPos(this, pos)}, getCursor: function(start) { let range = this.sel.primary(), pos if (start == null || start == "head") pos = range.head else if (start == "anchor") pos = range.anchor else if (start == "end" || start == "to" || start === false) pos = range.to() else pos = range.from() return pos }, listSelections: function() { return this.sel.ranges }, somethingSelected: function() {return this.sel.somethingSelected()}, setCursor: docMethodOp(function(line, ch, options) { setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options) }), setSelection: docMethodOp(function(anchor, head, options) { setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options) }), extendSelection: docMethodOp(function(head, other, options) { extendSelection(this, clipPos(this, head), other && clipPos(this, other), options) }), extendSelections: docMethodOp(function(heads, options) { extendSelections(this, clipPosArray(this, heads), options) }), extendSelectionsBy: docMethodOp(function(f, options) { let heads = map(this.sel.ranges, f) extendSelections(this, clipPosArray(this, heads), options) }), setSelections: docMethodOp(function(ranges, primary, options) { if (!ranges.length) return let out = [] for (let i = 0; i < ranges.length; i++) out[i] = new Range(clipPos(this, ranges[i].anchor), clipPos(this, ranges[i].head)) if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex) setSelection(this, normalizeSelection(this.cm, out, primary), options) }), addSelection: docMethodOp(function(anchor, head, options) { let ranges = this.sel.ranges.slice(0) ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))) setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options) }), getSelection: function(lineSep) { let ranges = this.sel.ranges, lines for (let i = 0; i < ranges.length; i++) { let sel = getBetween(this, ranges[i].from(), ranges[i].to()) lines = lines ? lines.concat(sel) : sel } if (lineSep === false) return lines else return lines.join(lineSep || this.lineSeparator()) }, getSelections: function(lineSep) { let parts = [], ranges = this.sel.ranges for (let i = 0; i < ranges.length; i++) { let sel = getBetween(this, ranges[i].from(), ranges[i].to()) if (lineSep !== false) sel = sel.join(lineSep || this.lineSeparator()) parts[i] = sel } return parts }, replaceSelection: function(code, collapse, origin) { let dup = [] for (let i = 0; i < this.sel.ranges.length; i++) dup[i] = code this.replaceSelections(dup, collapse, origin || "+input") }, replaceSelections: docMethodOp(function(code, collapse, origin) { let changes = [], sel = this.sel for (let i = 0; i < sel.ranges.length; i++) { let range = sel.ranges[i] changes[i] = {from: range.from(), to: range.to(), text: this.splitLines(code[i]), origin: origin} } let newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse) for (let i = changes.length - 1; i >= 0; i--) makeChange(this, changes[i]) if (newSel) setSelectionReplaceHistory(this, newSel) else if (this.cm) ensureCursorVisible(this.cm) }), undo: docMethodOp(function() {makeChangeFromHistory(this, "undo")}), redo: docMethodOp(function() {makeChangeFromHistory(this, "redo")}), undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true)}), redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true)}), setExtending: function(val) {this.extend = val}, getExtending: function() {return this.extend}, historySize: function() { let hist = this.history, done = 0, undone = 0 for (let i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done for (let i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone return {undo: done, redo: undone} }, clearHistory: function() {this.history = new History(this.history.maxGeneration)}, markClean: function() { this.cleanGeneration = this.changeGeneration(true) }, changeGeneration: function(forceSplit) { if (forceSplit) this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null return this.history.generation }, isClean: function (gen) { return this.history.generation == (gen || this.cleanGeneration) }, getHistory: function() { return {done: copyHistoryArray(this.history.done), undone: copyHistoryArray(this.history.undone)} }, setHistory: function(histData) { let hist = this.history = new History(this.history.maxGeneration) hist.done = copyHistoryArray(histData.done.slice(0), null, true) hist.undone = copyHistoryArray(histData.undone.slice(0), null, true) }, setGutterMarker: docMethodOp(function(line, gutterID, value) { return changeLine(this, line, "gutter", line => { let markers = line.gutterMarkers || (line.gutterMarkers = {}) markers[gutterID] = value if (!value && isEmpty(markers)) line.gutterMarkers = null return true }) }), clearGutter: docMethodOp(function(gutterID) { this.iter(line => { if (line.gutterMarkers && line.gutterMarkers[gutterID]) { changeLine(this, line, "gutter", () => { line.gutterMarkers[gutterID] = null if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null return true }) } }) }), lineInfo: function(line) { let n if (typeof line == "number") { if (!isLine(this, line)) return null n = line line = getLine(this, line) if (!line) return null } else { n = lineNo(line) if (n == null) return null } return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, widgets: line.widgets} }, addLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", line => { let prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass" if (!line[prop]) line[prop] = cls else if (classTest(cls).test(line[prop])) return false else line[prop] += " " + cls return true }) }), removeLineClass: docMethodOp(function(handle, where, cls) { return changeLine(this, handle, where == "gutter" ? "gutter" : "class", line => { let prop = where == "text" ? "textClass" : where == "background" ? "bgClass" : where == "gutter" ? "gutterClass" : "wrapClass" let cur = line[prop] if (!cur) return false else if (cls == null) line[prop] = null else { let found = cur.match(classTest(cls)) if (!found) return false let end = found.index + found[0].length line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null } return true }) }), addLineWidget: docMethodOp(function(handle, node, options) { return addLineWidget(this, handle, node, options) }), removeLineWidget: function(widget) { widget.clear() }, markText: function(from, to, options) { return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") }, setBookmark: function(pos, options) { let realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), insertLeft: options && options.insertLeft, clearWhenEmpty: false, shared: options && options.shared, handleMouseEvents: options && options.handleMouseEvents} pos = clipPos(this, pos) return markText(this, pos, pos, realOpts, "bookmark") }, findMarksAt: function(pos) { pos = clipPos(this, pos) let markers = [], spans = getLine(this, pos.line).markedSpans if (spans) for (let i = 0; i < spans.length; ++i) { let span = spans[i] if ((span.from == null || span.from <= pos.ch) && (span.to == null || span.to >= pos.ch)) markers.push(span.marker.parent || span.marker) } return markers }, findMarks: function(from, to, filter) { from = clipPos(this, from); to = clipPos(this, to) let found = [], lineNo = from.line this.iter(from.line, to.line + 1, line => { let spans = line.markedSpans if (spans) for (let i = 0; i < spans.length; i++) { let span = spans[i] if (!(span.to != null && lineNo == from.line && from.ch >= span.to || span.from == null && lineNo != from.line || span.from != null && lineNo == to.line && span.from >= to.ch) && (!filter || filter(span.marker))) found.push(span.marker.parent || span.marker) } ++lineNo }) return found }, getAllMarks: function() { let markers = [] this.iter(line => { let sps = line.markedSpans if (sps) for (let i = 0; i < sps.length; ++i) if (sps[i].from != null) markers.push(sps[i].marker) }) return markers }, posFromIndex: function(off) { let ch, lineNo = this.first, sepSize = this.lineSeparator().length this.iter(line => { let sz = line.text.length + sepSize if (sz > off) { ch = off; return true } off -= sz ++lineNo }) return clipPos(this, Pos(lineNo, ch)) }, indexFromPos: function (coords) { coords = clipPos(this, coords) let index = coords.ch if (coords.line < this.first || coords.ch < 0) return 0 let sepSize = this.lineSeparator().length this.iter(this.first, coords.line, line => { // iter aborts when callback returns a truthy value index += line.text.length + sepSize }) return index }, copy: function(copyHistory) { let doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first, this.lineSep, this.direction) doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft doc.sel = this.sel doc.extend = false if (copyHistory) { doc.history.undoDepth = this.history.undoDepth doc.setHistory(this.getHistory()) } return doc }, linkedDoc: function(options) { if (!options) options = {} let from = this.first, to = this.first + this.size if (options.from != null && options.from > from) from = options.from if (options.to != null && options.to < to) to = options.to let copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction) if (options.sharedHist) copy.history = this.history ;(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}) copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}] copySharedMarkers(copy, findSharedMarkers(this)) return copy }, unlinkDoc: function(other) { if (other instanceof CodeMirror) other = other.doc if (this.linked) for (let i = 0; i < this.linked.length; ++i) { let link = this.linked[i] if (link.doc != other) continue this.linked.splice(i, 1) other.unlinkDoc(this) detachSharedMarkers(findSharedMarkers(this)) break } // If the histories were shared, split them again if (other.history == this.history) { let splitIds = [other.id] linkedDocs(other, doc => splitIds.push(doc.id), true) other.history = new History(null) other.history.done = copyHistoryArray(this.history.done, splitIds) other.history.undone = copyHistoryArray(this.history.undone, splitIds) } }, iterLinkedDocs: function(f) {linkedDocs(this, f)}, getMode: function() {return this.mode}, getEditor: function() {return this.cm}, splitLines: function(str) { if (this.lineSep) return str.split(this.lineSep) return splitLinesAuto(str) }, lineSeparator: function() { return this.lineSep || "\n" }, setDirection: docMethodOp(function (dir) { if (dir != "rtl") dir = "ltr" if (dir == this.direction) return this.direction = dir this.iter(line => line.order = null) if (this.cm) directionChanged(this.cm) }) }) // Public alias. Doc.prototype.eachLine = Doc.prototype.iter export default Doc ================================================ FILE: third_party/CodeMirror/src/model/change_measurement.js ================================================ import { cmp, Pos } from "../line/pos.js" import { lst } from "../util/misc.js" import { normalizeSelection, Range, Selection } from "./selection.js" // Compute the position of the end of a change (its 'to' property // refers to the pre-change end). export function changeEnd(change) { if (!change.text) return change.to return Pos(change.from.line + change.text.length - 1, lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) } // Adjust a position to refer to the post-change position of the // same text, or the end of the change if the change covers it. function adjustForChange(pos, change) { if (cmp(pos, change.from) < 0) return pos if (cmp(pos, change.to) <= 0) return changeEnd(change) let line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch return Pos(line, ch) } export function computeSelAfterChange(doc, change) { let out = [] for (let i = 0; i < doc.sel.ranges.length; i++) { let range = doc.sel.ranges[i] out.push(new Range(adjustForChange(range.anchor, change), adjustForChange(range.head, change))) } return normalizeSelection(doc.cm, out, doc.sel.primIndex) } function offsetPos(pos, old, nw) { if (pos.line == old.line) return Pos(nw.line, pos.ch - old.ch + nw.ch) else return Pos(nw.line + (pos.line - old.line), pos.ch) } // Used by replaceSelections to allow moving the selection to the // start or around the replaced test. Hint may be "start" or "around". export function computeReplacedSel(doc, changes, hint) { let out = [] let oldPrev = Pos(doc.first, 0), newPrev = oldPrev for (let i = 0; i < changes.length; i++) { let change = changes[i] let from = offsetPos(change.from, oldPrev, newPrev) let to = offsetPos(changeEnd(change), oldPrev, newPrev) oldPrev = change.to newPrev = to if (hint == "around") { let range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0 out[i] = new Range(inv ? to : from, inv ? from : to) } else { out[i] = new Range(from, from) } } return new Selection(out, doc.sel.primIndex) } ================================================ FILE: third_party/CodeMirror/src/model/changes.js ================================================ import { retreatFrontier } from "../line/highlight.js" import { startWorker } from "../display/highlight_worker.js" import { operation } from "../display/operations.js" import { regChange, regLineChange } from "../display/view_tracking.js" import { clipLine, clipPos, cmp, Pos } from "../line/pos.js" import { sawReadOnlySpans } from "../line/saw_special_spans.js" import { lineLength, removeReadOnlyRanges, stretchSpansOverChange, visualLine } from "../line/spans.js" import { getBetween, getLine, lineNo } from "../line/utils_line.js" import { estimateHeight } from "../measurement/position_measurement.js" import { hasHandler, signal, signalCursorActivity } from "../util/event.js" import { indexOf, lst, map, sel_dontScroll } from "../util/misc.js" import { signalLater } from "../util/operation_group.js" import { changeEnd, computeSelAfterChange } from "./change_measurement.js" import { isWholeLineUpdate, linkedDocs, updateDoc } from "./document_data.js" import { addChangeToHistory, historyChangeFromChange, mergeOldSpans, pushSelectionToHistory } from "./history.js" import { Range, Selection } from "./selection.js" import { setSelection, setSelectionNoUndo } from "./selection_updates.js" // UPDATING // Allow "beforeChange" event handlers to influence a change function filterChange(doc, change, update) { let obj = { canceled: false, from: change.from, to: change.to, text: change.text, origin: change.origin, cancel: () => obj.canceled = true } if (update) obj.update = (from, to, text, origin) => { if (from) obj.from = clipPos(doc, from) if (to) obj.to = clipPos(doc, to) if (text) obj.text = text if (origin !== undefined) obj.origin = origin } signal(doc, "beforeChange", doc, obj) if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj) if (obj.canceled) { if (doc.cm) doc.cm.curOp.updateInput = 2 return null } return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} } // Apply a change to a document, and add it to the document's // history, and propagating it to all linked documents. export function makeChange(doc, change, ignoreReadOnly) { if (doc.cm) { if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) if (doc.cm.state.suppressEdits) return } if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { change = filterChange(doc, change, true) if (!change) return } // Possibly split or suppress the update based on the presence // of read-only spans in its range. let split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to) if (split) { for (let i = split.length - 1; i >= 0; --i) makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}) } else { makeChangeInner(doc, change) } } function makeChangeInner(doc, change) { if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return let selAfter = computeSelAfterChange(doc, change) addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN) makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)) let rebased = [] linkedDocs(doc, (doc, sharedHist) => { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change) rebased.push(doc.history) } makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)) }) } // Revert a change stored in a document's history. export function makeChangeFromHistory(doc, type, allowSelectionOnly) { let suppress = doc.cm && doc.cm.state.suppressEdits if (suppress && !allowSelectionOnly) return let hist = doc.history, event, selAfter = doc.sel let source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done // Verify that there is a useable event (so that ctrl-z won't // needlessly clear selection events) let i = 0 for (; i < source.length; i++) { event = source[i] if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) break } if (i == source.length) return hist.lastOrigin = hist.lastSelOrigin = null for (;;) { event = source.pop() if (event.ranges) { pushSelectionToHistory(event, dest) if (allowSelectionOnly && !event.equals(doc.sel)) { setSelection(doc, event, {clearRedo: false}) return } selAfter = event } else if (suppress) { source.push(event) return } else break } // Build up a reverse change object to add to the opposite history // stack (redo when undoing, and vice versa). let antiChanges = [] pushSelectionToHistory(selAfter, dest) dest.push({changes: antiChanges, generation: hist.generation}) hist.generation = event.generation || ++hist.maxGeneration let filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange") for (let i = event.changes.length - 1; i >= 0; --i) { let change = event.changes[i] change.origin = type if (filter && !filterChange(doc, change, false)) { source.length = 0 return } antiChanges.push(historyChangeFromChange(doc, change)) let after = i ? computeSelAfterChange(doc, change) : lst(source) makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)) if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}) let rebased = [] // Propagate to the linked documents linkedDocs(doc, (doc, sharedHist) => { if (!sharedHist && indexOf(rebased, doc.history) == -1) { rebaseHist(doc.history, change) rebased.push(doc.history) } makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)) }) } } // Sub-views need their line numbers shifted when text is added // above or below them in the parent document. function shiftDoc(doc, distance) { if (distance == 0) return doc.first += distance doc.sel = new Selection(map(doc.sel.ranges, range => new Range( Pos(range.anchor.line + distance, range.anchor.ch), Pos(range.head.line + distance, range.head.ch) )), doc.sel.primIndex) if (doc.cm) { regChange(doc.cm, doc.first, doc.first - distance, distance) for (let d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) regLineChange(doc.cm, l, "gutter") } } // More lower-level change function, handling only a single document // (not linked ones). function makeChangeSingleDoc(doc, change, selAfter, spans) { if (doc.cm && !doc.cm.curOp) return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) if (change.to.line < doc.first) { shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)) return } if (change.from.line > doc.lastLine()) return // Clip the change to the size of this doc if (change.from.line < doc.first) { let shift = change.text.length - 1 - (doc.first - change.from.line) shiftDoc(doc, shift) change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), text: [lst(change.text)], origin: change.origin} } let last = doc.lastLine() if (change.to.line > last) { change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), text: [change.text[0]], origin: change.origin} } change.removed = getBetween(doc, change.from, change.to) if (!selAfter) selAfter = computeSelAfterChange(doc, change) if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans) else updateDoc(doc, change, spans) setSelectionNoUndo(doc, selAfter, sel_dontScroll) } // Handle the interaction of a change to a document with the editor // that this document is part of. function makeChangeSingleDocInEditor(cm, change, spans) { let doc = cm.doc, display = cm.display, from = change.from, to = change.to let recomputeMaxLength = false, checkWidthStart = from.line if (!cm.options.lineWrapping) { checkWidthStart = lineNo(visualLine(getLine(doc, from.line))) doc.iter(checkWidthStart, to.line + 1, line => { if (line == display.maxLine) { recomputeMaxLength = true return true } }) } if (doc.sel.contains(change.from, change.to) > -1) signalCursorActivity(cm) updateDoc(doc, change, spans, estimateHeight(cm)) if (!cm.options.lineWrapping) { doc.iter(checkWidthStart, from.line + change.text.length, line => { let len = lineLength(line) if (len > display.maxLineLength) { display.maxLine = line display.maxLineLength = len display.maxLineChanged = true recomputeMaxLength = false } }) if (recomputeMaxLength) cm.curOp.updateMaxLine = true } retreatFrontier(doc, from.line) startWorker(cm, 400) let lendiff = change.text.length - (to.line - from.line) - 1 // Remember that these lines changed, for updating the display if (change.full) regChange(cm) else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) regLineChange(cm, from.line, "text") else regChange(cm, from.line, to.line + 1, lendiff) let changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change") if (changeHandler || changesHandler) { let obj = { from: from, to: to, text: change.text, removed: change.removed, origin: change.origin } if (changeHandler) signalLater(cm, "change", cm, obj) if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj) } cm.display.selForContextMenu = null } export function replaceRange(doc, code, from, to, origin) { if (!to) to = from if (cmp(to, from) < 0) [from, to] = [to, from] if (typeof code == "string") code = doc.splitLines(code) makeChange(doc, {from, to, text: code, origin}) } // Rebasing/resetting history to deal with externally-sourced changes function rebaseHistSelSingle(pos, from, to, diff) { if (to < pos.line) { pos.line += diff } else if (from < pos.line) { pos.line = from pos.ch = 0 } } // Tries to rebase an array of history events given a change in the // document. If the change touches the same lines as the event, the // event, and everything 'behind' it, is discarded. If the change is // before the event, the event's positions are updated. Uses a // copy-on-write scheme for the positions, to avoid having to // reallocate them all on every rebase, but also avoid problems with // shared position objects being unsafely updated. function rebaseHistArray(array, from, to, diff) { for (let i = 0; i < array.length; ++i) { let sub = array[i], ok = true if (sub.ranges) { if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true } for (let j = 0; j < sub.ranges.length; j++) { rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff) rebaseHistSelSingle(sub.ranges[j].head, from, to, diff) } continue } for (let j = 0; j < sub.changes.length; ++j) { let cur = sub.changes[j] if (to < cur.from.line) { cur.from = Pos(cur.from.line + diff, cur.from.ch) cur.to = Pos(cur.to.line + diff, cur.to.ch) } else if (from <= cur.to.line) { ok = false break } } if (!ok) { array.splice(0, i + 1) i = 0 } } } function rebaseHist(hist, change) { let from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1 rebaseHistArray(hist.done, from, to, diff) rebaseHistArray(hist.undone, from, to, diff) } // Utility for applying a change to a line by handle or number, // returning the number and optionally registering the line as // changed. export function changeLine(doc, handle, changeType, op) { let no = handle, line = handle if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)) else no = lineNo(handle) if (no == null) return null if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType) return line } ================================================ FILE: third_party/CodeMirror/src/model/chunk.js ================================================ import { cleanUpLine } from "../line/line_data.js" import { indexOf } from "../util/misc.js" import { signalLater } from "../util/operation_group.js" // The document is represented as a BTree consisting of leaves, with // chunk of lines in them, and branches, with up to ten leaves or // other branch nodes below them. The top node is always a branch // node, and is the document object itself (meaning it has // additional methods and properties). // // All nodes have parent links. The tree is used both to go from // line numbers to line objects, and to go from objects to numbers. // It also indexes by height, and is used to convert between height // and line object, and to find the total height of the document. // // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html export function LeafChunk(lines) { this.lines = lines this.parent = null let height = 0 for (let i = 0; i < lines.length; ++i) { lines[i].parent = this height += lines[i].height } this.height = height } LeafChunk.prototype = { chunkSize() { return this.lines.length }, // Remove the n lines at offset 'at'. removeInner(at, n) { for (let i = at, e = at + n; i < e; ++i) { let line = this.lines[i] this.height -= line.height cleanUpLine(line) signalLater(line, "delete") } this.lines.splice(at, n) }, // Helper used to collapse a small branch into a single leaf. collapse(lines) { lines.push.apply(lines, this.lines) }, // Insert the given array of lines at offset 'at', count them as // having the given height. insertInner(at, lines, height) { this.height += height this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)) for (let i = 0; i < lines.length; ++i) lines[i].parent = this }, // Used to iterate over a part of the tree. iterN(at, n, op) { for (let e = at + n; at < e; ++at) if (op(this.lines[at])) return true } } export function BranchChunk(children) { this.children = children let size = 0, height = 0 for (let i = 0; i < children.length; ++i) { let ch = children[i] size += ch.chunkSize(); height += ch.height ch.parent = this } this.size = size this.height = height this.parent = null } BranchChunk.prototype = { chunkSize() { return this.size }, removeInner(at, n) { this.size -= n for (let i = 0; i < this.children.length; ++i) { let child = this.children[i], sz = child.chunkSize() if (at < sz) { let rm = Math.min(n, sz - at), oldHeight = child.height child.removeInner(at, rm) this.height -= oldHeight - child.height if (sz == rm) { this.children.splice(i--, 1); child.parent = null } if ((n -= rm) == 0) break at = 0 } else at -= sz } // If the result is smaller than 25 lines, ensure that it is a // single leaf node. if (this.size - n < 25 && (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { let lines = [] this.collapse(lines) this.children = [new LeafChunk(lines)] this.children[0].parent = this } }, collapse(lines) { for (let i = 0; i < this.children.length; ++i) this.children[i].collapse(lines) }, insertInner(at, lines, height) { this.size += lines.length this.height += height for (let i = 0; i < this.children.length; ++i) { let child = this.children[i], sz = child.chunkSize() if (at <= sz) { child.insertInner(at, lines, height) if (child.lines && child.lines.length > 50) { // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. let remaining = child.lines.length % 25 + 25 for (let pos = remaining; pos < child.lines.length;) { let leaf = new LeafChunk(child.lines.slice(pos, pos += 25)) child.height -= leaf.height this.children.splice(++i, 0, leaf) leaf.parent = this } child.lines = child.lines.slice(0, remaining) this.maybeSpill() } break } at -= sz } }, // When a node has grown, check whether it should be split. maybeSpill() { if (this.children.length <= 10) return let me = this do { let spilled = me.children.splice(me.children.length - 5, 5) let sibling = new BranchChunk(spilled) if (!me.parent) { // Become the parent node let copy = new BranchChunk(me.children) copy.parent = me me.children = [copy, sibling] me = copy } else { me.size -= sibling.size me.height -= sibling.height let myIndex = indexOf(me.parent.children, me) me.parent.children.splice(myIndex + 1, 0, sibling) } sibling.parent = me.parent } while (me.children.length > 10) me.parent.maybeSpill() }, iterN(at, n, op) { for (let i = 0; i < this.children.length; ++i) { let child = this.children[i], sz = child.chunkSize() if (at < sz) { let used = Math.min(n, sz - at) if (child.iterN(at, used, op)) return true if ((n -= used) == 0) break at = 0 } else at -= sz } } } ================================================ FILE: third_party/CodeMirror/src/model/document_data.js ================================================ import { loadMode } from "../display/mode_state.js" import { runInOp } from "../display/operations.js" import { regChange } from "../display/view_tracking.js" import { Line, updateLine } from "../line/line_data.js" import { findMaxLine } from "../line/spans.js" import { getLine } from "../line/utils_line.js" import { estimateLineHeights } from "../measurement/position_measurement.js" import { addClass, rmClass } from "../util/dom.js" import { lst } from "../util/misc.js" import { signalLater } from "../util/operation_group.js" // DOCUMENT DATA STRUCTURE // By default, updates that start and end at the beginning of a line // are treated specially, in order to make the association of line // widgets and marker elements with the text behave more intuitive. export function isWholeLineUpdate(doc, change) { return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && (!doc.cm || doc.cm.options.wholeLineUpdateBefore) } // Perform a change on the document data structure. export function updateDoc(doc, change, markedSpans, estimateHeight) { function spansFor(n) {return markedSpans ? markedSpans[n] : null} function update(line, text, spans) { updateLine(line, text, spans, estimateHeight) signalLater(line, "change", line, change) } function linesFor(start, end) { let result = [] for (let i = start; i < end; ++i) result.push(new Line(text[i], spansFor(i), estimateHeight)) return result } let from = change.from, to = change.to, text = change.text let firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line) let lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line // Adjust the line structure if (change.full) { doc.insert(0, linesFor(0, text.length)) doc.remove(text.length, doc.size - text.length) } else if (isWholeLineUpdate(doc, change)) { // This is a whole-line replace. Treated specially to make // sure line objects move the way they are supposed to. let added = linesFor(0, text.length - 1) update(lastLine, lastLine.text, lastSpans) if (nlines) doc.remove(from.line, nlines) if (added.length) doc.insert(from.line, added) } else if (firstLine == lastLine) { if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans) } else { let added = linesFor(1, text.length - 1) added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)) update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) doc.insert(from.line + 1, added) } } else if (text.length == 1) { update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)) doc.remove(from.line + 1, nlines) } else { update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)) update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans) let added = linesFor(1, text.length - 1) if (nlines > 1) doc.remove(from.line + 1, nlines - 1) doc.insert(from.line + 1, added) } signalLater(doc, "change", doc, change) } // Call f for all linked documents. export function linkedDocs(doc, f, sharedHistOnly) { function propagate(doc, skip, sharedHist) { if (doc.linked) for (let i = 0; i < doc.linked.length; ++i) { let rel = doc.linked[i] if (rel.doc == skip) continue let shared = sharedHist && rel.sharedHist if (sharedHistOnly && !shared) continue f(rel.doc, shared) propagate(rel.doc, doc, shared) } } propagate(doc, null, true) } // Attach a document to an editor. export function attachDoc(cm, doc) { if (doc.cm) throw new Error("This document is already in use.") cm.doc = doc doc.cm = cm estimateLineHeights(cm) loadMode(cm) setDirectionClass(cm) if (!cm.options.lineWrapping) findMaxLine(cm) cm.options.mode = doc.modeOption regChange(cm) } function setDirectionClass(cm) { ;(cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl") } export function directionChanged(cm) { runInOp(cm, () => { setDirectionClass(cm) regChange(cm) }) } ================================================ FILE: third_party/CodeMirror/src/model/history.js ================================================ import { cmp, copyPos } from "../line/pos.js" import { stretchSpansOverChange } from "../line/spans.js" import { getBetween } from "../line/utils_line.js" import { signal } from "../util/event.js" import { indexOf, lst } from "../util/misc.js" import { changeEnd } from "./change_measurement.js" import { linkedDocs } from "./document_data.js" import { Selection } from "./selection.js" export function History(startGen) { // Arrays of change events and selections. Doing something adds an // event to done and clears undo. Undoing moves events from done // to undone, redoing moves them in the other direction. this.done = []; this.undone = [] this.undoDepth = Infinity // Used to track when changes can be merged into a single undo // event this.lastModTime = this.lastSelTime = 0 this.lastOp = this.lastSelOp = null this.lastOrigin = this.lastSelOrigin = null // Used by the isClean() method this.generation = this.maxGeneration = startGen || 1 } // Create a history change event from an updateDoc-style change // object. export function historyChangeFromChange(doc, change) { let histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)} attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1) linkedDocs(doc, doc => attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1), true) return histChange } // Pop all selection events off the end of a history array. Stop at // a change event. function clearSelectionEvents(array) { while (array.length) { let last = lst(array) if (last.ranges) array.pop() else break } } // Find the top change event in the history. Pop off selection // events that are in the way. function lastChangeEvent(hist, force) { if (force) { clearSelectionEvents(hist.done) return lst(hist.done) } else if (hist.done.length && !lst(hist.done).ranges) { return lst(hist.done) } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { hist.done.pop() return lst(hist.done) } } // Register a change in the history. Merges changes that are within // a single operation, or are close together with an origin that // allows merging (starting with "+") into a single event. export function addChangeToHistory(doc, change, selAfter, opId) { let hist = doc.history hist.undone.length = 0 let time = +new Date, cur let last if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { // Merge this change into the last event last = lst(cur.changes) if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { // Optimized case for simple insertion -- don't want to add // new changesets for every character typed last.to = changeEnd(change) } else { // Add new sub-event cur.changes.push(historyChangeFromChange(doc, change)) } } else { // Can not be merged, start a new event. let before = lst(hist.done) if (!before || !before.ranges) pushSelectionToHistory(doc.sel, hist.done) cur = {changes: [historyChangeFromChange(doc, change)], generation: hist.generation} hist.done.push(cur) while (hist.done.length > hist.undoDepth) { hist.done.shift() if (!hist.done[0].ranges) hist.done.shift() } } hist.done.push(selAfter) hist.generation = ++hist.maxGeneration hist.lastModTime = hist.lastSelTime = time hist.lastOp = hist.lastSelOp = opId hist.lastOrigin = hist.lastSelOrigin = change.origin if (!last) signal(doc, "historyAdded") } function selectionEventCanBeMerged(doc, origin, prev, sel) { let ch = origin.charAt(0) return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) } // Called whenever the selection changes, sets the new selection as // the pending selection in the history, and pushes the old pending // selection into the 'done' array when it was significantly // different (in number of selected ranges, emptiness, or time). export function addSelectionToHistory(doc, sel, opId, options) { let hist = doc.history, origin = options && options.origin // A new event is started when the previous origin does not match // the current, or the origins don't allow matching. Origins // starting with * are always merged, those starting with + are // merged when similar and close together in time. if (opId == hist.lastSelOp || (origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) hist.done[hist.done.length - 1] = sel else pushSelectionToHistory(sel, hist.done) hist.lastSelTime = +new Date hist.lastSelOrigin = origin hist.lastSelOp = opId if (options && options.clearRedo !== false) clearSelectionEvents(hist.undone) } export function pushSelectionToHistory(sel, dest) { let top = lst(dest) if (!(top && top.ranges && top.equals(sel))) dest.push(sel) } // Used to store marked span information in the history. function attachLocalSpans(doc, change, from, to) { let existing = change["spans_" + doc.id], n = 0 doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), line => { if (line.markedSpans) (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans ++n }) } // When un/re-doing restores text containing marked spans, those // that have been explicitly cleared should not be restored. function removeClearedSpans(spans) { if (!spans) return null let out for (let i = 0; i < spans.length; ++i) { if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i) } else if (out) out.push(spans[i]) } return !out ? spans : out.length ? out : null } // Retrieve and filter the old marked spans stored in a change event. function getOldSpans(doc, change) { let found = change["spans_" + doc.id] if (!found) return null let nw = [] for (let i = 0; i < change.text.length; ++i) nw.push(removeClearedSpans(found[i])) return nw } // Used for un/re-doing changes from the history. Combines the // result of computing the existing spans with the set of spans that // existed in the history (so that deleting around a span and then // undoing brings back the span). export function mergeOldSpans(doc, change) { let old = getOldSpans(doc, change) let stretched = stretchSpansOverChange(doc, change) if (!old) return stretched if (!stretched) return old for (let i = 0; i < old.length; ++i) { let oldCur = old[i], stretchCur = stretched[i] if (oldCur && stretchCur) { spans: for (let j = 0; j < stretchCur.length; ++j) { let span = stretchCur[j] for (let k = 0; k < oldCur.length; ++k) if (oldCur[k].marker == span.marker) continue spans oldCur.push(span) } } else if (stretchCur) { old[i] = stretchCur } } return old } // Used both to provide a JSON-safe object in .getHistory, and, when // detaching a document, to split the history in two export function copyHistoryArray(events, newGroup, instantiateSel) { let copy = [] for (let i = 0; i < events.length; ++i) { let event = events[i] if (event.ranges) { copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event) continue } let changes = event.changes, newChanges = [] copy.push({changes: newChanges}) for (let j = 0; j < changes.length; ++j) { let change = changes[j], m newChanges.push({from: change.from, to: change.to, text: change.text}) if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { if (indexOf(newGroup, Number(m[1])) > -1) { lst(newChanges)[prop] = change[prop] delete change[prop] } } } } return copy } ================================================ FILE: third_party/CodeMirror/src/model/line_widget.js ================================================ import { runInOp } from "../display/operations.js" import { addToScrollTop } from "../display/scrolling.js" import { regLineChange } from "../display/view_tracking.js" import { heightAtLine, lineIsHidden } from "../line/spans.js" import { lineNo, updateLineHeight } from "../line/utils_line.js" import { widgetHeight } from "../measurement/widgets.js" import { changeLine } from "./changes.js" import { eventMixin } from "../util/event.js" import { signalLater } from "../util/operation_group.js" // Line widgets are block elements displayed above or below a line. export class LineWidget { constructor(doc, node, options) { if (options) for (let opt in options) if (options.hasOwnProperty(opt)) this[opt] = options[opt] this.doc = doc this.node = node } clear() { let cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line) if (no == null || !ws) return for (let i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1) if (!ws.length) line.widgets = null let height = widgetHeight(this) updateLineHeight(line, Math.max(0, line.height - height)) if (cm) { runInOp(cm, () => { adjustScrollWhenAboveVisible(cm, line, -height) regLineChange(cm, no, "widget") }) signalLater(cm, "lineWidgetCleared", cm, this, no) } } changed() { let oldH = this.height, cm = this.doc.cm, line = this.line this.height = null let diff = widgetHeight(this) - oldH if (!diff) return if (!lineIsHidden(this.doc, line)) updateLineHeight(line, line.height + diff) if (cm) { runInOp(cm, () => { cm.curOp.forceUpdate = true adjustScrollWhenAboveVisible(cm, line, diff) signalLater(cm, "lineWidgetChanged", cm, this, lineNo(line)) }) } } } eventMixin(LineWidget) function adjustScrollWhenAboveVisible(cm, line, diff) { if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) addToScrollTop(cm, diff) } export function addLineWidget(doc, handle, node, options) { let widget = new LineWidget(doc, node, options) let cm = doc.cm if (cm && widget.noHScroll) cm.display.alignWidgets = true changeLine(doc, handle, "widget", line => { let widgets = line.widgets || (line.widgets = []) if (widget.insertAt == null) widgets.push(widget) else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget) widget.line = line if (cm && !lineIsHidden(doc, line)) { let aboveVisible = heightAtLine(line) < doc.scrollTop updateLineHeight(line, line.height + widgetHeight(widget)) if (aboveVisible) addToScrollTop(cm, widget.height) cm.curOp.forceUpdate = true } return true }) if (cm) signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)) return widget } ================================================ FILE: third_party/CodeMirror/src/model/mark_text.js ================================================ import { eltP } from "../util/dom.js" import { eventMixin, hasHandler, on } from "../util/event.js" import { endOperation, operation, runInOp, startOperation } from "../display/operations.js" import { clipPos, cmp, Pos } from "../line/pos.js" import { lineNo, updateLineHeight } from "../line/utils_line.js" import { clearLineMeasurementCacheFor, findViewForLine, textHeight } from "../measurement/position_measurement.js" import { seeReadOnlySpans, seeCollapsedSpans } from "../line/saw_special_spans.js" import { addMarkedSpan, conflictingCollapsedRange, getMarkedSpanFor, lineIsHidden, lineLength, MarkedSpan, removeMarkedSpan, visualLine } from "../line/spans.js" import { copyObj, indexOf, lst } from "../util/misc.js" import { signalLater } from "../util/operation_group.js" import { widgetHeight } from "../measurement/widgets.js" import { regChange, regLineChange } from "../display/view_tracking.js" import { linkedDocs } from "./document_data.js" import { addChangeToHistory } from "./history.js" import { reCheckSelection } from "./selection_updates.js" // TEXTMARKERS // Created with markText and setBookmark methods. A TextMarker is a // handle that can be used to clear or find a marked position in the // document. Line objects hold arrays (markedSpans) containing // {from, to, marker} object pointing to such marker objects, and // indicating that such a marker is present on that line. Multiple // lines may point to the same marker when it spans across lines. // The spans will have null for their from/to properties when the // marker continues beyond the start/end of the line. Markers have // links back to the lines they currently touch. // Collapsed markers have unique ids, in order to be able to order // them, which is needed for uniquely determining an outer marker // when they overlap (they may nest, but not partially overlap). let nextMarkerId = 0 export class TextMarker { constructor(doc, type) { this.lines = [] this.type = type this.doc = doc this.id = ++nextMarkerId } // Clear the marker. clear() { if (this.explicitlyCleared) return let cm = this.doc.cm, withOp = cm && !cm.curOp if (withOp) startOperation(cm) if (hasHandler(this, "clear")) { let found = this.find() if (found) signalLater(this, "clear", found.from, found.to) } let min = null, max = null for (let i = 0; i < this.lines.length; ++i) { let line = this.lines[i] let span = getMarkedSpanFor(line.markedSpans, this) if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text") else if (cm) { if (span.to != null) max = lineNo(line) if (span.from != null) min = lineNo(line) } line.markedSpans = removeMarkedSpan(line.markedSpans, span) if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) updateLineHeight(line, textHeight(cm.display)) } if (cm && this.collapsed && !cm.options.lineWrapping) for (let i = 0; i < this.lines.length; ++i) { let visual = visualLine(this.lines[i]), len = lineLength(visual) if (len > cm.display.maxLineLength) { cm.display.maxLine = visual cm.display.maxLineLength = len cm.display.maxLineChanged = true } } if (min != null && cm && this.collapsed) regChange(cm, min, max + 1) this.lines.length = 0 this.explicitlyCleared = true if (this.atomic && this.doc.cantEdit) { this.doc.cantEdit = false if (cm) reCheckSelection(cm.doc) } if (cm) signalLater(cm, "markerCleared", cm, this, min, max) if (withOp) endOperation(cm) if (this.parent) this.parent.clear() } // Find the position of the marker in the document. Returns a {from, // to} object by default. Side can be passed to get a specific side // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the // Pos objects returned contain a line object, rather than a line // number (used to prevent looking up the same line twice). find(side, lineObj) { if (side == null && this.type == "bookmark") side = 1 let from, to for (let i = 0; i < this.lines.length; ++i) { let line = this.lines[i] let span = getMarkedSpanFor(line.markedSpans, this) if (span.from != null) { from = Pos(lineObj ? line : lineNo(line), span.from) if (side == -1) return from } if (span.to != null) { to = Pos(lineObj ? line : lineNo(line), span.to) if (side == 1) return to } } return from && {from: from, to: to} } // Signals that the marker's widget changed, and surrounding layout // should be recomputed. changed() { let pos = this.find(-1, true), widget = this, cm = this.doc.cm if (!pos || !cm) return runInOp(cm, () => { let line = pos.line, lineN = lineNo(pos.line) let view = findViewForLine(cm, lineN) if (view) { clearLineMeasurementCacheFor(view) cm.curOp.selectionChanged = cm.curOp.forceUpdate = true } cm.curOp.updateMaxLine = true if (!lineIsHidden(widget.doc, line) && widget.height != null) { let oldHeight = widget.height widget.height = null let dHeight = widgetHeight(widget) - oldHeight if (dHeight) updateLineHeight(line, line.height + dHeight) } signalLater(cm, "markerChanged", cm, this) }) } attachLine(line) { if (!this.lines.length && this.doc.cm) { let op = this.doc.cm.curOp if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this) } this.lines.push(line) } detachLine(line) { this.lines.splice(indexOf(this.lines, line), 1) if (!this.lines.length && this.doc.cm) { let op = this.doc.cm.curOp ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this) } } } eventMixin(TextMarker) // Create a marker, wire it up to the right lines, and export function markText(doc, from, to, options, type) { // Shared markers (across linked documents) are handled separately // (markTextShared will call out to this again, once per // document). if (options && options.shared) return markTextShared(doc, from, to, options, type) // Ensure we are in an operation. if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type) let marker = new TextMarker(doc, type), diff = cmp(from, to) if (options) copyObj(options, marker, false) // Don't connect empty markers unless clearWhenEmpty is false if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) return marker if (marker.replacedWith) { // Showing up as a widget implies collapsed (widget replaces text) marker.collapsed = true marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget") if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true") if (options.insertLeft) marker.widgetNode.insertLeft = true } if (marker.collapsed) { if (conflictingCollapsedRange(doc, from.line, from, to, marker) || from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) throw new Error("Inserting collapsed marker partially overlapping an existing one") seeCollapsedSpans() } if (marker.addToHistory) addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN) let curLine = from.line, cm = doc.cm, updateMaxLine doc.iter(curLine, to.line + 1, line => { if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) updateMaxLine = true if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0) addMarkedSpan(line, new MarkedSpan(marker, curLine == from.line ? from.ch : null, curLine == to.line ? to.ch : null)) ++curLine }) // lineIsHidden depends on the presence of the spans, so needs a second pass if (marker.collapsed) doc.iter(from.line, to.line + 1, line => { if (lineIsHidden(doc, line)) updateLineHeight(line, 0) }) if (marker.clearOnEnter) on(marker, "beforeCursorEnter", () => marker.clear()) if (marker.readOnly) { seeReadOnlySpans() if (doc.history.done.length || doc.history.undone.length) doc.clearHistory() } if (marker.collapsed) { marker.id = ++nextMarkerId marker.atomic = true } if (cm) { // Sync editor state if (updateMaxLine) cm.curOp.updateMaxLine = true if (marker.collapsed) regChange(cm, from.line, to.line + 1) else if (marker.className || marker.startStyle || marker.endStyle || marker.css || marker.attributes || marker.title) for (let i = from.line; i <= to.line; i++) regLineChange(cm, i, "text") if (marker.atomic) reCheckSelection(cm.doc) signalLater(cm, "markerAdded", cm, marker) } return marker } // SHARED TEXTMARKERS // A shared marker spans multiple linked documents. It is // implemented as a meta-marker-object controlling multiple normal // markers. export class SharedTextMarker { constructor(markers, primary) { this.markers = markers this.primary = primary for (let i = 0; i < markers.length; ++i) markers[i].parent = this } clear() { if (this.explicitlyCleared) return this.explicitlyCleared = true for (let i = 0; i < this.markers.length; ++i) this.markers[i].clear() signalLater(this, "clear") } find(side, lineObj) { return this.primary.find(side, lineObj) } } eventMixin(SharedTextMarker) function markTextShared(doc, from, to, options, type) { options = copyObj(options) options.shared = false let markers = [markText(doc, from, to, options, type)], primary = markers[0] let widget = options.widgetNode linkedDocs(doc, doc => { if (widget) options.widgetNode = widget.cloneNode(true) markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)) for (let i = 0; i < doc.linked.length; ++i) if (doc.linked[i].isParent) return primary = lst(markers) }) return new SharedTextMarker(markers, primary) } export function findSharedMarkers(doc) { return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), m => m.parent) } export function copySharedMarkers(doc, markers) { for (let i = 0; i < markers.length; i++) { let marker = markers[i], pos = marker.find() let mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to) if (cmp(mFrom, mTo)) { let subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type) marker.markers.push(subMark) subMark.parent = marker } } } export function detachSharedMarkers(markers) { for (let i = 0; i < markers.length; i++) { let marker = markers[i], linked = [marker.primary.doc] linkedDocs(marker.primary.doc, d => linked.push(d)) for (let j = 0; j < marker.markers.length; j++) { let subMarker = marker.markers[j] if (indexOf(linked, subMarker.doc) == -1) { subMarker.parent = null marker.markers.splice(j--, 1) } } } } ================================================ FILE: third_party/CodeMirror/src/model/selection.js ================================================ import { cmp, copyPos, equalCursorPos, maxPos, minPos } from "../line/pos.js" import { indexOf } from "../util/misc.js" // Selection objects are immutable. A new one is created every time // the selection changes. A selection is one or more non-overlapping // (and non-touching) ranges, sorted, and an integer that indicates // which one is the primary selection (the one that's scrolled into // view, that getCursor returns, etc). export class Selection { constructor(ranges, primIndex) { this.ranges = ranges this.primIndex = primIndex } primary() { return this.ranges[this.primIndex] } equals(other) { if (other == this) return true if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false for (let i = 0; i < this.ranges.length; i++) { let here = this.ranges[i], there = other.ranges[i] if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) return false } return true } deepCopy() { let out = [] for (let i = 0; i < this.ranges.length; i++) out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)) return new Selection(out, this.primIndex) } somethingSelected() { for (let i = 0; i < this.ranges.length; i++) if (!this.ranges[i].empty()) return true return false } contains(pos, end) { if (!end) end = pos for (let i = 0; i < this.ranges.length; i++) { let range = this.ranges[i] if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) return i } return -1 } } export class Range { constructor(anchor, head) { this.anchor = anchor; this.head = head } from() { return minPos(this.anchor, this.head) } to() { return maxPos(this.anchor, this.head) } empty() { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch } } // Take an unsorted, potentially overlapping set of ranges, and // build a selection out of it. 'Consumes' ranges array (modifying // it). export function normalizeSelection(cm, ranges, primIndex) { let mayTouch = cm && cm.options.selectionsMayTouch let prim = ranges[primIndex] ranges.sort((a, b) => cmp(a.from(), b.from())) primIndex = indexOf(ranges, prim) for (let i = 1; i < ranges.length; i++) { let cur = ranges[i], prev = ranges[i - 1] let diff = cmp(prev.to(), cur.from()) if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { let from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()) let inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head if (i <= primIndex) --primIndex ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)) } } return new Selection(ranges, primIndex) } export function simpleSelection(anchor, head) { return new Selection([new Range(anchor, head || anchor)], 0) } ================================================ FILE: third_party/CodeMirror/src/model/selection_updates.js ================================================ import { signalLater } from "../util/operation_group.js" import { ensureCursorVisible } from "../display/scrolling.js" import { clipPos, cmp, Pos } from "../line/pos.js" import { getLine } from "../line/utils_line.js" import { hasHandler, signal, signalCursorActivity } from "../util/event.js" import { lst, sel_dontScroll } from "../util/misc.js" import { addSelectionToHistory } from "./history.js" import { normalizeSelection, Range, Selection, simpleSelection } from "./selection.js" // The 'scroll' parameter given to many of these indicated whether // the new cursor position should be scrolled into view after // modifying the selection. // If shift is held or the extend flag is set, extends a range to // include a given position (and optionally a second position). // Otherwise, simply returns the range between the given positions. // Used for cursor motion and such. export function extendRange(range, head, other, extend) { if (extend) { let anchor = range.anchor if (other) { let posBefore = cmp(head, anchor) < 0 if (posBefore != (cmp(other, anchor) < 0)) { anchor = head head = other } else if (posBefore != (cmp(head, other) < 0)) { head = other } } return new Range(anchor, head) } else { return new Range(other || head, head) } } // Extend the primary selection range, discard the rest. export function extendSelection(doc, head, other, options, extend) { if (extend == null) extend = doc.cm && (doc.cm.display.shift || doc.extend) setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options) } // Extend all selections (pos is an array of selections with length // equal the number of selections) export function extendSelections(doc, heads, options) { let out = [] let extend = doc.cm && (doc.cm.display.shift || doc.extend) for (let i = 0; i < doc.sel.ranges.length; i++) out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend) let newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex) setSelection(doc, newSel, options) } // Updates a single range in the selection. export function replaceOneSelection(doc, i, range, options) { let ranges = doc.sel.ranges.slice(0) ranges[i] = range setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options) } // Reset the selection to a single range. export function setSimpleSelection(doc, anchor, head, options) { setSelection(doc, simpleSelection(anchor, head), options) } // Give beforeSelectionChange handlers a change to influence a // selection update. function filterSelectionChange(doc, sel, options) { let obj = { ranges: sel.ranges, update: function(ranges) { this.ranges = [] for (let i = 0; i < ranges.length; i++) this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), clipPos(doc, ranges[i].head)) }, origin: options && options.origin } signal(doc, "beforeSelectionChange", doc, obj) if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj) if (obj.ranges != sel.ranges) return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) else return sel } export function setSelectionReplaceHistory(doc, sel, options) { let done = doc.history.done, last = lst(done) if (last && last.ranges) { done[done.length - 1] = sel setSelectionNoUndo(doc, sel, options) } else { setSelection(doc, sel, options) } } // Set a new selection. export function setSelection(doc, sel, options) { setSelectionNoUndo(doc, sel, options) addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options) } export function setSelectionNoUndo(doc, sel, options) { if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) sel = filterSelectionChange(doc, sel, options) let bias = options && options.bias || (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1) setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)) if (!(options && options.scroll === false) && doc.cm) ensureCursorVisible(doc.cm) } function setSelectionInner(doc, sel) { if (sel.equals(doc.sel)) return doc.sel = sel if (doc.cm) { doc.cm.curOp.updateInput = 1 doc.cm.curOp.selectionChanged = true signalCursorActivity(doc.cm) } signalLater(doc, "cursorActivity", doc) } // Verify that the selection does not partially select any atomic // marked ranges. export function reCheckSelection(doc) { setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)) } // Return a selection that does not partially select any atomic // ranges. function skipAtomicInSelection(doc, sel, bias, mayClear) { let out for (let i = 0; i < sel.ranges.length; i++) { let range = sel.ranges[i] let old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i] let newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear) let newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear) if (out || newAnchor != range.anchor || newHead != range.head) { if (!out) out = sel.ranges.slice(0, i) out[i] = new Range(newAnchor, newHead) } } return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel } function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { let line = getLine(doc, pos.line) if (line.markedSpans) for (let i = 0; i < line.markedSpans.length; ++i) { let sp = line.markedSpans[i], m = sp.marker if ((sp.from == null || (m.inclusiveLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && (sp.to == null || (m.inclusiveRight ? sp.to >= pos.ch : sp.to > pos.ch))) { if (mayClear) { signal(m, "beforeCursorEnter") if (m.explicitlyCleared) { if (!line.markedSpans) break else {--i; continue} } } if (!m.atomic) continue if (oldPos) { let near = m.find(dir < 0 ? 1 : -1), diff if (dir < 0 ? m.inclusiveRight : m.inclusiveLeft) near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null) if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) return skipAtomicInner(doc, near, pos, dir, mayClear) } let far = m.find(dir < 0 ? -1 : 1) if (dir < 0 ? m.inclusiveLeft : m.inclusiveRight) far = movePos(doc, far, dir, far.line == pos.line ? line : null) return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null } } return pos } // Ensure a given position is not inside an atomic range. export function skipAtomic(doc, pos, oldPos, bias, mayClear) { let dir = bias || 1 let found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)) if (!found) { doc.cantEdit = true return Pos(doc.first, 0) } return found } function movePos(doc, pos, dir, line) { if (dir < 0 && pos.ch == 0) { if (pos.line > doc.first) return clipPos(doc, Pos(pos.line - 1)) else return null } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { if (pos.line < doc.first + doc.size - 1) return Pos(pos.line + 1, 0) else return null } else { return new Pos(pos.line, pos.ch + dir) } } export function selectAll(cm) { cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll) } ================================================ FILE: third_party/CodeMirror/src/modes.js ================================================ import { copyObj, createObj } from "./util/misc.js" // Known modes, by name and by MIME export let modes = {}, mimeModes = {} // Extra arguments are stored as the mode's dependencies, which is // used by (legacy) mechanisms like loadmode.js to automatically // load a mode. (Preferred mechanism is the require/define calls.) export function defineMode(name, mode) { if (arguments.length > 2) mode.dependencies = Array.prototype.slice.call(arguments, 2) modes[name] = mode } export function defineMIME(mime, spec) { mimeModes[mime] = spec } // Given a MIME type, a {name, ...options} config object, or a name // string, return a mode config object. export function resolveMode(spec) { if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { spec = mimeModes[spec] } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { let found = mimeModes[spec.name] if (typeof found == "string") found = {name: found} spec = createObj(found, spec) spec.name = found.name } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { return resolveMode("application/xml") } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { return resolveMode("application/json") } if (typeof spec == "string") return {name: spec} else return spec || {name: "null"} } // Given a mode spec (anything that resolveMode accepts), find and // initialize an actual mode object. export function getMode(options, spec) { spec = resolveMode(spec) let mfactory = modes[spec.name] if (!mfactory) return getMode(options, "text/plain") let modeObj = mfactory(options, spec) if (modeExtensions.hasOwnProperty(spec.name)) { let exts = modeExtensions[spec.name] for (let prop in exts) { if (!exts.hasOwnProperty(prop)) continue if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop] modeObj[prop] = exts[prop] } } modeObj.name = spec.name if (spec.helperType) modeObj.helperType = spec.helperType if (spec.modeProps) for (let prop in spec.modeProps) modeObj[prop] = spec.modeProps[prop] return modeObj } // This can be used to attach properties to mode objects from // outside the actual mode definition. export let modeExtensions = {} export function extendMode(mode, properties) { let exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}) copyObj(properties, exts) } export function copyState(mode, state) { if (state === true) return state if (mode.copyState) return mode.copyState(state) let nstate = {} for (let n in state) { let val = state[n] if (val instanceof Array) val = val.concat([]) nstate[n] = val } return nstate } // Given a mode and a state (for that mode), find the inner mode and // state at the position that the state refers to. export function innerMode(mode, state) { let info while (mode.innerMode) { info = mode.innerMode(state) if (!info || info.mode == mode) break state = info.state mode = info.mode } return info || {mode: mode, state: state} } export function startState(mode, a1, a2) { return mode.startState ? mode.startState(a1, a2) : true } ================================================ FILE: third_party/CodeMirror/src/util/StringStream.js ================================================ import { countColumn } from "./misc.js" // STRING STREAM // Fed to the mode parsers, provides helper functions to make // parsers more succinct. class StringStream { constructor(string, tabSize, lineOracle) { this.pos = this.start = 0 this.string = string this.tabSize = tabSize || 8 this.lastColumnPos = this.lastColumnValue = 0 this.lineStart = 0 this.lineOracle = lineOracle } eol() {return this.pos >= this.string.length} sol() {return this.pos == this.lineStart} peek() {return this.string.charAt(this.pos) || undefined} next() { if (this.pos < this.string.length) return this.string.charAt(this.pos++) } eat(match) { let ch = this.string.charAt(this.pos) let ok if (typeof match == "string") ok = ch == match else ok = ch && (match.test ? match.test(ch) : match(ch)) if (ok) {++this.pos; return ch} } eatWhile(match) { let start = this.pos while (this.eat(match)){} return this.pos > start } eatSpace() { let start = this.pos while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos return this.pos > start } skipToEnd() {this.pos = this.string.length} skipTo(ch) { let found = this.string.indexOf(ch, this.pos) if (found > -1) {this.pos = found; return true} } backUp(n) {this.pos -= n} column() { if (this.lastColumnPos < this.start) { this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue) this.lastColumnPos = this.start } return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) } indentation() { return countColumn(this.string, null, this.tabSize) - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) } match(pattern, consume, caseInsensitive) { if (typeof pattern == "string") { let cased = str => caseInsensitive ? str.toLowerCase() : str let substr = this.string.substr(this.pos, pattern.length) if (cased(substr) == cased(pattern)) { if (consume !== false) this.pos += pattern.length return true } } else { let match = this.string.slice(this.pos).match(pattern) if (match && match.index > 0) return null if (match && consume !== false) this.pos += match[0].length return match } } current(){return this.string.slice(this.start, this.pos)} hideFirstChars(n, inner) { this.lineStart += n try { return inner() } finally { this.lineStart -= n } } lookAhead(n) { let oracle = this.lineOracle return oracle && oracle.lookAhead(n) } baseToken() { let oracle = this.lineOracle return oracle && oracle.baseToken(this.pos) } } export default StringStream ================================================ FILE: third_party/CodeMirror/src/util/bidi.js ================================================ import { lst } from "./misc.js" // BIDI HELPERS export function iterateBidiSections(order, from, to, f) { if (!order) return f(from, to, "ltr", 0) let found = false for (let i = 0; i < order.length; ++i) { let part = order[i] if (part.from < to && part.to > from || from == to && part.to == from) { f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i) found = true } } if (!found) f(from, to, "ltr") } export let bidiOther = null export function getBidiPartAt(order, ch, sticky) { let found bidiOther = null for (let i = 0; i < order.length; ++i) { let cur = order[i] if (cur.from < ch && cur.to > ch) return i if (cur.to == ch) { if (cur.from != cur.to && sticky == "before") found = i else bidiOther = i } if (cur.from == ch) { if (cur.from != cur.to && sticky != "before") found = i else bidiOther = i } } return found != null ? found : bidiOther } // Bidirectional ordering algorithm // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm // that this (partially) implements. // One-char codes used for character types: // L (L): Left-to-Right // R (R): Right-to-Left // r (AL): Right-to-Left Arabic // 1 (EN): European Number // + (ES): European Number Separator // % (ET): European Number Terminator // n (AN): Arabic Number // , (CS): Common Number Separator // m (NSM): Non-Spacing Mark // b (BN): Boundary Neutral // s (B): Paragraph Separator // t (S): Segment Separator // w (WS): Whitespace // N (ON): Other Neutrals // Returns null if characters are ordered as they appear // (left-to-right), or an array of sections ({from, to, level} // objects) in the order in which they occur visually. let bidiOrdering = (function() { // Character types for codepoints 0 to 0xff let lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN" // Character types for codepoints 0x600 to 0x6f9 let arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111" function charType(code) { if (code <= 0xf7) return lowTypes.charAt(code) else if (0x590 <= code && code <= 0x5f4) return "R" else if (0x600 <= code && code <= 0x6f9) return arabicTypes.charAt(code - 0x600) else if (0x6ee <= code && code <= 0x8ac) return "r" else if (0x2000 <= code && code <= 0x200b) return "w" else if (code == 0x200c) return "b" else return "L" } let bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/ let isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/ function BidiSpan(level, from, to) { this.level = level this.from = from; this.to = to } return function(str, direction) { let outerType = direction == "ltr" ? "L" : "R" if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) return false let len = str.length, types = [] for (let i = 0; i < len; ++i) types.push(charType(str.charCodeAt(i))) // W1. Examine each non-spacing mark (NSM) in the level run, and // change the type of the NSM to the type of the previous // character. If the NSM is at the start of the level run, it will // get the type of sor. for (let i = 0, prev = outerType; i < len; ++i) { let type = types[i] if (type == "m") types[i] = prev else prev = type } // W2. Search backwards from each instance of a European number // until the first strong type (R, L, AL, or sor) is found. If an // AL is found, change the type of the European number to Arabic // number. // W3. Change all ALs to R. for (let i = 0, cur = outerType; i < len; ++i) { let type = types[i] if (type == "1" && cur == "r") types[i] = "n" else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R" } } // W4. A single European separator between two European numbers // changes to a European number. A single common separator between // two numbers of the same type changes to that type. for (let i = 1, prev = types[0]; i < len - 1; ++i) { let type = types[i] if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1" else if (type == "," && prev == types[i+1] && (prev == "1" || prev == "n")) types[i] = prev prev = type } // W5. A sequence of European terminators adjacent to European // numbers changes to all European numbers. // W6. Otherwise, separators and terminators change to Other // Neutral. for (let i = 0; i < len; ++i) { let type = types[i] if (type == ",") types[i] = "N" else if (type == "%") { let end for (end = i + 1; end < len && types[end] == "%"; ++end) {} let replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N" for (let j = i; j < end; ++j) types[j] = replace i = end - 1 } } // W7. Search backwards from each instance of a European number // until the first strong type (R, L, or sor) is found. If an L is // found, then change the type of the European number to L. for (let i = 0, cur = outerType; i < len; ++i) { let type = types[i] if (cur == "L" && type == "1") types[i] = "L" else if (isStrong.test(type)) cur = type } // N1. A sequence of neutrals takes the direction of the // surrounding strong text if the text on both sides has the same // direction. European and Arabic numbers act as if they were R in // terms of their influence on neutrals. Start-of-level-run (sor) // and end-of-level-run (eor) are used at level run boundaries. // N2. Any remaining neutrals take the embedding direction. for (let i = 0; i < len; ++i) { if (isNeutral.test(types[i])) { let end for (end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} let before = (i ? types[i-1] : outerType) == "L" let after = (end < len ? types[end] : outerType) == "L" let replace = before == after ? (before ? "L" : "R") : outerType for (let j = i; j < end; ++j) types[j] = replace i = end - 1 } } // Here we depart from the documented algorithm, in order to avoid // building up an actual levels array. Since there are only three // levels (0, 1, 2) in an implementation that doesn't take // explicit embedding into account, we can build up the order on // the fly, without following the level-based algorithm. let order = [], m for (let i = 0; i < len;) { if (countsAsLeft.test(types[i])) { let start = i for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} order.push(new BidiSpan(0, start, i)) } else { let pos = i, at = order.length for (++i; i < len && types[i] != "L"; ++i) {} for (let j = pos; j < i;) { if (countsAsNum.test(types[j])) { if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)) let nstart = j for (++j; j < i && countsAsNum.test(types[j]); ++j) {} order.splice(at, 0, new BidiSpan(2, nstart, j)) pos = j } else ++j } if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)) } } if (direction == "ltr") { if (order[0].level == 1 && (m = str.match(/^\s+/))) { order[0].from = m[0].length order.unshift(new BidiSpan(0, 0, m[0].length)) } if (lst(order).level == 1 && (m = str.match(/\s+$/))) { lst(order).to -= m[0].length order.push(new BidiSpan(0, len - m[0].length, len)) } } return direction == "rtl" ? order.reverse() : order } })() // Get the bidi ordering for the given line (and cache it). Returns // false for lines that are fully left-to-right, and an array of // BidiSpan objects otherwise. export function getOrder(line, direction) { let order = line.order if (order == null) order = line.order = bidiOrdering(line.text, direction) return order } ================================================ FILE: third_party/CodeMirror/src/util/browser.js ================================================ // Kludges for bugs and behavior differences that can't be feature // detected are enabled based on userAgent etc sniffing. let userAgent = navigator.userAgent let platform = navigator.platform export let gecko = /gecko\/\d/i.test(userAgent) let ie_upto10 = /MSIE \d/.test(userAgent) let ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent) let edge = /Edge\/(\d+)/.exec(userAgent) export let ie = ie_upto10 || ie_11up || edge export let ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]) export let webkit = !edge && /WebKit\//.test(userAgent) let qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent) export let chrome = !edge && /Chrome\//.test(userAgent) export let presto = /Opera\//.test(userAgent) export let safari = /Apple Computer/.test(navigator.vendor) export let mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent) export let phantom = /PhantomJS/.test(userAgent) export let ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent) export let android = /Android/.test(userAgent) // This is woefully incomplete. Suggestions for alternative methods welcome. export let mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent) export let mac = ios || /Mac/.test(platform) export let chromeOS = /\bCrOS\b/.test(userAgent) export let windows = /win/i.test(platform) let presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/) if (presto_version) presto_version = Number(presto_version[1]) if (presto_version && presto_version >= 15) { presto = false; webkit = true } // Some browsers use the wrong event properties to signal cmd/ctrl on OS X export let flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)) export let captureRightClick = gecko || (ie && ie_version >= 9) ================================================ FILE: third_party/CodeMirror/src/util/dom.js ================================================ import { ie, ios } from "./browser.js" export function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } export let rmClass = function(node, cls) { let current = node.className let match = classTest(cls).exec(current) if (match) { let after = current.slice(match.index + match[0].length) node.className = current.slice(0, match.index) + (after ? match[1] + after : "") } } export function removeChildren(e) { for (let count = e.childNodes.length; count > 0; --count) e.removeChild(e.firstChild) return e } export function removeChildrenAndAdd(parent, e) { return removeChildren(parent).appendChild(e) } export function elt(tag, content, className, style) { let e = document.createElement(tag) if (className) e.className = className if (style) e.style.cssText = style if (typeof content == "string") e.appendChild(document.createTextNode(content)) else if (content) for (let i = 0; i < content.length; ++i) e.appendChild(content[i]) return e } // wrapper for elt, which removes the elt from the accessibility tree export function eltP(tag, content, className, style) { let e = elt(tag, content, className, style) e.setAttribute("role", "presentation") return e } export let range if (document.createRange) range = function(node, start, end, endNode) { let r = document.createRange() r.setEnd(endNode || node, end) r.setStart(node, start) return r } else range = function(node, start, end) { let r = document.body.createTextRange() try { r.moveToElementText(node.parentNode) } catch(e) { return r } r.collapse(true) r.moveEnd("character", end) r.moveStart("character", start) return r } export function contains(parent, child) { if (child.nodeType == 3) // Android browser always returns false when child is a textnode child = child.parentNode if (parent.contains) return parent.contains(child) do { if (child.nodeType == 11) child = child.host if (child == parent) return true } while (child = child.parentNode) } export function activeElt() { // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. // IE < 10 will throw when accessed while the page is loading or in an iframe. // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. let activeElement try { activeElement = document.activeElement } catch(e) { activeElement = document.body || null } while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) activeElement = activeElement.shadowRoot.activeElement return activeElement } export function addClass(node, cls) { let current = node.className if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls } export function joinClasses(a, b) { let as = a.split(" ") for (let i = 0; i < as.length; i++) if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i] return b } export let selectInput = function(node) { node.select() } if (ios) // Mobile Safari apparently has a bug where select() is broken. selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length } else if (ie) // Suppress mysterious IE10 errors selectInput = function(node) { try { node.select() } catch(_e) {} } ================================================ FILE: third_party/CodeMirror/src/util/event.js ================================================ import { mac } from "./browser.js" import { indexOf } from "./misc.js" // EVENT HANDLING // Lightweight event framework. on/off also work on DOM nodes, // registering native DOM handlers. const noHandlers = [] export let on = function(emitter, type, f) { if (emitter.addEventListener) { emitter.addEventListener(type, f, false) } else if (emitter.attachEvent) { emitter.attachEvent("on" + type, f) } else { let map = emitter._handlers || (emitter._handlers = {}) map[type] = (map[type] || noHandlers).concat(f) } } export function getHandlers(emitter, type) { return emitter._handlers && emitter._handlers[type] || noHandlers } export function off(emitter, type, f) { if (emitter.removeEventListener) { emitter.removeEventListener(type, f, false) } else if (emitter.detachEvent) { emitter.detachEvent("on" + type, f) } else { let map = emitter._handlers, arr = map && map[type] if (arr) { let index = indexOf(arr, f) if (index > -1) map[type] = arr.slice(0, index).concat(arr.slice(index + 1)) } } } export function signal(emitter, type /*, values...*/) { let handlers = getHandlers(emitter, type) if (!handlers.length) return let args = Array.prototype.slice.call(arguments, 2) for (let i = 0; i < handlers.length; ++i) handlers[i].apply(null, args) } // The DOM events that CodeMirror handles can be overridden by // registering a (non-DOM) handler on the editor for the event name, // and preventDefault-ing the event in that handler. export function signalDOMEvent(cm, e, override) { if (typeof e == "string") e = {type: e, preventDefault: function() { this.defaultPrevented = true }} signal(cm, override || e.type, cm, e) return e_defaultPrevented(e) || e.codemirrorIgnore } export function signalCursorActivity(cm) { let arr = cm._handlers && cm._handlers.cursorActivity if (!arr) return let set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []) for (let i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) set.push(arr[i]) } export function hasHandler(emitter, type) { return getHandlers(emitter, type).length > 0 } // Add on and off methods to a constructor's prototype, to make // registering events on such objects more convenient. export function eventMixin(ctor) { ctor.prototype.on = function(type, f) {on(this, type, f)} ctor.prototype.off = function(type, f) {off(this, type, f)} } // Due to the fact that we still support jurassic IE versions, some // compatibility wrappers are needed. export function e_preventDefault(e) { if (e.preventDefault) e.preventDefault() else e.returnValue = false } export function e_stopPropagation(e) { if (e.stopPropagation) e.stopPropagation() else e.cancelBubble = true } export function e_defaultPrevented(e) { return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false } export function e_stop(e) {e_preventDefault(e); e_stopPropagation(e)} export function e_target(e) {return e.target || e.srcElement} export function e_button(e) { let b = e.which if (b == null) { if (e.button & 1) b = 1 else if (e.button & 2) b = 3 else if (e.button & 4) b = 2 } if (mac && e.ctrlKey && b == 1) b = 3 return b } ================================================ FILE: third_party/CodeMirror/src/util/feature_detection.js ================================================ import { elt, range, removeChildren, removeChildrenAndAdd } from "./dom.js" import { ie, ie_version } from "./browser.js" // Detect drag-and-drop export let dragAndDrop = function() { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. if (ie && ie_version < 9) return false let div = elt('div') return "draggable" in div || "dragDrop" in div }() let zwspSupported export function zeroWidthElement(measure) { if (zwspSupported == null) { let test = elt("span", "\u200b") removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])) if (measure.firstChild.offsetHeight != 0) zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8) } let node = zwspSupported ? elt("span", "\u200b") : elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px") node.setAttribute("cm-text", "") return node } // Feature-detect IE's crummy client rect reporting for bidi text let badBidiRects export function hasBadBidiRects(measure) { if (badBidiRects != null) return badBidiRects let txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")) let r0 = range(txt, 0, 1).getBoundingClientRect() let r1 = range(txt, 1, 2).getBoundingClientRect() removeChildren(measure) if (!r0 || r0.left == r0.right) return false // Safari returns null in some cases (#2780) return badBidiRects = (r1.right - r0.right < 3) } // See if "".split is the broken IE version, if so, provide an // alternative way to split lines. export let splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? string => { let pos = 0, result = [], l = string.length while (pos <= l) { let nl = string.indexOf("\n", pos) if (nl == -1) nl = string.length let line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl) let rt = line.indexOf("\r") if (rt != -1) { result.push(line.slice(0, rt)) pos += rt + 1 } else { result.push(line) pos = nl + 1 } } return result } : string => string.split(/\r\n?|\n/) export let hasSelection = window.getSelection ? te => { try { return te.selectionStart != te.selectionEnd } catch(e) { return false } } : te => { let range try {range = te.ownerDocument.selection.createRange()} catch(e) {} if (!range || range.parentElement() != te) return false return range.compareEndPoints("StartToEnd", range) != 0 } export let hasCopyEvent = (() => { let e = elt("div") if ("oncopy" in e) return true e.setAttribute("oncopy", "return;") return typeof e.oncopy == "function" })() let badZoomedRects = null export function hasBadZoomedRects(measure) { if (badZoomedRects != null) return badZoomedRects let node = removeChildrenAndAdd(measure, elt("span", "x")) let normal = node.getBoundingClientRect() let fromRange = range(node, 0, 1).getBoundingClientRect() return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 } ================================================ FILE: third_party/CodeMirror/src/util/misc.js ================================================ export function bind(f) { let args = Array.prototype.slice.call(arguments, 1) return function(){return f.apply(null, args)} } export function copyObj(obj, target, overwrite) { if (!target) target = {} for (let prop in obj) if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) target[prop] = obj[prop] return target } // Counts the column offset in a string, taking tabs into account. // Used mostly to find indentation. export function countColumn(string, end, tabSize, startIndex, startValue) { if (end == null) { end = string.search(/[^\s\u00a0]/) if (end == -1) end = string.length } for (let i = startIndex || 0, n = startValue || 0;;) { let nextTab = string.indexOf("\t", i) if (nextTab < 0 || nextTab >= end) return n + (end - i) n += nextTab - i n += tabSize - (n % tabSize) i = nextTab + 1 } } export class Delayed { constructor() {this.id = null} set(ms, f) { clearTimeout(this.id) this.id = setTimeout(f, ms) } } export function indexOf(array, elt) { for (let i = 0; i < array.length; ++i) if (array[i] == elt) return i return -1 } // Number of pixels added to scroller and sizer to hide scrollbar export let scrollerGap = 30 // Returned or thrown by various protocols to signal 'I'm not // handling this'. export let Pass = {toString: function(){return "CodeMirror.Pass"}} // Reused option objects for setSelection & friends export let sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"} // The inverse of countColumn -- find the offset that corresponds to // a particular column. export function findColumn(string, goal, tabSize) { for (let pos = 0, col = 0;;) { let nextTab = string.indexOf("\t", pos) if (nextTab == -1) nextTab = string.length let skipped = nextTab - pos if (nextTab == string.length || col + skipped >= goal) return pos + Math.min(skipped, goal - col) col += nextTab - pos col += tabSize - (col % tabSize) pos = nextTab + 1 if (col >= goal) return pos } } let spaceStrs = [""] export function spaceStr(n) { while (spaceStrs.length <= n) spaceStrs.push(lst(spaceStrs) + " ") return spaceStrs[n] } export function lst(arr) { return arr[arr.length-1] } export function map(array, f) { let out = [] for (let i = 0; i < array.length; i++) out[i] = f(array[i], i) return out } export function insertSorted(array, value, score) { let pos = 0, priority = score(value) while (pos < array.length && score(array[pos]) <= priority) pos++ array.splice(pos, 0, value) } function nothing() {} export function createObj(base, props) { let inst if (Object.create) { inst = Object.create(base) } else { nothing.prototype = base inst = new nothing() } if (props) copyObj(props, inst) return inst } let nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/ export function isWordCharBasic(ch) { return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) } export function isWordChar(ch, helper) { if (!helper) return isWordCharBasic(ch) if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true return helper.test(ch) } export function isEmpty(obj) { for (let n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false return true } // Extending unicode characters. A series of a non-extending char + // any number of extending chars is treated as a single unit as far // as editing and measuring is concerned. This is not fully correct, // since some scripts/fonts/browsers also treat other configurations // of code points as a group. let 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]/ export function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. export function skipExtendingChars(str, pos, dir) { while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) pos += dir return pos } // Returns the value from the range [`from`; `to`] that satisfies // `pred` and is closest to `from`. Assumes that at least `to` // satisfies `pred`. Supports `from` being greater than `to`. export function findFirst(pred, from, to) { // At any point we are certain `to` satisfies `pred`, don't know // whether `from` does. let dir = from > to ? -1 : 1 for (;;) { if (from == to) return from let midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF) if (mid == from) return pred(mid) ? from : to if (pred(mid)) to = mid else from = mid + dir } } ================================================ FILE: third_party/CodeMirror/src/util/operation_group.js ================================================ import { getHandlers } from "./event.js" let operationGroup = null export function pushOperation(op) { if (operationGroup) { operationGroup.ops.push(op) } else { op.ownsGroup = operationGroup = { ops: [op], delayedCallbacks: [] } } } function fireCallbacksForOps(group) { // Calls delayed callbacks and cursorActivity handlers until no // new ones appear let callbacks = group.delayedCallbacks, i = 0 do { for (; i < callbacks.length; i++) callbacks[i].call(null) for (let j = 0; j < group.ops.length; j++) { let op = group.ops[j] if (op.cursorActivityHandlers) while (op.cursorActivityCalled < op.cursorActivityHandlers.length) op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm) } } while (i < callbacks.length) } export function finishOperation(op, endCb) { let group = op.ownsGroup if (!group) return try { fireCallbacksForOps(group) } finally { operationGroup = null endCb(group) } } let orphanDelayedCallbacks = null // Often, we want to signal events at a point where we are in the // middle of some work, but don't want the handler to start calling // other methods on the editor, which might be in an inconsistent // state or simply not expect any other events to happen. // signalLater looks whether there are any handlers, and schedules // them to be executed when the last operation ends, or, if no // operation is active, when a timeout fires. export function signalLater(emitter, type /*, values...*/) { let arr = getHandlers(emitter, type) if (!arr.length) return let args = Array.prototype.slice.call(arguments, 2), list if (operationGroup) { list = operationGroup.delayedCallbacks } else if (orphanDelayedCallbacks) { list = orphanDelayedCallbacks } else { list = orphanDelayedCallbacks = [] setTimeout(fireOrphanDelayed, 0) } for (let i = 0; i < arr.length; ++i) list.push(() => arr[i].apply(null, args)) } function fireOrphanDelayed() { let delayed = orphanDelayedCallbacks orphanDelayedCallbacks = null for (let i = 0; i < delayed.length; ++i) delayed[i]() } ================================================ FILE: third_party/CodeMirror/test/comment_test.js ================================================ namespace = "comment_"; (function() { function test(name, mode, run, before, after) { return testCM(name, function(cm) { run(cm); eq(cm.getValue(), after); }, {value: before, mode: mode}); } var simpleProg = "function foo() {\n return bar;\n}"; var inlineBlock = "foo(/* bar */ true);"; var inlineBlocks = "foo(/* bar */ true, /* baz */ false);"; var multiLineInlineBlock = ["above();", "foo(/* bar */ true);", "below();"]; test("block", "javascript", function(cm) { cm.blockComment(Pos(0, 3), Pos(3, 0), {blockCommentLead: " *"}); }, simpleProg + "\n", "/* function foo() {\n * return bar;\n * }\n */"); test("blockToggle", "javascript", function(cm) { cm.blockComment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"}); cm.uncomment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"}); }, simpleProg, simpleProg); test("blockToggle2", "javascript", function(cm) { cm.setCursor({line: 0, ch: 7 /* inside the block comment */}); cm.execCommand("toggleComment"); }, inlineBlock, "foo(bar true);"); // This test should work but currently fails. // test("blockToggle3", "javascript", function(cm) { // cm.setCursor({line: 0, ch: 7 /* inside the first block comment */}); // cm.execCommand("toggleComment"); // }, inlineBlocks, "foo(bar true, /* baz */ false);"); test("line", "javascript", function(cm) { cm.lineComment(Pos(1, 1), Pos(1, 1)); }, simpleProg, "function foo() {\n// return bar;\n}"); test("lineToggle", "javascript", function(cm) { cm.lineComment(Pos(0, 0), Pos(2, 1)); cm.uncomment(Pos(0, 0), Pos(2, 1)); }, simpleProg, simpleProg); test("fallbackToBlock", "css", function(cm) { cm.lineComment(Pos(0, 0), Pos(2, 1)); }, "html {\n border: none;\n}", "/* html {\n border: none;\n} */"); test("fallbackToLine", "ruby", function(cm) { cm.blockComment(Pos(0, 0), Pos(1)); }, "def blah()\n return hah\n", "# def blah()\n# return hah\n"); test("ignoreExternalBlockComments", "javascript", function(cm) { cm.execCommand("toggleComment"); }, inlineBlocks, "// " + inlineBlocks); test("ignoreExternalBlockComments2", "javascript", function(cm) { cm.setCursor({line: 0, ch: null /* eol */}); cm.execCommand("toggleComment"); }, inlineBlocks, "// " + inlineBlocks); test("ignoreExternalBlockCommentsMultiLineAbove", "javascript", function(cm) { cm.setSelection({line: 0, ch: 0}, {line: 1, ch: 1}); cm.execCommand("toggleComment"); }, multiLineInlineBlock.join("\n"), ["// " + multiLineInlineBlock[0], "// " + multiLineInlineBlock[1], multiLineInlineBlock[2]].join("\n")); test("ignoreExternalBlockCommentsMultiLineBelow", "javascript", function(cm) { cm.setSelection({line: 1, ch: 13 /* after end of block comment */}, {line: 2, ch: 1}); cm.execCommand("toggleComment"); }, multiLineInlineBlock.join("\n"), [multiLineInlineBlock[0], "// " + multiLineInlineBlock[1], "// " + multiLineInlineBlock[2]].join("\n")); test("commentRange", "javascript", function(cm) { cm.blockComment(Pos(1, 2), Pos(1, 13), {fullLines: false}); }, simpleProg, "function foo() {\n /*return bar;*/\n}"); test("indented", "javascript", function(cm) { cm.lineComment(Pos(1, 0), Pos(2), {indent: true}); }, simpleProg, "function foo() {\n// return bar;\n// }"); test("singleEmptyLine", "javascript", function(cm) { cm.setCursor(1); cm.execCommand("toggleComment"); }, "a;\n\nb;", "a;\n// \nb;"); test("dontMessWithStrings", "javascript", function(cm) { cm.execCommand("toggleComment"); }, "console.log(\"/*string*/\");", "// console.log(\"/*string*/\");"); test("dontMessWithStrings2", "javascript", function(cm) { cm.execCommand("toggleComment"); }, "console.log(\"// string\");", "// console.log(\"// string\");"); test("dontMessWithStrings3", "javascript", function(cm) { cm.execCommand("toggleComment"); }, "// console.log(\"// string\");", "console.log(\"// string\");"); test("includeLastLine", "javascript", function(cm) { cm.execCommand("selectAll") cm.execCommand("toggleComment") }, "// foo\n// bar\nbaz", "// // foo\n// // bar\n// baz") test("uncommentWithTrailingBlockEnd", "xml", function(cm) { cm.execCommand("toggleComment") }, " -->", "foo -->") test("dontCommentInComment", "xml", function(cm) { cm.setCursor(1, 0) cm.execCommand("toggleComment") }, "", "") })(); ================================================ FILE: third_party/CodeMirror/test/contenteditable_test.js ================================================ (function() { "use strict"; namespace = "contenteditable_"; var Pos = CodeMirror.Pos function findTextNode(dom, text) { if (dom instanceof CodeMirror) dom = dom.getInputField() if (dom.nodeType == 1) { for (var ch = dom.firstChild; ch; ch = ch.nextSibling) { var found = findTextNode(ch, text) if (found) return found } } else if (dom.nodeType == 3 && dom.nodeValue == text) { return dom } } function lineElt(node) { for (;;) { var parent = node.parentNode if (/CodeMirror-code/.test(parent.className)) return node node = parent } } testCM("insert_text", function(cm) { findTextNode(cm, "foobar").nodeValue = "foo bar" cm.display.input.updateFromDOM() eq(cm.getValue(), "foo bar") }, {inputStyle: "contenteditable", value: "foobar"}) testCM("split_line", function(cm) { cm.setSelection(Pos(2, 3)) var node = findTextNode(cm, "foobar") node.nodeValue = "foo" var lineNode = lineElt(node) lineNode.parentNode.insertBefore(document.createElement("pre"), lineNode.nextSibling).textContent = "bar" cm.display.input.updateFromDOM() eq(cm.getValue(), "one\ntwo\nfoo\nbar\nthree\nfour\n") }, {inputStyle: "contenteditable", value: "one\ntwo\nfoobar\nthree\nfour\n"}) testCM("join_line", function(cm) { cm.setSelection(Pos(2, 3)) var node = findTextNode(cm, "foo") node.nodeValue = "foobar" var lineNode = lineElt(node) lineNode.parentNode.removeChild(lineNode.nextSibling) cm.display.input.updateFromDOM() eq(cm.getValue(), "one\ntwo\nfoobar\nthree\nfour\n") }, {inputStyle: "contenteditable", value: "one\ntwo\nfoo\nbar\nthree\nfour\n"}) testCM("delete_multiple", function(cm) { cm.setSelection(Pos(1, 3), Pos(4, 0)) var text = findTextNode(cm, "two"), startLine = lineElt(text) for (var i = 0; i < 3; i++) startLine.parentNode.removeChild(startLine.nextSibling) text.nodeValue = "twothree" cm.display.input.updateFromDOM() eq(cm.getValue(), "one\ntwothree\nfour\n") }, {inputStyle: "contenteditable", value: "one\ntwo\nfoo\nbar\nthree\nfour\n"}) testCM("ambiguous_diff_middle", function(cm) { cm.setSelection(Pos(0, 2)) findTextNode(cm, "baah").nodeValue = "baaah" cm.display.input.updateFromDOM() eqCharPos(cm.getCursor(), Pos(0, 3)) }, {inputStyle: "contenteditable", value: "baah"}) testCM("ambiguous_diff_start", function(cm) { cm.setSelection(Pos(0, 1)) findTextNode(cm, "baah").nodeValue = "baaah" cm.display.input.updateFromDOM() eqCharPos(cm.getCursor(), Pos(0, 2)) }, {inputStyle: "contenteditable", value: "baah"}) testCM("ambiguous_diff_end", function(cm) { cm.setSelection(Pos(0, 3)) findTextNode(cm, "baah").nodeValue = "baaah" cm.display.input.updateFromDOM() eqCharPos(cm.getCursor(), Pos(0, 4)) }, {inputStyle: "contenteditable", value: "baah"}) testCM("force_redraw", function(cm) { findTextNode(cm, "foo").parentNode.appendChild(document.createElement("hr")).className = "inserted" cm.display.input.updateFromDOM() eq(byClassName(cm.getInputField(), "inserted").length, 0) }, {inputStyle: "contenteditable", value: "foo"}) testCM("type_on_empty_line", function(cm) { cm.setSelection(Pos(1, 0)) findTextNode(cm, "\u200b").nodeValue += "hello" cm.display.input.updateFromDOM() eq(cm.getValue(), "foo\nhello\nbar") }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) testCM("type_after_empty_line", function(cm) { cm.setSelection(Pos(2, 0)) findTextNode(cm, "bar").nodeValue = "hellobar" cm.display.input.updateFromDOM() eq(cm.getValue(), "foo\n\nhellobar") }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) testCM("type_before_empty_line", function(cm) { cm.setSelection(Pos(0, 3)) findTextNode(cm, "foo").nodeValue = "foohello" cm.display.input.updateFromDOM() eq(cm.getValue(), "foohello\n\nbar") }, {inputStyle: "contenteditable", value: "foo\n\nbar"}) })(); ================================================ FILE: third_party/CodeMirror/test/doc_test.js ================================================ (function() { // A minilanguage for instantiating linked CodeMirror instances and Docs function instantiateSpec(spec, place, opts) { var names = {}, pos = 0, l = spec.length, editors = []; while (spec) { var m = spec.match(/^(\w+)(\*?)(?:='([^\']*)'|<(~?)(\w+)(?:\/(\d+)-(\d+))?)\s*/); var name = m[1], isDoc = m[2], cur; if (m[3]) { cur = isDoc ? CodeMirror.Doc(m[3]) : CodeMirror(place, clone(opts, {value: m[3]})); } else { var other = m[5]; if (!names.hasOwnProperty(other)) { names[other] = editors.length; editors.push(CodeMirror(place, opts)); } var doc = editors[names[other]].linkedDoc({ sharedHist: !m[4], from: m[6] ? Number(m[6]) : null, to: m[7] ? Number(m[7]) : null }); cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc})); } names[name] = editors.length; editors.push(cur); spec = spec.slice(m[0].length); } return editors; } function clone(obj, props) { if (!obj) return; clone.prototype = obj; var inst = new clone(); if (props) for (var n in props) if (props.hasOwnProperty(n)) inst[n] = props[n]; return inst; } function eqAll(val) { var end = arguments.length, msg = null; if (typeof arguments[end-1] == "string") msg = arguments[--end]; if (i == end) throw new Error("No editors provided to eqAll"); for (var i = 1; i < end; ++i) eq(arguments[i].getValue(), val, msg) } function testDoc(name, spec, run, opts, expectFail) { if (!opts) opts = {}; return test("doc_" + name, function() { var place = document.getElementById("testground"); var editors = instantiateSpec(spec, place, opts); var successful = false; try { run.apply(null, editors); successful = true; } finally { if (!successful || verbose) { place.style.visibility = "visible"; } else { for (var i = 0; i < editors.length; ++i) if (editors[i] instanceof CodeMirror) place.removeChild(editors[i].getWrapperElement()); } } }, expectFail); } var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); function testBasic(a, b) { eqAll("x", a, b); a.setValue("hey"); eqAll("hey", a, b); b.setValue("wow"); eqAll("wow", a, b); a.replaceRange("u\nv\nw", Pos(0, 3)); b.replaceRange("i", Pos(0, 4)); b.replaceRange("j", Pos(2, 1)); eqAll("wowui\nv\nwj", a, b); } testDoc("basic", "A='x' B 0, "not at left"); is(pos.top > 0, "not at top"); }); testDoc("copyDoc", "A='u'", function(a) { var copy = a.getDoc().copy(true); a.setValue("foo"); copy.setValue("bar"); var old = a.swapDoc(copy); eq(a.getValue(), "bar"); a.undo(); eq(a.getValue(), "u"); a.swapDoc(old); eq(a.getValue(), "foo"); eq(old.historySize().undo, 1); eq(old.copy(false).historySize().undo, 0); }); testDoc("docKeepsMode", "A='1+1'", function(a) { var other = CodeMirror.Doc("hi", "text/x-markdown"); a.setOption("mode", "text/javascript"); var old = a.swapDoc(other); eq(a.getOption("mode"), "text/x-markdown"); eq(a.getMode().name, "markdown"); a.swapDoc(old); eq(a.getOption("mode"), "text/javascript"); eq(a.getMode().name, "javascript"); }); testDoc("subview", "A='1\n2\n3\n4\n5' B<~A/1-3", function(a, b) { eq(b.getValue(), "2\n3"); eq(b.firstLine(), 1); b.setCursor(Pos(4)); eqCharPos(b.getCursor(), Pos(2, 1)); a.replaceRange("-1\n0\n", Pos(0, 0)); eq(b.firstLine(), 3); eqCharPos(b.getCursor(), Pos(4, 1)); a.undo(); eqCharPos(b.getCursor(), Pos(2, 1)); b.replaceRange("oyoy\n", Pos(2, 0)); eq(a.getValue(), "1\n2\noyoy\n3\n4\n5"); b.undo(); eq(a.getValue(), "1\n2\n3\n4\n5"); }); testDoc("subviewEditOnBoundary", "A='11\n22\n33\n44\n55' B<~A/1-4", function(a, b) { a.replaceRange("x\nyy\nz", Pos(0, 1), Pos(2, 1)); eq(b.firstLine(), 2); eq(b.lineCount(), 2); eq(b.getValue(), "z3\n44"); a.replaceRange("q\nrr\ns", Pos(3, 1), Pos(4, 1)); eq(b.firstLine(), 2); eq(b.getValue(), "z3\n4q"); eq(a.getValue(), "1x\nyy\nz3\n4q\nrr\ns5"); a.execCommand("selectAll"); a.replaceSelection("!"); eqAll("!", a, b); }); testDoc("sharedMarker", "A='ab\ncd\nef\ngh' B 500){ totalTime = 0; delay = 50; } setTimeout(function(){step(i + 1);}, delay); } else { // Quit tests running = false; return null; } } step(0); } function label(str, msg) { if (msg) return str + " (" + msg + ")"; return str; } function eq(a, b, msg) { if (a != b) throw new Failure(label(a + " != " + b, msg)); } function near(a, b, margin, msg) { if (Math.abs(a - b) > margin) throw new Failure(label(a + " is not close to " + b + " (" + margin + ")", msg)); } function eqCharPos(a, b, msg) { function str(p) { return "{line:" + p.line + ",ch:" + p.ch + ",sticky:" + p.sticky + "}"; } if (a == b) return; if (a == null) throw new Failure(label("comparing null to " + str(b), msg)); if (b == null) throw new Failure(label("comparing " + str(a) + " to null", msg)); if (a.line != b.line || a.ch != b.ch) throw new Failure(label(str(a) + " != " + str(b), msg)); } function eqCursorPos(a, b, msg) { eqCharPos(a, b, msg); if (a) eq(a.sticky, b.sticky, msg ? msg + ' (sticky)' : 'sticky'); } function is(a, msg) { if (!a) throw new Failure(label("assertion failed", msg)); } function countTests() { if (!filters.length) return tests.length; var sum = 0; for (var i = 0; i < tests.length; ++i) { var name = tests[i].name; for (var j = 0; j < filters.length; j++) { if (name.match(filters[j])) { ++sum; break; } } } return sum; } function parseTestFilter(s) { if (/_\*$/.test(s)) return new RegExp("^" + s.slice(0, s.length - 2), "i"); else return new RegExp(s, "i"); } ================================================ FILE: third_party/CodeMirror/test/emacs_test.js ================================================ (function() { "use strict"; var Pos = CodeMirror.Pos; namespace = "emacs_"; var eventCache = {}; function fakeEvent(keyName) { var event = eventCache[key]; if (event) return event; var ctrl, shift, alt; var key = keyName.replace(/\w+-/g, function(type) { if (type == "Ctrl-") ctrl = true; else if (type == "Alt-") alt = true; else if (type == "Shift-") shift = true; return ""; }); var code; for (var c in CodeMirror.keyNames) if (CodeMirror.keyNames[c] == key) { code = c; break; } if (code == null) throw new Error("Unknown key: " + key); return eventCache[keyName] = { type: "keydown", keyCode: code, ctrlKey: ctrl, shiftKey: shift, altKey: alt, preventDefault: function(){}, stopPropagation: function(){} }; } function sim(name, start /*, actions... */) { var keys = Array.prototype.slice.call(arguments, 2); testCM(name, function(cm) { for (var i = 0; i < keys.length; ++i) { var cur = keys[i]; if (cur instanceof Pos) cm.setCursor(cur); else if (cur.call) cur(cm); else cm.triggerOnKeyDown(fakeEvent(cur)); } }, {keyMap: "emacs", value: start, mode: "javascript"}); } function at(line, ch, sticky) { return function(cm) { eqCursorPos(cm.getCursor(), Pos(line, ch, sticky)); }; } function txt(str) { return function(cm) { eq(cm.getValue(), str); }; } sim("motionHSimple", "abc", "Ctrl-F", "Ctrl-F", "Ctrl-B", at(0, 1, "after")); sim("motionHMulti", "abcde", "Ctrl-4", "Ctrl-F", at(0, 4, "before"), "Ctrl--", "Ctrl-2", "Ctrl-F", at(0, 2, "after"), "Ctrl-5", "Ctrl-B", at(0, 0, "after")); sim("motionHWord", "abc. def ghi", "Alt-F", at(0, 3, "before"), "Alt-F", at(0, 8, "before"), "Ctrl-B", "Alt-B", at(0, 5, "after"), "Alt-B", at(0, 0, "after")); sim("motionHWordMulti", "abc. def ghi ", "Ctrl-3", "Alt-F", at(0, 12, "before"), "Ctrl-2", "Alt-B", at(0, 5, "after"), "Ctrl--", "Alt-B", at(0, 8, "before")); sim("motionVSimple", "a\nb\nc\n", "Ctrl-N", "Ctrl-N", "Ctrl-P", at(1, 0, "after")); sim("motionVMulti", "a\nb\nc\nd\ne\n", "Ctrl-2", "Ctrl-N", at(2, 0, "after"), "Ctrl-F", "Ctrl--", "Ctrl-N", at(1, 1, "before"), "Ctrl--", "Ctrl-3", "Ctrl-P", at(4, 1, "before")); sim("killYank", "abc\ndef\nghi", "Ctrl-F", "Ctrl-Space", "Ctrl-N", "Ctrl-N", "Ctrl-W", "Ctrl-E", "Ctrl-Y", txt("ahibc\ndef\ng")); sim("killRing", "abcdef", "Ctrl-Space", "Ctrl-F", "Ctrl-W", "Ctrl-Space", "Ctrl-F", "Ctrl-W", "Ctrl-Y", "Alt-Y", txt("acdef")); sim("copyYank", "abcd", "Ctrl-Space", "Ctrl-E", "Alt-W", "Ctrl-Y", txt("abcdabcd")); sim("killLineSimple", "foo\nbar", "Ctrl-F", "Ctrl-K", txt("f\nbar")); sim("killLineEmptyLine", "foo\n \nbar", "Ctrl-N", "Ctrl-K", txt("foo\nbar")); sim("killLineMulti", "foo\nbar\nbaz", "Ctrl-F", "Ctrl-F", "Ctrl-K", "Ctrl-K", "Ctrl-K", "Ctrl-A", "Ctrl-Y", txt("o\nbarfo\nbaz")); sim("moveByParagraph", "abc\ndef\n\n\nhij\nklm\n\n", "Ctrl-F", "Ctrl-Down", at(2, 0), "Ctrl-Down", at(6, 0), "Ctrl-N", "Ctrl-Up", at(3, 0), "Ctrl-Up", at(0, 0), Pos(1, 2), "Ctrl-Down", at(2, 0), Pos(4, 2), "Ctrl-Up", at(3, 0)); sim("moveByParagraphMulti", "abc\n\ndef\n\nhij\n\nklm", "Ctrl-U", "2", "Ctrl-Down", at(3, 0), "Shift-Alt-.", "Ctrl-3", "Ctrl-Up", at(1, 0)); sim("moveBySentence", "sentence one! sentence\ntwo\n\nparagraph two", "Alt-E", at(0, 13), "Alt-E", at(1, 3), "Ctrl-F", "Alt-A", at(0, 13)); sim("moveByExpr", "function foo(a, b) {}", "Ctrl-Alt-F", at(0, 8), "Ctrl-Alt-F", at(0, 12), "Ctrl-Alt-F", at(0, 18), "Ctrl-Alt-B", at(0, 12), "Ctrl-Alt-B", at(0, 9)); sim("moveByExprMulti", "foo bar baz bug", "Ctrl-2", "Ctrl-Alt-F", at(0, 7), "Ctrl--", "Ctrl-Alt-F", at(0, 4), "Ctrl--", "Ctrl-2", "Ctrl-Alt-B", at(0, 11)); sim("delExpr", "var x = [\n a,\n b\n c\n];", Pos(0, 8), "Ctrl-Alt-K", txt("var x = ;"), "Ctrl-/", Pos(4, 1), "Ctrl-Alt-Backspace", txt("var x = ;")); sim("delExprMulti", "foo bar baz", "Ctrl-2", "Ctrl-Alt-K", txt(" baz"), "Ctrl-/", "Ctrl-E", "Ctrl-2", "Ctrl-Alt-Backspace", txt("foo ")); sim("justOneSpace", "hi bye ", Pos(0, 4), "Alt-Space", txt("hi bye "), Pos(0, 4), "Alt-Space", txt("hi b ye "), "Ctrl-A", "Alt-Space", "Ctrl-E", "Alt-Space", txt(" hi b ye ")); sim("openLine", "foo bar", "Alt-F", "Ctrl-O", txt("foo\n bar")) sim("transposeChar", "abcd\ne", "Ctrl-F", "Ctrl-T", "Ctrl-T", txt("bcad\ne"), at(0, 3), "Ctrl-F", "Ctrl-T", "Ctrl-T", "Ctrl-T", txt("bcda\ne"), at(0, 4), "Ctrl-F", "Ctrl-T", txt("bcde\na"), at(1, 1)); sim("manipWordCase", "foo BAR bAZ", "Alt-C", "Alt-L", "Alt-U", txt("Foo bar BAZ"), "Ctrl-A", "Alt-U", "Alt-L", "Alt-C", txt("FOO bar Baz")); sim("manipWordCaseMulti", "foo Bar bAz", "Ctrl-2", "Alt-U", txt("FOO BAR bAz"), "Ctrl-A", "Ctrl-3", "Alt-C", txt("Foo Bar Baz")); sim("upExpr", "foo {\n bar[];\n baz(blah);\n}", Pos(2, 7), "Ctrl-Alt-U", at(2, 5), "Ctrl-Alt-U", at(0, 4)); sim("transposeExpr", "do foo[bar] dah", Pos(0, 6), "Ctrl-Alt-T", txt("do [bar]foo dah")); sim("clearMark", "abcde", Pos(0, 2), "Ctrl-Space", "Ctrl-F", "Ctrl-F", "Ctrl-G", "Ctrl-W", txt("abcde")); sim("delRegion", "abcde", "Ctrl-Space", "Ctrl-F", "Ctrl-F", "Delete", txt("cde")); sim("backspaceRegion", "abcde", "Ctrl-Space", "Ctrl-F", "Ctrl-F", "Backspace", txt("cde")); sim("backspaceDoesntAddToRing", "foobar", "Ctrl-F", "Ctrl-F", "Ctrl-F", "Ctrl-K", "Backspace", "Backspace", "Ctrl-Y", txt("fbar")); testCM("save", function(cm) { var saved = false; CodeMirror.commands.save = function(cm) { saved = cm.getValue(); }; cm.triggerOnKeyDown(fakeEvent("Ctrl-X")); cm.triggerOnKeyDown(fakeEvent("Ctrl-S")); is(saved, "hi"); }, {value: "hi", keyMap: "emacs"}); testCM("gotoInvalidLineFloat", function(cm) { cm.openDialog = function(_, cb) { cb("2.2"); }; cm.triggerOnKeyDown(fakeEvent("Alt-G")); cm.triggerOnKeyDown(fakeEvent("G")); }, {value: "1\n2\n3\n4", keyMap: "emacs"}); })(); ================================================ FILE: third_party/CodeMirror/test/html-hint-test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var Pos = CodeMirror.Pos; namespace = "html-hint_"; testData =[ { name: "html-element", value: "\n"] }, { name: "linkref-attribute", value: "\n", list: [""] } ]; function escapeHtmlList(o) { return '' + JSON.stringify(o.list,null,2) .replace(//g, ">") + '' } function test(name, spec) { testCM(name, function(cm) { cm.setValue(spec.value); cm.setCursor(spec.cursor); var completion = CodeMirror.hint.html(cm); if (!deepCompare(completion.list, spec.list)) throw new Failure("Wrong completion results. Got" + escapeHtmlList(completion) +" but expected" + escapeHtmlList(spec)); eqCharPos(completion.from, spec.from,'from-failed'); eqCharPos(completion.to, spec.to, 'to-failed'); }, { value: spec.value, mode: spec.mode || "text/html" }); } testData.forEach(function (value) { // Use sane defaults var lines = value.value.split(/\n/); value.to = value.pos || Pos(lines.length-1, lines[lines.length-1].length); value.from = value.from || Pos(lines.length-1,0); value.cursor = value.cursor || value.to; var name = value.name ||value.value; test(name,value) }); function deepCompare(a, b) { if (a === b) return true; if (!(a && typeof a === "object") || !(b && typeof b === "object")) return false; var array = a instanceof Array if ((b instanceof Array) !== array) return false; if (array) { if (a.length !== b.length) return false; for (var i = 0; i < a.length; i++) if (!deepCompare(a[i], b[i])) return false } else { for (var p in a) if (!(p in b) || !deepCompare(a[p], b[p])) return false; for (var p in b) if (!(p in a)) return false } return true } })(); ================================================ FILE: third_party/CodeMirror/test/index.html ================================================ CodeMirror: Test Suite

    Test Suite

    A limited set of programmatic sanity tests for CodeMirror.

    Ran 0 of 0 tests

    Please enable JavaScript...

    ================================================ FILE: third_party/CodeMirror/test/lint.js ================================================ var blint = require("blint"); ["mode", "lib", "addon", "keymap"].forEach(function(dir) { blint.checkDir(dir, { browser: true, allowedGlobals: ["CodeMirror", "define", "test", "requirejs"], ecmaVersion: 5, tabs: dir == "lib" }); }); ["src"].forEach(function(dir) { blint.checkDir(dir, { browser: true, ecmaVersion: 6, semicolons: false }); }); module.exports = {ok: blint.success()}; ================================================ FILE: third_party/CodeMirror/test/mode_test.css ================================================ .mt-output .mt-token { border: 1px solid #ddd; white-space: pre; font-family: "Consolas", monospace; text-align: center; } .mt-output .mt-style { font-size: x-small; } .mt-output .mt-state { font-size: x-small; vertical-align: top; } .mt-output .mt-state-row { display: none; } .mt-state-unhide .mt-output .mt-state-row { display: table-row; } ================================================ FILE: third_party/CodeMirror/test/mode_test.js ================================================ /** * Helper to test CodeMirror highlighting modes. It pretty prints output of the * highlighter and can check against expected styles. * * Mode tests are registered by calling test.mode(testName, mode, * tokens), where mode is a mode object as returned by * CodeMirror.getMode, and tokens is an array of lines that make up * the test. * * These lines are strings, in which styled stretches of code are * enclosed in brackets `[]`, and prefixed by their style. For * example, `[keyword if]`. Brackets in the code itself must be * duplicated to prevent them from being interpreted as token * boundaries. For example `a[[i]]` for `a[i]`. If a token has * multiple styles, the styles must be separated by ampersands, for * example `[tag&error ]`. * * See the test.js files in the css, markdown, gfm, and stex mode * directories for examples. */ (function() { function findSingle(str, pos, ch) { for (;;) { var found = str.indexOf(ch, pos); if (found == -1) return null; if (str.charAt(found + 1) != ch) return found; pos = found + 2; } } var styleName = /[\w&-_]+/g; function parseTokens(strs) { var tokens = [], plain = ""; for (var i = 0; i < strs.length; ++i) { if (i) plain += "\n"; var str = strs[i], pos = 0; while (pos < str.length) { var style = null, text; if (str.charAt(pos) == "[" && str.charAt(pos+1) != "[") { styleName.lastIndex = pos + 1; var m = styleName.exec(str); style = m[0].replace(/&/g, " "); var textStart = pos + style.length + 2; var end = findSingle(str, textStart, "]"); if (end == null) throw new Error("Unterminated token at " + pos + " in '" + str + "'" + style); text = str.slice(textStart, end); pos = end + 1; } else { var end = findSingle(str, pos, "["); if (end == null) end = str.length; text = str.slice(pos, end); pos = end; } text = text.replace(/\[\[|\]\]/g, function(s) {return s.charAt(0);}); tokens.push({style: style, text: text}); plain += text; } } return {tokens: tokens, plain: plain}; } test.mode = function(name, mode, tokens, modeName) { var data = parseTokens(tokens); return test((modeName || mode.name) + "_" + name, function() { return compare(data.plain, data.tokens, mode); }); }; function esc(str) { return str.replace(/&/g, '&').replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); } function compare(text, expected, mode) { var expectedOutput = []; for (var i = 0; i < expected.length; ++i) { var sty = expected[i].style; if (sty && sty.indexOf(" ")) sty = sty.split(' ').sort().join(' '); expectedOutput.push({style: sty, text: expected[i].text}); } var observedOutput = highlight(text, mode); var s = ""; var diff = highlightOutputsDifferent(expectedOutput, observedOutput); if (diff != null) { s += '
    '; s += '
    ' + esc(text) + '
    '; s += '
    '; s += 'expected:'; s += prettyPrintOutputTable(expectedOutput, diff); s += 'observed: [display states]'; s += prettyPrintOutputTable(observedOutput, diff); s += '
    '; s += '
    '; } if (observedOutput.indentFailures) { for (var i = 0; i < observedOutput.indentFailures.length; i++) s += "
    " + esc(observedOutput.indentFailures[i]) + "
    "; } if (s) throw new Failure(s); } function stringify(obj) { function replacer(key, obj) { if (typeof obj == "function") { var m = obj.toString().match(/function\s*[^\s(]*/); return m ? m[0] : "function"; } return obj; } if (window.JSON && JSON.stringify) return JSON.stringify(obj, replacer, 2); return "[unsupported]"; // Fail safely if no native JSON. } function highlight(string, mode) { var state = mode.startState(); var lines = string.replace(/\r\n/g,'\n').split('\n'); var st = [], pos = 0; for (var i = 0; i < lines.length; ++i) { var line = lines[i], newLine = true; if (mode.indent) { var ws = line.match(/^\s*/)[0]; var indent = mode.indent(state, line.slice(ws.length), line); if (indent != CodeMirror.Pass && indent != ws.length) (st.indentFailures || (st.indentFailures = [])).push( "Indentation of line " + (i + 1) + " is " + indent + " (expected " + ws.length + ")"); } var stream = new CodeMirror.StringStream(line, 4, { lookAhead: function(n) { return lines[i + n] } }); if (line == "" && mode.blankLine) mode.blankLine(state); /* Start copied code from CodeMirror.highlight */ while (!stream.eol()) { for (var j = 0; j < 10 && stream.start >= stream.pos; j++) var compare = mode.token(stream, state); if (j == 10) throw new Failure("Failed to advance the stream." + stream.string + " " + stream.pos); var substr = stream.current(); if (compare && compare.indexOf(" ") > -1) compare = compare.split(' ').sort().join(' '); stream.start = stream.pos; if (pos && st[pos-1].style == compare && !newLine) { st[pos-1].text += substr; } else if (substr) { st[pos++] = {style: compare, text: substr, state: stringify(state)}; } // Give up when line is ridiculously long if (stream.pos > 5000) { st[pos++] = {style: null, text: this.text.slice(stream.pos)}; break; } newLine = false; } } return st; } function highlightOutputsDifferent(o1, o2) { var minLen = Math.min(o1.length, o2.length); for (var i = 0; i < minLen; ++i) if (o1[i].style != o2[i].style || o1[i].text != o2[i].text) return i; if (o1.length > minLen || o2.length > minLen) return minLen; } function prettyPrintOutputTable(output, diffAt) { var s = ''; s += ''; for (var i = 0; i < output.length; ++i) { var style = output[i].style, val = output[i].text; s += ''; } s += ''; for (var i = 0; i < output.length; ++i) { s += ''; } if(output[0].state) { s += ''; for (var i = 0; i < output.length; ++i) { s += ''; } } s += '
    ' + '' + esc(val.replace(/ /g,'\xb7')) + // · MIDDLE DOT '' + '
    ' + (output[i].style || null) + '
    ' + esc(output[i].state) + '
    '; return s; } })(); ================================================ FILE: third_party/CodeMirror/test/multi_test.js ================================================ (function() { namespace = "multi_"; function hasSelections(cm) { var sels = cm.listSelections(); var given = (arguments.length - 1) / 4; if (sels.length != given) throw new Failure("expected " + given + " selections, found " + sels.length); for (var i = 0, p = 1; i < given; i++, p += 4) { var anchor = Pos(arguments[p], arguments[p + 1]); var head = Pos(arguments[p + 2], arguments[p + 3]); eqCharPos(sels[i].anchor, anchor, "anchor of selection " + i); eqCharPos(sels[i].head, head, "head of selection " + i); } } function hasCursors(cm) { var sels = cm.listSelections(); var given = (arguments.length - 1) / 2; if (sels.length != given) throw new Failure("expected " + given + " selections, found " + sels.length); for (var i = 0, p = 1; i < given; i++, p += 2) { eqCursorPos(sels[i].anchor, sels[i].head, "something selected for " + i); var head = Pos(arguments[p], arguments[p + 1]); eqCharPos(sels[i].head, head, "selection " + i); } } testCM("getSelection", function(cm) { select(cm, {anchor: Pos(0, 0), head: Pos(1, 2)}, {anchor: Pos(2, 2), head: Pos(2, 0)}); eq(cm.getSelection(), "1234\n56\n90"); eq(cm.getSelection(false).join("|"), "1234|56|90"); eq(cm.getSelections().join("|"), "1234\n56|90"); }, {value: "1234\n5678\n90"}); testCM("setSelection", function(cm) { select(cm, Pos(3, 0), Pos(0, 0), {anchor: Pos(2, 5), head: Pos(1, 0)}); hasSelections(cm, 0, 0, 0, 0, 2, 5, 1, 0, 3, 0, 3, 0); cm.setSelection(Pos(1, 2), Pos(1, 1)); hasSelections(cm, 1, 2, 1, 1); select(cm, {anchor: Pos(1, 1), head: Pos(2, 4)}, {anchor: Pos(0, 0), head: Pos(1, 3)}, Pos(3, 0), Pos(2, 2)); hasSelections(cm, 0, 0, 2, 4, 3, 0, 3, 0); cm.setSelections([{anchor: Pos(0, 1), head: Pos(0, 2)}, {anchor: Pos(1, 1), head: Pos(1, 2)}, {anchor: Pos(2, 1), head: Pos(2, 2)}], 1); eqCharPos(cm.getCursor("head"), Pos(1, 2)); eqCharPos(cm.getCursor("anchor"), Pos(1, 1)); eqCharPos(cm.getCursor("from"), Pos(1, 1)); eqCharPos(cm.getCursor("to"), Pos(1, 2)); cm.setCursor(Pos(1, 1)); hasCursors(cm, 1, 1); }, {value: "abcde\nabcde\nabcde\n"}); testCM("somethingSelected", function(cm) { select(cm, Pos(0, 1), {anchor: Pos(0, 3), head: Pos(0, 5)}); eq(cm.somethingSelected(), true); select(cm, Pos(0, 1), Pos(0, 3), Pos(0, 5)); eq(cm.somethingSelected(), false); }, {value: "123456789"}); testCM("extendSelection", function(cm) { select(cm, Pos(0, 1), Pos(1, 1), Pos(2, 1)); cm.setExtending(true); cm.extendSelections([Pos(0, 2), Pos(1, 0), Pos(2, 3)]); hasSelections(cm, 0, 1, 0, 2, 1, 1, 1, 0, 2, 1, 2, 3); cm.extendSelection(Pos(2, 4), Pos(2, 0)); hasSelections(cm, 2, 4, 2, 0); }, {value: "1234\n1234\n1234"}); testCM("addSelection", function(cm) { select(cm, Pos(0, 1), Pos(1, 1)); cm.addSelection(Pos(0, 0), Pos(0, 4)); hasSelections(cm, 0, 0, 0, 4, 1, 1, 1, 1); cm.addSelection(Pos(2, 2)); hasSelections(cm, 0, 0, 0, 4, 1, 1, 1, 1, 2, 2, 2, 2); }, {value: "1234\n1234\n1234"}); testCM("replaceSelection", function(cm) { var selections = [{anchor: Pos(0, 0), head: Pos(0, 1)}, {anchor: Pos(0, 2), head: Pos(0, 3)}, {anchor: Pos(0, 4), head: Pos(0, 5)}, {anchor: Pos(2, 1), head: Pos(2, 4)}, {anchor: Pos(2, 5), head: Pos(2, 6)}]; var val = "123456\n123456\n123456"; cm.setValue(val); cm.setSelections(selections); cm.replaceSelection("ab", "around"); eq(cm.getValue(), "ab2ab4ab6\n123456\n1ab5ab"); hasSelections(cm, 0, 0, 0, 2, 0, 3, 0, 5, 0, 6, 0, 8, 2, 1, 2, 3, 2, 4, 2, 6); cm.setValue(val); cm.setSelections(selections); cm.replaceSelection("", "around"); eq(cm.getValue(), "246\n123456\n15"); hasSelections(cm, 0, 0, 0, 0, 0, 1, 0, 1, 0, 2, 0, 2, 2, 1, 2, 1, 2, 2, 2, 2); cm.setValue(val); cm.setSelections(selections); cm.replaceSelection("X\nY\nZ", "around"); hasSelections(cm, 0, 0, 2, 1, 2, 2, 4, 1, 4, 2, 6, 1, 8, 1, 10, 1, 10, 2, 12, 1); cm.replaceSelection("a", "around"); hasSelections(cm, 0, 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 2, 1, 2, 2, 2, 3, 2, 4); cm.replaceSelection("xy", "start"); hasSelections(cm, 0, 0, 0, 0, 0, 3, 0, 3, 0, 6, 0, 6, 2, 1, 2, 1, 2, 4, 2, 4); cm.replaceSelection("z\nf"); hasSelections(cm, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 6, 1, 6, 1, 7, 1, 7, 1); eq(cm.getValue(), "z\nfxy2z\nfxy4z\nfxy6\n123456\n1z\nfxy5z\nfxy"); }); function select(cm) { var sels = []; for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg.head) sels.push(arg); else sels.push({head: arg, anchor: arg}); } cm.setSelections(sels, sels.length - 1); } testCM("indentSelection", function(cm) { select(cm, Pos(0, 1), Pos(1, 1)); cm.indentSelection(4); eq(cm.getValue(), " foo\n bar\nbaz"); select(cm, Pos(0, 2), Pos(0, 3), Pos(0, 4)); cm.indentSelection(-2); eq(cm.getValue(), " foo\n bar\nbaz"); select(cm, {anchor: Pos(0, 0), head: Pos(1, 2)}, {anchor: Pos(1, 3), head: Pos(2, 0)}); cm.indentSelection(-2); eq(cm.getValue(), "foo\n bar\nbaz"); }, {value: "foo\nbar\nbaz"}); testCM("killLine", function(cm) { select(cm, Pos(0, 1), Pos(0, 2), Pos(1, 1)); cm.execCommand("killLine"); eq(cm.getValue(), "f\nb\nbaz"); cm.execCommand("killLine"); eq(cm.getValue(), "fbbaz"); cm.setValue("foo\nbar\nbaz"); select(cm, Pos(0, 1), {anchor: Pos(0, 2), head: Pos(2, 1)}); cm.execCommand("killLine"); eq(cm.getValue(), "faz"); }, {value: "foo\nbar\nbaz"}); testCM("deleteLine", function(cm) { select(cm, Pos(0, 0), {head: Pos(0, 1), anchor: Pos(2, 0)}, Pos(4, 0)); cm.execCommand("deleteLine"); eq(cm.getValue(), "4\n6\n7"); select(cm, Pos(2, 1)); cm.execCommand("deleteLine"); eq(cm.getValue(), "4\n6\n"); }, {value: "1\n2\n3\n4\n5\n6\n7"}); testCM("deleteH", function(cm) { select(cm, Pos(0, 4), {anchor: Pos(1, 4), head: Pos(1, 5)}); cm.execCommand("delWordAfter"); eq(cm.getValue(), "foo bar baz\nabc ef ghi\n"); cm.execCommand("delWordAfter"); eq(cm.getValue(), "foo baz\nabc ghi\n"); cm.execCommand("delCharBefore"); cm.execCommand("delCharBefore"); eq(cm.getValue(), "fo baz\nab ghi\n"); select(cm, Pos(0, 3), Pos(0, 4), Pos(0, 5)); cm.execCommand("delWordAfter"); eq(cm.getValue(), "fo \nab ghi\n"); }, {value: "foo bar baz\nabc def ghi\n"}); testCM("goLineStart", function(cm) { select(cm, Pos(0, 2), Pos(0, 3), Pos(1, 1)); cm.execCommand("goLineStart"); hasCursors(cm, 0, 0, 1, 0); select(cm, Pos(1, 1), Pos(0, 1)); cm.setExtending(true); cm.execCommand("goLineStart"); hasSelections(cm, 0, 1, 0, 0, 1, 1, 1, 0); }, {value: "foo\nbar\nbaz"}); testCM("moveV", function(cm) { select(cm, Pos(0, 2), Pos(1, 2)); cm.execCommand("goLineDown"); hasCursors(cm, 1, 2, 2, 2); cm.execCommand("goLineUp"); hasCursors(cm, 0, 2, 1, 2); cm.execCommand("goLineUp"); hasCursors(cm, 0, 0, 0, 2); cm.execCommand("goLineUp"); hasCursors(cm, 0, 0); select(cm, Pos(0, 2), Pos(1, 2)); cm.setExtending(true); cm.execCommand("goLineDown"); hasSelections(cm, 0, 2, 2, 2); }, {value: "12345\n12345\n12345"}); testCM("moveH", function(cm) { select(cm, Pos(0, 1), Pos(0, 3), Pos(0, 5), Pos(2, 3)); cm.execCommand("goCharRight"); hasCursors(cm, 0, 2, 0, 4, 1, 0, 2, 4); cm.execCommand("goCharLeft"); hasCursors(cm, 0, 1, 0, 3, 0, 5, 2, 3); for (var i = 0; i < 15; i++) cm.execCommand("goCharRight"); hasCursors(cm, 2, 4, 2, 5); }, {value: "12345\n12345\n12345"}); testCM("newlineAndIndent", function(cm) { select(cm, Pos(0, 5), Pos(1, 5)); cm.execCommand("newlineAndIndent"); hasCursors(cm, 1, 2, 3, 2); eq(cm.getValue(), "x = [\n 1];\ny = [\n 2];"); cm.undo(); eq(cm.getValue(), "x = [1];\ny = [2];"); hasCursors(cm, 0, 5, 1, 5); select(cm, Pos(0, 5), Pos(0, 6)); cm.execCommand("newlineAndIndent"); hasCursors(cm, 1, 2, 2, 0); eq(cm.getValue(), "x = [\n 1\n];\ny = [2];"); }, {value: "x = [1];\ny = [2];", mode: "javascript"}); testCM("goDocStartEnd", function(cm) { select(cm, Pos(0, 1), Pos(1, 1)); cm.execCommand("goDocStart"); hasCursors(cm, 0, 0); select(cm, Pos(0, 1), Pos(1, 1)); cm.execCommand("goDocEnd"); hasCursors(cm, 1, 3); select(cm, Pos(0, 1), Pos(1, 1)); cm.setExtending(true); cm.execCommand("goDocEnd"); hasSelections(cm, 1, 1, 1, 3); }, {value: "abc\ndef"}); testCM("selectionHistory", function(cm) { for (var i = 0; i < 3; ++i) cm.addSelection(Pos(0, i * 2), Pos(0, i * 2 + 1)); cm.execCommand("undoSelection"); eq(cm.getSelection(), "1\n2"); cm.execCommand("undoSelection"); eq(cm.getSelection(), "1"); cm.execCommand("undoSelection"); eq(cm.getSelection(), ""); eqCharPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("redoSelection"); eq(cm.getSelection(), "1"); cm.execCommand("redoSelection"); eq(cm.getSelection(), "1\n2"); cm.execCommand("redoSelection"); eq(cm.getSelection(), "1\n2\n3"); }, {value: "1 2 3"}); testCM("selectionsMayTouch", function(cm) { select(cm, Pos(0, 0), Pos(0, 2)) cm.setExtending(true); cm.extendSelections([Pos(0, 2), Pos(0, 4)]) hasSelections(cm, 0, 0, 0, 2, 0, 2, 0, 4) cm.extendSelections([Pos(0, 3), Pos(0, 4)]) hasSelections(cm, 0, 0, 0, 4) }, {selectionsMayTouch: true, value: "1234"}) })(); ================================================ FILE: third_party/CodeMirror/test/phantom_driver.js ================================================ var page = require('webpage').create(); page.open("http://localhost:3000/test/index.html", function (status) { if (status != "success") { console.log("page couldn't be loaded successfully"); phantom.exit(1); } waitFor(function () { return page.evaluate(function () { var output = document.getElementById('status'); if (!output) { return false; } return (/^(\d+ failures?|all passed)/i).test(output.innerText); }); }, function () { var failed = page.evaluate(function () { return window.failed; }); var output = page.evaluate(function () { return document.getElementById('output').innerText + "\n" + document.getElementById('status').innerText; }); console.log(output); phantom.exit(failed > 0 ? 1 : 0); }); }); function waitFor (test, cb) { if (test()) { cb(); } else { setTimeout(function () { waitFor(test, cb); }, 250); } } ================================================ FILE: third_party/CodeMirror/test/run.js ================================================ #!/usr/bin/env node var ok = require("./lint").ok; var files = new (require('node-static').Server)(); var server = require('http').createServer(function (req, res) { req.addListener('end', function () { files.serve(req, res, function (err/*, result */) { if (err) { console.error(err); process.exit(1); } }); }).resume(); }).addListener('error', function (err) { throw err; }).listen(3000, function () { var childProcess = require('child_process'); var phantomjs = require("phantomjs-prebuilt"); var childArgs = [ require("path").join(__dirname, 'phantom_driver.js') ]; childProcess.execFile(phantomjs.path, childArgs, function (err, stdout, stderr) { server.close(); console.log(stdout); if (err) console.error(err); if (stderr) console.error(stderr); process.exit(err || stderr || !ok ? 1 : 0); }); }); ================================================ FILE: third_party/CodeMirror/test/scroll_test.js ================================================ (function() { "use strict"; namespace = "scroll_"; testCM("bars_hidden", function(cm) { for (var i = 0;; i++) { var wrapBox = cm.getWrapperElement().getBoundingClientRect(); var scrollBox = cm.getScrollerElement().getBoundingClientRect(); is(wrapBox.bottom < scrollBox.bottom - 10); is(wrapBox.right < scrollBox.right - 10); if (i == 1) break; cm.getWrapperElement().style.height = "auto"; cm.refresh(); } }); function barH(cm) { return byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; } function barV(cm) { return byClassName(cm.getWrapperElement(), "CodeMirror-vscrollbar")[0]; } function displayBottom(cm, scrollbar) { if (scrollbar && cm.display.scroller.offsetHeight > cm.display.scroller.clientHeight) return barH(cm).getBoundingClientRect().top; else return cm.getWrapperElement().getBoundingClientRect().bottom - 1; } function displayRight(cm, scrollbar) { if (scrollbar && cm.display.scroller.offsetWidth > cm.display.scroller.clientWidth) return barV(cm).getBoundingClientRect().left; else return cm.getWrapperElement().getBoundingClientRect().right - 1; } function testMovedownFixed(cm, hScroll) { cm.setSize("100px", "100px"); if (hScroll) cm.setValue(new Array(100).join("x")); var bottom = displayBottom(cm, hScroll); for (var i = 0; i < 30; i++) { cm.replaceSelection("x\n"); var cursorBottom = cm.cursorCoords(null, "window").bottom; is(cursorBottom <= bottom); } is(cursorBottom >= bottom - 5); } testCM("movedown_fixed", function(cm) {testMovedownFixed(cm, false);}); testCM("movedown_hscroll_fixed", function(cm) {testMovedownFixed(cm, true);}); function testMovedownResize(cm, hScroll) { cm.getWrapperElement().style.height = "auto"; if (hScroll) cm.setValue(new Array(100).join("x")); cm.refresh(); for (var i = 0; i < 30; i++) { cm.replaceSelection("x\n"); var bottom = displayBottom(cm, hScroll); var cursorBottom = cm.cursorCoords(null, "window").bottom; is(cursorBottom <= bottom); is(cursorBottom >= bottom - 5); } } testCM("movedown_resize", function(cm) {testMovedownResize(cm, false);}); testCM("movedown_hscroll_resize", function(cm) {testMovedownResize(cm, true);}); function testMoveright(cm, wrap, scroll) { cm.setSize("100px", "100px"); if (wrap) cm.setOption("lineWrapping", true); if (scroll) { cm.setValue("\n" + new Array(100).join("x\n")); cm.setCursor(Pos(0, 0)); } var right = displayRight(cm, scroll); for (var i = 0; i < 10; i++) { cm.replaceSelection("xxxxxxxxxx"); var cursorRight = cm.cursorCoords(null, "window").right; is(cursorRight < right); } if (!wrap) is(cursorRight > right - 20); } testCM("moveright", function(cm) {testMoveright(cm, false, false);}); testCM("moveright_wrap", function(cm) {testMoveright(cm, true, false);}); testCM("moveright_scroll", function(cm) {testMoveright(cm, false, true);}); testCM("moveright_scroll_wrap", function(cm) {testMoveright(cm, true, true);}); testCM("suddenly_wide", function(cm) { addDoc(cm, 100, 100); cm.replaceSelection(new Array(600).join("l ") + "\n"); cm.execCommand("goLineUp"); cm.execCommand("goLineEnd"); is(barH(cm).scrollLeft > cm.getScrollerElement().scrollLeft - 1); }); testCM("wrap_changes_height", function(cm) { var line = new Array(20).join("a ") + "\n"; cm.setValue(new Array(20).join(line)); var box = cm.getWrapperElement().getBoundingClientRect(); cm.setSize(cm.cursorCoords(Pos(0), "window").right - box.left + 2, cm.cursorCoords(Pos(19, 0), "window").bottom - box.top + 2); cm.setCursor(Pos(19, 0)); cm.replaceSelection("\n"); is(cm.cursorCoords(null, "window").bottom < displayBottom(cm, false)); }, {lineWrapping: true}); testCM("height_auto_with_gutter_expect_no_scroll_after_line_delete", function(cm) { cm.setSize(null, "auto"); cm.setValue("x\n"); cm.execCommand("goDocEnd"); cm.execCommand("delCharBefore"); eq(cm.getScrollInfo().top, 0); cm.scrollTo(null, 10); is(cm.getScrollInfo().top < 5); }, {lineNumbers: true}); testCM("bidi_ensureCursorVisible", function(cm) { cm.setValue("
    وضع الاستخدام. عندما لا تعطى، وهذا الافتراضي إلى الطريقة الاولى\n"); cm.execCommand("goLineStart"); eq(cm.getScrollInfo().left, 0); cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(0, 3, "before")); eq(cm.getScrollInfo().left, 0); }, {lineWrapping: false}); })(); ================================================ FILE: third_party/CodeMirror/test/search_test.js ================================================ (function() { "use strict"; function run(doc, query, options) { var cursor = doc.getSearchCursor(query, null, options); for (var i = 3; i < arguments.length; i += 4) { var found = cursor.findNext(); is(found, "not enough results (forward)"); eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), "from, forward, " + (i - 3) / 4); eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), "to, forward, " + (i - 3) / 4); } is(!cursor.findNext(), "too many matches (forward)"); for (var i = arguments.length - 4; i >= 3; i -= 4) { var found = cursor.findPrevious(); is(found, "not enough results (backwards)"); eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), "from, backwards, " + (i - 3) / 4); eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), "to, backwards, " + (i - 3) / 4); } is(!cursor.findPrevious(), "too many matches (backwards)"); } function test(name, f) { window.test("search_" + name, f) } test("simple", function() { var doc = new CodeMirror.Doc("abcdefg\nabcdefg") run(doc, "cde", false, 0, 2, 0, 5, 1, 2, 1, 5); }); test("multiline", function() { var doc = new CodeMirror.Doc("hallo\na\nb\ngoodbye") run(doc, "llo\na\nb\ngoo", false, 0, 2, 3, 3); run(doc, "blah\na\nb\nhall", false); run(doc, "bye\nx\neye", false); }); test("regexp", function() { var doc = new CodeMirror.Doc("abcde\nabcde") run(doc, /bcd/, false, 0, 1, 0, 4, 1, 1, 1, 4); run(doc, /BCD/, false); run(doc, /BCD/i, false, 0, 1, 0, 4, 1, 1, 1, 4); }); test("regexpMultiline", function() { var doc = new CodeMirror.Doc("foo foo\nbar\nbaz") run(doc, /fo[^]*az/, {multiline: true}, 0, 0, 2, 3) run(doc, /[oa][^u]/, {multiline: true}, 0, 1, 0, 3, 0, 5, 0, 7, 1, 1, 1, 3, 2, 1, 2, 3) run(doc, /[a][^u]{2}/, {multiline: true}, 1, 1, 2, 0) }) test("insensitive", function() { var doc = new CodeMirror.Doc("hallo\nHALLO\noink\nhAllO") run(doc, "All", false, 3, 1, 3, 4); run(doc, "All", true, 0, 1, 0, 4, 1, 1, 1, 4, 3, 1, 3, 4); }); test("multilineInsensitive", function() { var doc = new CodeMirror.Doc("zie ginds komT\nDe Stoomboot\nuit Spanje weer aan") run(doc, "komt\nde stoomboot\nuit", false); run(doc, "komt\nde stoomboot\nuit", {caseFold: true}, 0, 10, 2, 3); run(doc, "kOMt\ndE stOOmboot\nuiT", {caseFold: true}, 0, 10, 2, 3); }); test("multilineInsensitiveSlow", function() { var text = "" for (var i = 0; i < 1000; i++) text += "foo\nbar\n" var doc = new CodeMirror.Doc("find\nme\n" + text + "find\nme\n") var t0 = +new Date run(doc, /find\nme/, {multiline: true}, 0, 0, 1, 2, 2002, 0, 2003, 2) is(+new Date - t0 < 100) }) test("expandingCaseFold", function() { var doc = new CodeMirror.Doc("İİ İİ\nuu uu") run(doc, "", true, 0, 8, 0, 12, 1, 8, 1, 12); run(doc, "İİ", true, 0, 3, 0, 5, 0, 6, 0, 8); }); test("normalize", function() { if (!String.prototype.normalize) return var doc = new CodeMirror.Doc("yılbaşı\n수 있을까\nLe taux d'humidité à London") run(doc, "s", false, 0, 5, 0, 6) run(doc, "이", false, 1, 2, 1, 3) run(doc, "a", false, 0, 4, 0, 5, 2, 4, 2, 5, 2, 19, 2, 20) }) })(); ================================================ FILE: third_party/CodeMirror/test/sql-hint-test.js ================================================ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: https://codemirror.net/LICENSE (function() { var Pos = CodeMirror.Pos; var simpleTables = { "users": ["name", "score", "birthDate"], "xcountries": ["name", "population", "size"] }; var schemaTables = { "schema.users": ["name", "score", "birthDate"], "schema.countries": ["name", "population", "size"] }; var displayTextTables = [{ text: "mytable", displayText: "mytable | The main table", columns: [{text: "id", displayText: "id | Unique ID"}, {text: "name", displayText: "name | The name"}] }]; namespace = "sql-hint_"; function test(name, spec) { testCM(name, function(cm) { cm.setValue(spec.value); cm.setCursor(spec.cursor); var completion = CodeMirror.hint.sql(cm, {tables: spec.tables}); if (!deepCompare(completion.list, spec.list)) throw new Failure("Wrong completion results " + JSON.stringify(completion.list) + " vs " + JSON.stringify(spec.list)); eqCharPos(completion.from, spec.from); eqCharPos(completion.to, spec.to); }, { value: spec.value, mode: spec.mode || "text/x-mysql" }); } test("keywords", { value: "SEL", cursor: Pos(0, 3), list: [{"text":"SELECT","className":"CodeMirror-hint-keyword"}], from: Pos(0, 0), to: Pos(0, 3) }); test("from", { value: "SELECT * fr", cursor: Pos(0, 11), list: [{"text":"FROM","className":"CodeMirror-hint-keyword"}], from: Pos(0, 9), to: Pos(0, 11) }); test("table", { value: "SELECT xc", cursor: Pos(0, 9), tables: simpleTables, list: [{"text":"xcountries","className":"CodeMirror-hint-table"}], from: Pos(0, 7), to: Pos(0, 9) }); test("columns", { value: "SELECT users.", cursor: Pos(0, 13), tables: simpleTables, list: ["users.name", "users.score", "users.birthDate"], from: Pos(0, 7), to: Pos(0, 13) }); test("singlecolumn", { value: "SELECT users.na", cursor: Pos(0, 15), tables: simpleTables, list: ["users.name"], from: Pos(0, 7), to: Pos(0, 15) }); test("quoted", { value: "SELECT `users`.`na", cursor: Pos(0, 18), tables: simpleTables, list: ["`users`.`name`"], from: Pos(0, 7), to: Pos(0, 18) }); test("doublequoted", { value: "SELECT \"users\".\"na", cursor: Pos(0, 18), tables: simpleTables, list: ["\"users\".\"name\""], from: Pos(0, 7), to: Pos(0, 18), mode: "text/x-sqlite" }); test("quotedcolumn", { value: "SELECT users.`na", cursor: Pos(0, 16), tables: simpleTables, list: ["`users`.`name`"], from: Pos(0, 7), to: Pos(0, 16) }); test("doublequotedcolumn", { value: "SELECT users.\"na", cursor: Pos(0, 16), tables: simpleTables, list: ["\"users\".\"name\""], from: Pos(0, 7), to: Pos(0, 16), mode: "text/x-sqlite" }); test("schema", { value: "SELECT schem", cursor: Pos(0, 12), tables: schemaTables, list: [{"text":"schema.users","className":"CodeMirror-hint-table"}, {"text":"schema.countries","className":"CodeMirror-hint-table"}, {"text":"SCHEMA","className":"CodeMirror-hint-keyword"}, {"text":"SCHEMA_NAME","className":"CodeMirror-hint-keyword"}, {"text":"SCHEMAS","className":"CodeMirror-hint-keyword"}], from: Pos(0, 7), to: Pos(0, 12) }); test("schemaquoted", { value: "SELECT `sch", cursor: Pos(0, 11), tables: schemaTables, list: ["`schema`.`users`", "`schema`.`countries`"], from: Pos(0, 7), to: Pos(0, 11) }); test("schemadoublequoted", { value: "SELECT \"sch", cursor: Pos(0, 11), tables: schemaTables, list: ["\"schema\".\"users\"", "\"schema\".\"countries\""], from: Pos(0, 7), to: Pos(0, 11), mode: "text/x-sqlite" }); test("schemacolumn", { value: "SELECT schema.users.", cursor: Pos(0, 20), tables: schemaTables, list: ["schema.users.name", "schema.users.score", "schema.users.birthDate"], from: Pos(0, 7), to: Pos(0, 20) }); test("schemacolumnquoted", { value: "SELECT `schema`.`users`.", cursor: Pos(0, 24), tables: schemaTables, list: ["`schema`.`users`.`name`", "`schema`.`users`.`score`", "`schema`.`users`.`birthDate`"], from: Pos(0, 7), to: Pos(0, 24) }); test("schemacolumndoublequoted", { value: "SELECT \"schema\".\"users\".", cursor: Pos(0, 24), tables: schemaTables, list: ["\"schema\".\"users\".\"name\"", "\"schema\".\"users\".\"score\"", "\"schema\".\"users\".\"birthDate\""], from: Pos(0, 7), to: Pos(0, 24), mode: "text/x-sqlite" }); test("displayText_table", { value: "SELECT myt", cursor: Pos(0, 10), tables: displayTextTables, list: [{text: "mytable", displayText: "mytable | The main table", "className":"CodeMirror-hint-table"}], from: Pos(0, 7), to: Pos(0, 10) }); test("displayText_column", { value: "SELECT mytable.", cursor: Pos(0, 15), tables: displayTextTables, list: [{text: "mytable.id", displayText: "id | Unique ID"}, {text: "mytable.name", displayText: "name | The name"}], from: Pos(0, 7), to: Pos(0, 15) }); test("alias_complete", { value: "SELECT t. FROM users t", cursor: Pos(0, 9), tables: simpleTables, list: ["t.name", "t.score", "t.birthDate"], from: Pos(0, 7), to: Pos(0, 9) }); test("alias_complete_with_displayText", { value: "SELECT t. FROM mytable t", cursor: Pos(0, 9), tables: displayTextTables, list: [{text: "t.id", displayText: "id | Unique ID"}, {text: "t.name", displayText: "name | The name"}], from: Pos(0, 7), to: Pos(0, 9) }) function deepCompare(a, b) { if (a === b) return true if (!(a && typeof a == "object") || !(b && typeof b == "object")) return false var array = Array.isArray(a) if (Array.isArray(b) != array) return false if (array) { if (a.length != b.length) return false for (var i = 0; i < a.length; i++) if (!deepCompare(a[i], b[i])) return false } else { for (var p in a) if (!(p in b) || !deepCompare(a[p], b[p])) return false for (var p in b) if (!(p in a)) return false } return true } })(); ================================================ FILE: third_party/CodeMirror/test/sublime_test.js ================================================ (function() { "use strict"; var Pos = CodeMirror.Pos; namespace = "sublime_"; function stTest(name) { var actions = Array.prototype.slice.call(arguments, 1); testCM(name, function(cm) { for (var i = 0; i < actions.length; i++) { var action = actions[i]; if (typeof action == "string" && i == 0) cm.setValue(action); else if (typeof action == "string") cm.execCommand(action); else if (action instanceof Pos) cm.setCursor(action); else action(cm); } }); } function at(line, ch, msg) { return function(cm) { eq(cm.listSelections().length, 1); eqCursorPos(cm.getCursor("head"), Pos(line, ch), msg); eqCursorPos(cm.getCursor("anchor"), Pos(line, ch), msg); }; } function val(content, msg) { return function(cm) { eq(cm.getValue(), content, msg); }; } function argsToRanges(args) { if (args.length % 4) throw new Error("Wrong number of arguments for ranges."); var ranges = []; for (var i = 0; i < args.length; i += 4) ranges.push({anchor: Pos(args[i], args[i + 1]), head: Pos(args[i + 2], args[i + 3])}); return ranges; } function setSel() { var ranges = argsToRanges(arguments); return function(cm) { cm.setSelections(ranges, 0); }; } function hasSel() { var ranges = argsToRanges(arguments); return function(cm) { var sels = cm.listSelections(); if (sels.length != ranges.length) throw new Failure("Expected " + ranges.length + " selections, but found " + sels.length); for (var i = 0; i < sels.length; i++) { eqCharPos(sels[i].anchor, ranges[i].anchor, "anchor " + i); eqCharPos(sels[i].head, ranges[i].head, "head " + i); } }; } stTest("bySubword", "the foo_bar DooDahBah \n a", "goSubwordLeft", at(0, 0), "goSubwordRight", at(0, 3), "goSubwordRight", at(0, 7), "goSubwordRight", at(0, 11), "goSubwordRight", at(0, 15), "goSubwordRight", at(0, 18), "goSubwordRight", at(0, 21), "goSubwordRight", at(0, 22), "goSubwordRight", at(1, 0), "goSubwordRight", at(1, 2), "goSubwordRight", at(1, 2), "goSubwordLeft", at(1, 1), "goSubwordLeft", at(1, 0), "goSubwordLeft", at(0, 22), "goSubwordLeft", at(0, 18), "goSubwordLeft", at(0, 15), "goSubwordLeft", at(0, 12), "goSubwordLeft", at(0, 8), "goSubwordLeft", at(0, 4), "goSubwordLeft", at(0, 0)); stTest("splitSelectionByLine", "abc\ndef\nghi", setSel(0, 1, 2, 2), "splitSelectionByLine", hasSel(0, 1, 0, 3, 1, 0, 1, 3, 2, 0, 2, 2)); stTest("splitSelectionByLineMulti", "abc\ndef\nghi\njkl", setSel(0, 1, 1, 1, 1, 2, 3, 2, 3, 3, 3, 3), "splitSelectionByLine", hasSel(0, 1, 0, 3, 1, 0, 1, 1, 1, 2, 1, 3, 2, 0, 2, 3, 3, 0, 3, 2, 3, 3, 3, 3)); stTest("selectLine", "abc\ndef\nghi", setSel(0, 1, 0, 1, 2, 0, 2, 1), "selectLine", hasSel(0, 0, 1, 0, 2, 0, 2, 3), setSel(0, 1, 1, 0), "selectLine", hasSel(0, 0, 2, 0)); stTest("insertLineAfter", "abcde\nfghijkl\nmn", setSel(0, 1, 0, 1, 0, 3, 0, 3, 1, 2, 1, 2, 1, 3, 1, 5), "insertLineAfter", hasSel(1, 0, 1, 0, 3, 0, 3, 0), val("abcde\n\nfghijkl\n\nmn")); stTest("insertLineBefore", "abcde\nfghijkl\nmn", setSel(0, 1, 0, 1, 0, 3, 0, 3, 1, 2, 1, 2, 1, 3, 1, 5), "insertLineBefore", hasSel(0, 0, 0, 0, 2, 0, 2, 0), val("\nabcde\n\nfghijkl\nmn")); stTest("selectNextOccurrence", "a foo bar\nfoobar foo", setSel(0, 2, 0, 5), "selectNextOccurrence", hasSel(0, 2, 0, 5, 1, 0, 1, 3), "selectNextOccurrence", hasSel(0, 2, 0, 5, 1, 0, 1, 3, 1, 7, 1, 10), "selectNextOccurrence", hasSel(0, 2, 0, 5, 1, 0, 1, 3, 1, 7, 1, 10), Pos(0, 3), "selectNextOccurrence", hasSel(0, 2, 0, 5), "selectNextOccurrence", hasSel(0, 2, 0, 5, 1, 7, 1, 10), setSel(0, 6, 0, 9), "selectNextOccurrence", hasSel(0, 6, 0, 9, 1, 3, 1, 6)); stTest("selectScope", "foo(a) {\n bar[1, 2];\n}", "selectScope", hasSel(0, 0, 2, 1), Pos(0, 4), "selectScope", hasSel(0, 4, 0, 5), Pos(0, 5), "selectScope", hasSel(0, 4, 0, 5), Pos(0, 6), "selectScope", hasSel(0, 0, 2, 1), Pos(0, 8), "selectScope", hasSel(0, 8, 2, 0), Pos(1, 2), "selectScope", hasSel(0, 8, 2, 0), Pos(1, 6), "selectScope", hasSel(1, 6, 1, 10), Pos(1, 9), "selectScope", hasSel(1, 6, 1, 10), "selectScope", hasSel(0, 8, 2, 0), "selectScope", hasSel(0, 0, 2, 1)); stTest("goToBracket", "foo(a) {\n bar[1, 2];\n}", Pos(0, 0), "goToBracket", at(0, 0), Pos(0, 4), "goToBracket", at(0, 5), "goToBracket", at(0, 4), Pos(0, 8), "goToBracket", at(2, 0), "goToBracket", at(0, 8), Pos(1, 2), "goToBracket", at(2, 0), Pos(1, 7), "goToBracket", at(1, 10), "goToBracket", at(1, 6)); stTest("swapLine", "1\n2\n3---\n4\n5", "swapLineDown", val("2\n1\n3---\n4\n5"), "swapLineUp", val("1\n2\n3---\n4\n5"), "swapLineUp", val("1\n2\n3---\n4\n5"), Pos(4, 1), "swapLineDown", val("1\n2\n3---\n4\n5"), setSel(0, 1, 0, 1, 1, 0, 2, 0, 2, 2, 2, 2), "swapLineDown", val("4\n1\n2\n3---\n5"), hasSel(1, 1, 1, 1, 2, 0, 3, 0, 3, 2, 3, 2), "swapLineUp", val("1\n2\n3---\n4\n5"), hasSel(0, 1, 0, 1, 1, 0, 2, 0, 2, 2, 2, 2)); stTest("swapLineEmptyBottomSel", "1\n2\n3", setSel(0, 1, 1, 0), "swapLineDown", val("2\n1\n3"), hasSel(1, 1, 2, 0), "swapLineUp", val("1\n2\n3"), hasSel(0, 1, 1, 0), "swapLineUp", val("1\n2\n3"), hasSel(0, 0, 0, 0)); stTest("swapLineUpFromEnd", "a\nb\nc", Pos(2, 1), "swapLineUp", hasSel(1, 1, 1, 1), val("a\nc\nb")); stTest("joinLines", "abc\ndef\nghi\njkl", "joinLines", val("abc def\nghi\njkl"), at(0, 4), "undo", setSel(0, 2, 1, 1), "joinLines", val("abc def ghi\njkl"), hasSel(0, 2, 0, 8), "undo", setSel(0, 1, 0, 1, 1, 1, 1, 1, 3, 1, 3, 1), "joinLines", val("abc def ghi\njkl"), hasSel(0, 4, 0, 4, 0, 8, 0, 8, 1, 3, 1, 3)); stTest("duplicateLine", "abc\ndef\nghi", Pos(1, 0), "duplicateLine", val("abc\ndef\ndef\nghi"), at(2, 0), "undo", setSel(0, 1, 0, 1, 1, 1, 1, 1, 2, 1, 2, 1), "duplicateLine", val("abc\nabc\ndef\ndef\nghi\nghi"), hasSel(1, 1, 1, 1, 3, 1, 3, 1, 5, 1, 5, 1)); stTest("duplicateLineSelection", "abcdef", setSel(0, 1, 0, 1, 0, 2, 0, 4, 0, 5, 0, 5), "duplicateLine", val("abcdef\nabcdcdef\nabcdcdef"), hasSel(2, 1, 2, 1, 2, 4, 2, 6, 2, 7, 2, 7)); stTest("sortLines", "c\nb\na\nC\nB\nA", "sortLines", val("A\nB\nC\na\nb\nc"), "undo", setSel(0, 0, 2, 0, 3, 0, 5, 0), "sortLines", val("b\nc\na\nB\nC\nA"), hasSel(0, 0, 2, 0, 3, 0, 5, 0), "undo", setSel(1, 0, 5, 0), "sortLinesInsensitive", val("c\na\nB\nb\nC\nA")); stTest("bookmarks", "abc\ndef\nghi\njkl", Pos(0, 1), "toggleBookmark", setSel(1, 1, 1, 2), "toggleBookmark", setSel(2, 1, 2, 2), "toggleBookmark", "nextBookmark", hasSel(0, 1, 0, 1), "nextBookmark", hasSel(1, 1, 1, 2), "nextBookmark", hasSel(2, 1, 2, 2), "prevBookmark", hasSel(1, 1, 1, 2), "prevBookmark", hasSel(0, 1, 0, 1), "prevBookmark", hasSel(2, 1, 2, 2), "prevBookmark", hasSel(1, 1, 1, 2), "toggleBookmark", "prevBookmark", hasSel(2, 1, 2, 2), "prevBookmark", hasSel(0, 1, 0, 1), "selectBookmarks", hasSel(0, 1, 0, 1, 2, 1, 2, 2), "clearBookmarks", Pos(0, 0), "selectBookmarks", at(0, 0)); stTest("smartBackspace", " foo\n bar", setSel(0, 2, 0, 2, 1, 4, 1, 4, 1, 6, 1, 6), "smartBackspace", val("foo\n br")) stTest("upAndDowncaseAtCursor", "abc\ndef x\nghI", setSel(0, 1, 0, 3, 1, 1, 1, 1, 1, 4, 1, 4), "upcaseAtCursor", val("aBC\nDEF x\nghI"), hasSel(0, 1, 0, 3, 1, 3, 1, 3, 1, 4, 1, 4), "downcaseAtCursor", val("abc\ndef x\nghI"), hasSel(0, 1, 0, 3, 1, 3, 1, 3, 1, 4, 1, 4)); stTest("mark", "abc\ndef\nghi", Pos(1, 1), "setSublimeMark", Pos(2, 1), "selectToSublimeMark", hasSel(2, 1, 1, 1), Pos(0, 1), "swapWithSublimeMark", at(1, 1), "swapWithSublimeMark", at(0, 1), "deleteToSublimeMark", val("aef\nghi"), "sublimeYank", val("abc\ndef\nghi"), at(1, 1)); stTest("findUnder", "foo foobar a", "findUnder", hasSel(0, 4, 0, 7), "findUnder", hasSel(0, 0, 0, 3), "findUnderPrevious", hasSel(0, 4, 0, 7), "findUnderPrevious", hasSel(0, 0, 0, 3), Pos(0, 4), "findUnder", hasSel(0, 4, 0, 10), Pos(0, 11), "findUnder", hasSel(0, 11, 0, 11)); })(); ================================================ FILE: third_party/CodeMirror/test/test.js ================================================ var Pos = CodeMirror.Pos; CodeMirror.defaults.rtlMoveVisually = true; function forEach(arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i], i); } function addDoc(cm, width, height) { var content = [], line = ""; for (var i = 0; i < width; ++i) line += "x"; for (var i = 0; i < height; ++i) content.push(line); cm.setValue(content.join("\n")); } function byClassName(elt, cls) { if (elt.getElementsByClassName) return elt.getElementsByClassName(cls); var found = [], re = new RegExp("\\b" + cls + "\\b"); function search(elt) { if (elt.nodeType == 3) return; if (re.test(elt.className)) found.push(elt); for (var i = 0, e = elt.childNodes.length; i < e; ++i) search(elt.childNodes[i]); } search(elt); return found; } var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent); var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent); var mac = /Mac/.test(navigator.platform); var phantom = /PhantomJS/.test(navigator.userAgent); var opera = /Opera\/\./.test(navigator.userAgent); var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/); if (opera_version) opera_version = Number(opera_version); var opera_lt10 = opera && (!opera_version || opera_version < 10); namespace = "core_"; test("core_fromTextArea", function() { var te = document.getElementById("code"); te.value = "CONTENT"; var cm = CodeMirror.fromTextArea(te); is(!te.offsetHeight); eq(cm.getValue(), "CONTENT"); cm.setValue("foo\nbar"); eq(cm.getValue(), "foo\nbar"); cm.save(); is(/^foo\r?\nbar$/.test(te.value)); cm.setValue("xxx"); cm.toTextArea(); is(te.offsetHeight); eq(te.value, "xxx"); }); testCM("getRange", function(cm) { eq(cm.getLine(0), "1234"); eq(cm.getLine(1), "5678"); eq(cm.getLine(2), null); eq(cm.getLine(-1), null); eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123"); eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234"); eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56"); eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78"); }, {value: "1234\n5678"}); testCM("replaceRange", function(cm) { eq(cm.getValue(), ""); cm.replaceRange("foo\n", Pos(0, 0)); eq(cm.getValue(), "foo\n"); cm.replaceRange("a\nb", Pos(0, 1)); eq(cm.getValue(), "fa\nboo\n"); eq(cm.lineCount(), 3); cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1)); eq(cm.getValue(), "xyzzyoo\n"); cm.replaceRange("abc", Pos(0, 0), Pos(10, 0)); eq(cm.getValue(), "abc"); eq(cm.lineCount(), 1); }); testCM("selection", function(cm) { cm.setSelection(Pos(0, 4), Pos(2, 2)); is(cm.somethingSelected()); eq(cm.getSelection(), "11\n222222\n33"); eqCursorPos(cm.getCursor(false), Pos(2, 2)); eqCursorPos(cm.getCursor(true), Pos(0, 4)); cm.setSelection(Pos(1, 0)); is(!cm.somethingSelected()); eq(cm.getSelection(), ""); eqCursorPos(cm.getCursor(true), Pos(1, 0)); cm.replaceSelection("abc", "around"); eq(cm.getSelection(), "abc"); eq(cm.getValue(), "111111\nabc222222\n333333"); cm.replaceSelection("def", "end"); eq(cm.getSelection(), ""); eqCursorPos(cm.getCursor(true), Pos(1, 3)); cm.setCursor(Pos(2, 1)); eqCursorPos(cm.getCursor(true), Pos(2, 1)); cm.setCursor(1, 2); eqCursorPos(cm.getCursor(true), Pos(1, 2)); }, {value: "111111\n222222\n333333"}); testCM("extendSelection", function(cm) { cm.setExtending(true); addDoc(cm, 10, 10); cm.setSelection(Pos(3, 5)); eqCursorPos(cm.getCursor("head"), Pos(3, 5)); eqCursorPos(cm.getCursor("anchor"), Pos(3, 5)); cm.setSelection(Pos(2, 5), Pos(5, 5)); eqCursorPos(cm.getCursor("head"), Pos(5, 5)); eqCursorPos(cm.getCursor("anchor"), Pos(2, 5)); eqCursorPos(cm.getCursor("start"), Pos(2, 5)); eqCursorPos(cm.getCursor("end"), Pos(5, 5)); cm.setSelection(Pos(5, 5), Pos(2, 5)); eqCursorPos(cm.getCursor("head"), Pos(2, 5)); eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); eqCursorPos(cm.getCursor("start"), Pos(2, 5)); eqCursorPos(cm.getCursor("end"), Pos(5, 5)); cm.extendSelection(Pos(3, 2)); eqCursorPos(cm.getCursor("head"), Pos(3, 2)); eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); cm.extendSelection(Pos(6, 2)); eqCursorPos(cm.getCursor("head"), Pos(6, 2)); eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); cm.extendSelection(Pos(6, 3), Pos(6, 4)); eqCursorPos(cm.getCursor("head"), Pos(6, 4)); eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); cm.extendSelection(Pos(0, 3), Pos(0, 4)); eqCursorPos(cm.getCursor("head"), Pos(0, 3)); eqCursorPos(cm.getCursor("anchor"), Pos(5, 5)); cm.extendSelection(Pos(4, 5), Pos(6, 5)); eqCursorPos(cm.getCursor("head"), Pos(6, 5)); eqCursorPos(cm.getCursor("anchor"), Pos(4, 5)); cm.setExtending(false); cm.extendSelection(Pos(0, 3), Pos(0, 4)); eqCursorPos(cm.getCursor("head"), Pos(0, 3)); eqCursorPos(cm.getCursor("anchor"), Pos(0, 4)); }); testCM("lines", function(cm) { eq(cm.getLine(0), "111111"); eq(cm.getLine(1), "222222"); eq(cm.getLine(-1), null); cm.replaceRange("", Pos(1, 0), Pos(2, 0)) cm.replaceRange("abc", Pos(1, 0), Pos(1)); eq(cm.getValue(), "111111\nabc"); }, {value: "111111\n222222\n333333"}); testCM("indent", function(cm) { cm.indentLine(1); eq(cm.getLine(1), " blah();"); cm.setOption("indentUnit", 8); cm.indentLine(1); eq(cm.getLine(1), "\tblah();"); cm.setOption("indentUnit", 10); cm.setOption("tabSize", 4); cm.indentLine(1); eq(cm.getLine(1), "\t\t blah();"); }, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8}); testCM("indentByNumber", function(cm) { cm.indentLine(0, 2); eq(cm.getLine(0), " foo"); cm.indentLine(0, -200); eq(cm.getLine(0), "foo"); cm.setSelection(Pos(0, 0), Pos(1, 2)); cm.indentSelection(3); eq(cm.getValue(), " foo\n bar\nbaz"); }, {value: "foo\nbar\nbaz"}); test("core_defaults", function() { var defsCopy = {}, defs = CodeMirror.defaults; for (var opt in defs) defsCopy[opt] = defs[opt]; defs.indentUnit = 5; defs.value = "uu"; defs.indentWithTabs = true; defs.tabindex = 55; var place = document.getElementById("testground"), cm = CodeMirror(place); try { eq(cm.getOption("indentUnit"), 5); cm.setOption("indentUnit", 10); eq(defs.indentUnit, 5); eq(cm.getValue(), "uu"); eq(cm.getOption("indentWithTabs"), true); eq(cm.getInputField().tabIndex, 55); } finally { for (var opt in defsCopy) defs[opt] = defsCopy[opt]; place.removeChild(cm.getWrapperElement()); } }); testCM("lineInfo", function(cm) { eq(cm.lineInfo(-1), null); var mark = document.createElement("span"); var lh = cm.setGutterMarker(1, "FOO", mark); var info = cm.lineInfo(1); eq(info.text, "222222"); eq(info.gutterMarkers.FOO, mark); eq(info.line, 1); eq(cm.lineInfo(2).gutterMarkers, null); cm.setGutterMarker(lh, "FOO", null); eq(cm.lineInfo(1).gutterMarkers, null); cm.setGutterMarker(1, "FOO", mark); cm.setGutterMarker(0, "FOO", mark); cm.clearGutter("FOO"); eq(cm.lineInfo(0).gutterMarkers, null); eq(cm.lineInfo(1).gutterMarkers, null); }, {value: "111111\n222222\n333333"}); testCM("coords", function(cm) { cm.setSize(null, 100); addDoc(cm, 32, 200); var top = cm.charCoords(Pos(0, 0)); var bot = cm.charCoords(Pos(200, 30)); is(top.left < bot.left); is(top.top < bot.top); is(top.top < top.bottom); cm.scrollTo(null, 100); var top2 = cm.charCoords(Pos(0, 0)); is(top.top > top2.top); eq(top.left, top2.left); }); testCM("coordsChar", function(cm) { addDoc(cm, 35, 70); for (var i = 0; i < 2; ++i) { var sys = i ? "local" : "page"; for (var ch = 0; ch <= 35; ch += 5) { for (var line = 0; line < 70; line += 5) { cm.setCursor(line, ch); var coords = cm.charCoords(Pos(line, ch), sys); var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys); eqCharPos(pos, Pos(line, ch)); } } } }, {lineNumbers: true}); testCM("coordsCharBidi", function(cm) { addDoc(cm, 35, 70); // Put an rtl character into each line to trigger the bidi code path in coordsChar cm.setValue(cm.getValue().replace(/\bx/g, 'و')) for (var i = 0; i < 2; ++i) { var sys = i ? "local" : "page"; for (var ch = 2; ch <= 35; ch += 5) { for (var line = 0; line < 70; line += 5) { cm.setCursor(line, ch); var coords = cm.charCoords(Pos(line, ch), sys); var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys); eqCharPos(pos, Pos(line, ch)); } } } }, {lineNumbers: true}); testCM("badBidiOptimization", function(cm) { var coords = cm.charCoords(Pos(0, 34)) eqCharPos(cm.coordsChar({left: coords.right, top: coords.top + 2}), Pos(0, 34)) }, {value: "----------

    هل يمكنك اختيار مستوى قسط التأمين الذي ترغب بدفعه؟

    "}) testCM("posFromIndex", function(cm) { cm.setValue( "This function should\n" + "convert a zero based index\n" + "to line and ch." ); var examples = [ { index: -1, line: 0, ch: 0 }, // <- Tests clipping { index: 0, line: 0, ch: 0 }, { index: 10, line: 0, ch: 10 }, { index: 39, line: 1, ch: 18 }, { index: 55, line: 2, ch: 7 }, { index: 63, line: 2, ch: 15 }, { index: 64, line: 2, ch: 15 } // <- Tests clipping ]; for (var i = 0; i < examples.length; i++) { var example = examples[i]; var pos = cm.posFromIndex(example.index); eq(pos.line, example.line); eq(pos.ch, example.ch); if (example.index >= 0 && example.index < 64) eq(cm.indexFromPos(pos), example.index); } }); testCM("undo", function(cm) { cm.replaceRange("def", Pos(0, 0), Pos(0)); eq(cm.historySize().undo, 1); cm.undo(); eq(cm.getValue(), "abc"); eq(cm.historySize().undo, 0); eq(cm.historySize().redo, 1); cm.redo(); eq(cm.getValue(), "def"); eq(cm.historySize().undo, 1); eq(cm.historySize().redo, 0); cm.setValue("1\n\n\n2"); cm.clearHistory(); eq(cm.historySize().undo, 0); for (var i = 0; i < 20; ++i) { cm.replaceRange("a", Pos(0, 0)); cm.replaceRange("b", Pos(3, 0)); } eq(cm.historySize().undo, 40); for (var i = 0; i < 40; ++i) cm.undo(); eq(cm.historySize().redo, 40); eq(cm.getValue(), "1\n\n\n2"); }, {value: "abc"}); testCM("undoDepth", function(cm) { cm.replaceRange("d", Pos(0)); cm.replaceRange("e", Pos(0)); cm.replaceRange("f", Pos(0)); cm.undo(); cm.undo(); cm.undo(); eq(cm.getValue(), "abcd"); }, {value: "abc", undoDepth: 4}); testCM("undoDoesntClearValue", function(cm) { cm.undo(); eq(cm.getValue(), "x"); }, {value: "x"}); testCM("undoMultiLine", function(cm) { cm.operation(function() { cm.replaceRange("x", Pos(0, 0)); cm.replaceRange("y", Pos(1, 0)); }); cm.undo(); eq(cm.getValue(), "abc\ndef\nghi"); cm.operation(function() { cm.replaceRange("y", Pos(1, 0)); cm.replaceRange("x", Pos(0, 0)); }); cm.undo(); eq(cm.getValue(), "abc\ndef\nghi"); cm.operation(function() { cm.replaceRange("y", Pos(2, 0)); cm.replaceRange("x", Pos(1, 0)); cm.replaceRange("z", Pos(2, 0)); }); cm.undo(); eq(cm.getValue(), "abc\ndef\nghi", 3); }, {value: "abc\ndef\nghi"}); testCM("undoComposite", function(cm) { cm.replaceRange("y", Pos(1)); cm.operation(function() { cm.replaceRange("x", Pos(0)); cm.replaceRange("z", Pos(2)); }); eq(cm.getValue(), "ax\nby\ncz\n"); cm.undo(); eq(cm.getValue(), "a\nby\nc\n"); cm.undo(); eq(cm.getValue(), "a\nb\nc\n"); cm.redo(); cm.redo(); eq(cm.getValue(), "ax\nby\ncz\n"); }, {value: "a\nb\nc\n"}); testCM("undoSelection", function(cm) { cm.setSelection(Pos(0, 2), Pos(0, 4)); cm.replaceSelection(""); cm.setCursor(Pos(1, 0)); cm.undo(); eqCursorPos(cm.getCursor(true), Pos(0, 2)); eqCursorPos(cm.getCursor(false), Pos(0, 4)); cm.setCursor(Pos(1, 0)); cm.redo(); eqCursorPos(cm.getCursor(true), Pos(0, 2)); eqCursorPos(cm.getCursor(false), Pos(0, 2)); }, {value: "abcdefgh\n"}); testCM("undoSelectionAsBefore", function(cm) { cm.replaceSelection("abc", "around"); cm.undo(); cm.redo(); eq(cm.getSelection(), "abc"); }); testCM("selectionChangeConfusesHistory", function(cm) { cm.replaceSelection("abc", null, "dontmerge"); cm.operation(function() { cm.setCursor(Pos(0, 0)); cm.replaceSelection("abc", null, "dontmerge"); }); eq(cm.historySize().undo, 2); }); testCM("markTextSingleLine", function(cm) { forEach([{a: 0, b: 1, c: "", f: 2, t: 5}, {a: 0, b: 4, c: "", f: 0, t: 2}, {a: 1, b: 2, c: "x", f: 3, t: 6}, {a: 4, b: 5, c: "", f: 3, t: 5}, {a: 4, b: 5, c: "xx", f: 3, t: 7}, {a: 2, b: 5, c: "", f: 2, t: 3}, {a: 2, b: 5, c: "abcd", f: 6, t: 7}, {a: 2, b: 6, c: "x", f: null, t: null}, {a: 3, b: 6, c: "", f: null, t: null}, {a: 0, b: 9, c: "hallo", f: null, t: null}, {a: 4, b: 6, c: "x", f: 3, t: 4}, {a: 4, b: 8, c: "", f: 3, t: 4}, {a: 6, b: 6, c: "a", f: 3, t: 6}, {a: 8, b: 9, c: "", f: 3, t: 6}], function(test) { cm.setValue("1234567890"); var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: "foo"}); cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b)); var f = r.find(); eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t); }); }); testCM("markTextMultiLine", function(cm) { function p(v) { return v && Pos(v[0], v[1]); } forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]}, {a: [0, 0], b: [0, 5], c: "foo\n", f: [1, 0], t: [3, 5]}, {a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]}, {a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]}, {a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]}, {a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]}, {a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]}, {a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]}, {a: [0, 5], b: [2, 5], c: "xx", f: null, t: null}, {a: [0, 0], b: [2, 10], c: "x", f: null, t: null}, {a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]}, {a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]}, {a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]}, {a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]}, {a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) { cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n"); var r = cm.markText(Pos(0, 5), Pos(2, 5), {className: "CodeMirror-matchingbracket"}); cm.replaceRange(test.c, p(test.a), p(test.b)); var f = r.find(); eqCursorPos(f && f.from, p(test.f)); eqCursorPos(f && f.to, p(test.t)); }); }); testCM("markTextUndo", function(cm) { var marker1, marker2, bookmark; marker1 = cm.markText(Pos(0, 1), Pos(0, 3), {className: "CodeMirror-matchingbracket"}); marker2 = cm.markText(Pos(0, 0), Pos(2, 1), {className: "CodeMirror-matchingbracket"}); bookmark = cm.setBookmark(Pos(1, 5)); cm.operation(function(){ cm.replaceRange("foo", Pos(0, 2)); cm.replaceRange("bar\nbaz\nbug\n", Pos(2, 0), Pos(3, 0)); }); var v1 = cm.getValue(); cm.setValue(""); eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null); cm.undo(); eqCursorPos(bookmark.find(), Pos(1, 5), "still there"); cm.undo(); var m1Pos = marker1.find(), m2Pos = marker2.find(); eqCursorPos(m1Pos.from, Pos(0, 1)); eqCursorPos(m1Pos.to, Pos(0, 3)); eqCursorPos(m2Pos.from, Pos(0, 0)); eqCursorPos(m2Pos.to, Pos(2, 1)); eqCursorPos(bookmark.find(), Pos(1, 5)); cm.redo(); cm.redo(); eq(bookmark.find(), null); cm.undo(); eqCursorPos(bookmark.find(), Pos(1, 5)); eq(cm.getValue(), v1); }, {value: "1234\n56789\n00\n"}); testCM("markTextStayGone", function(cm) { var m1 = cm.markText(Pos(0, 0), Pos(0, 1)); cm.replaceRange("hi", Pos(0, 2)); m1.clear(); cm.undo(); eq(m1.find(), null); }, {value: "hello"}); testCM("markTextAllowEmpty", function(cm) { var m1 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false}); is(m1.find()); cm.replaceRange("x", Pos(0, 0)); is(m1.find()); cm.replaceRange("y", Pos(0, 2)); is(m1.find()); cm.replaceRange("z", Pos(0, 3), Pos(0, 4)); is(!m1.find()); var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false, inclusiveLeft: true, inclusiveRight: true}); cm.replaceRange("q", Pos(0, 1), Pos(0, 2)); is(m2.find()); cm.replaceRange("", Pos(0, 0), Pos(0, 3)); is(!m2.find()); var m3 = cm.markText(Pos(0, 1), Pos(0, 1), {clearWhenEmpty: false}); cm.replaceRange("a", Pos(0, 3)); is(m3.find()); cm.replaceRange("b", Pos(0, 1)); is(!m3.find()); }, {value: "abcde"}); testCM("markTextStacked", function(cm) { var m1 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false}); var m2 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false}); cm.replaceRange("B", Pos(0, 1)); is(m1.find() && m2.find()); }, {value: "A"}); testCM("undoPreservesNewMarks", function(cm) { cm.markText(Pos(0, 3), Pos(0, 4)); cm.markText(Pos(1, 1), Pos(1, 3)); cm.replaceRange("", Pos(0, 3), Pos(3, 1)); var mBefore = cm.markText(Pos(0, 0), Pos(0, 1)); var mAfter = cm.markText(Pos(0, 5), Pos(0, 6)); var mAround = cm.markText(Pos(0, 2), Pos(0, 4)); cm.undo(); eqCursorPos(mBefore.find().from, Pos(0, 0)); eqCursorPos(mBefore.find().to, Pos(0, 1)); eqCursorPos(mAfter.find().from, Pos(3, 3)); eqCursorPos(mAfter.find().to, Pos(3, 4)); eqCursorPos(mAround.find().from, Pos(0, 2)); eqCursorPos(mAround.find().to, Pos(3, 2)); var found = cm.findMarksAt(Pos(2, 2)); eq(found.length, 1); eq(found[0], mAround); }, {value: "aaaa\nbbbb\ncccc\ndddd"}); testCM("markClearBetween", function(cm) { cm.setValue("aaa\nbbb\nccc\nddd\n"); cm.markText(Pos(0, 0), Pos(2)); cm.replaceRange("aaa\nbbb\nccc", Pos(0, 0), Pos(2)); eq(cm.findMarksAt(Pos(1, 1)).length, 0); }); testCM("findMarksMiddle", function(cm) { var mark = cm.markText(Pos(1, 1), Pos(3, 1)); var found = cm.findMarks(Pos(2, 1), Pos(2, 2)); eq(found.length, 1); eq(found[0], mark); }, {value: "line 0\nline 1\nline 2\nline 3"}); testCM("deleteSpanCollapsedInclusiveLeft", function(cm) { var from = Pos(1, 0), to = Pos(1, 1); var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true}); // Delete collapsed span. cm.replaceRange("", from, to); }, {value: "abc\nX\ndef"}); testCM("markTextCSS", function(cm) { function present() { var spans = cm.display.lineDiv.getElementsByTagName("span"); for (var i = 0; i < spans.length; i++) if (spans[i].style.color && spans[i].textContent == "cdef") return true; } var m = cm.markText(Pos(0, 2), Pos(0, 6), {css: "color: cyan"}); is(present()); m.clear(); is(!present()); }, {value: "abcdefgh"}); testCM("markTextWithAttributes", function(cm) { function present() { var spans = cm.display.lineDiv.getElementsByTagName("span"); for (var i = 0; i < spans.length; i++) if (spans[i].getAttribute("label") == "label" && spans[i].textContent == "cdef") return true; } var m = cm.markText(Pos(0, 2), Pos(0, 6), {attributes: {label: "label"}}); is(present()); m.clear(); is(!present()); }, {value: "abcdefgh"}); testCM("bookmark", function(cm) { function p(v) { return v && Pos(v[0], v[1]); } forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]}, {a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]}, {a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]}, {a: [1, 4], b: [1, 6], c: "", d: null}, {a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]}, {a: [1, 6], b: [1, 8], c: "", d: [1, 5]}, {a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]}, {bm: [1, 9], a: [1, 1], b: [1, 1], c: "\n", d: [2, 8]}], function(test) { cm.setValue("1234567890\n1234567890\n1234567890"); var b = cm.setBookmark(p(test.bm) || Pos(1, 5)); cm.replaceRange(test.c, p(test.a), p(test.b)); eqCursorPos(b.find(), p(test.d)); }); }); testCM("bookmarkInsertLeft", function(cm) { var br = cm.setBookmark(Pos(0, 2), {insertLeft: false}); var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true}); cm.setCursor(Pos(0, 2)); cm.replaceSelection("hi"); eqCursorPos(br.find(), Pos(0, 2)); eqCursorPos(bl.find(), Pos(0, 4)); cm.replaceRange("", Pos(0, 4), Pos(0, 5)); cm.replaceRange("", Pos(0, 2), Pos(0, 4)); cm.replaceRange("", Pos(0, 1), Pos(0, 2)); // Verify that deleting next to bookmarks doesn't kill them eqCursorPos(br.find(), Pos(0, 1)); eqCursorPos(bl.find(), Pos(0, 1)); }, {value: "abcdef"}); testCM("bookmarkCursor", function(cm) { var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)), pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)), pos41 = cm.cursorCoords(Pos(4, 1)); cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true}); cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true}); cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")}); cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")}); var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)), new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0)); near(new01.left, pos01.left, 1); near(new01.top, pos01.top, 1); is(new11.left > pos11.left, "at right, middle of line"); near(new11.top == pos11.top, 1); near(new20.left, pos20.left, 1); near(new20.top, pos20.top, 1); is(new30.left > pos30.left, "at right, empty line"); near(new30.top, pos30, 1); cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")}); is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug"); }, {value: "foo\nbar\n\n\nx\ny"}); testCM("multiBookmarkCursor", function(cm) { if (phantom) return; var ms = [], m; function add(insertLeft) { for (var i = 0; i < 3; ++i) { var node = document.createElement("span"); node.innerHTML = "X"; ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft})); } } var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left; add(true); near(base1, cm.cursorCoords(Pos(0, 1)).left, 1); while (m = ms.pop()) m.clear(); add(false); near(base4, cm.cursorCoords(Pos(0, 1)).left, 1); }, {value: "abcdefg"}); testCM("getAllMarks", function(cm) { addDoc(cm, 10, 10); var m1 = cm.setBookmark(Pos(0, 2)); var m2 = cm.markText(Pos(0, 2), Pos(3, 2)); var m3 = cm.markText(Pos(1, 2), Pos(1, 8)); var m4 = cm.markText(Pos(8, 0), Pos(9, 0)); eq(cm.getAllMarks().length, 4); m1.clear(); m3.clear(); eq(cm.getAllMarks().length, 2); }); testCM("setValueClears", function(cm) { cm.addLineClass(0, "wrap", "foo"); var mark = cm.markText(Pos(0, 0), Pos(1, 1), {inclusiveLeft: true, inclusiveRight: true}); cm.setValue("foo"); is(!cm.lineInfo(0).wrapClass); is(!mark.find()); }, {value: "a\nb"}); testCM("bug577", function(cm) { cm.setValue("a\nb"); cm.clearHistory(); cm.setValue("fooooo"); cm.undo(); }); testCM("scrollSnap", function(cm) { cm.setSize(100, 100); addDoc(cm, 200, 200); cm.setCursor(Pos(100, 180)); var info = cm.getScrollInfo(); is(info.left > 0 && info.top > 0); cm.setCursor(Pos(0, 0)); info = cm.getScrollInfo(); is(info.left == 0 && info.top == 0, "scrolled clean to top"); cm.setCursor(Pos(100, 180)); cm.setCursor(Pos(199, 0)); info = cm.getScrollInfo(); is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom"); }); testCM("scrollIntoView", function(cm) { if (phantom) return; function test(line, ch, msg) { var pos = Pos(line, ch); cm.scrollIntoView(pos); var outer = cm.getWrapperElement().getBoundingClientRect(); var box = cm.charCoords(pos, "window"); is(box.left >= outer.left, msg + " (left)"); is(box.right <= outer.right, msg + " (right)"); is(box.top >= outer.top, msg + " (top)"); is(box.bottom <= outer.bottom, msg + " (bottom)"); } addDoc(cm, 200, 200); test(199, 199, "bottom right"); test(0, 0, "top left"); test(100, 100, "center"); test(199, 0, "bottom left"); test(0, 199, "top right"); test(100, 100, "center again"); }); testCM("scrollBackAndForth", function(cm) { addDoc(cm, 1, 200); cm.operation(function() { cm.scrollIntoView(Pos(199, 0)); cm.scrollIntoView(Pos(4, 0)); }); is(cm.getScrollInfo().top > 0); }); testCM("selectAllNoScroll", function(cm) { addDoc(cm, 1, 200); cm.execCommand("selectAll"); eq(cm.getScrollInfo().top, 0); cm.setCursor(199); cm.execCommand("selectAll"); is(cm.getScrollInfo().top > 0); }); testCM("selectionPos", function(cm) { if (phantom || cm.getOption("inputStyle") != "textarea") return; cm.setSize(100, 100); addDoc(cm, 200, 100); cm.setSelection(Pos(1, 100), Pos(98, 100)); var lineWidth = cm.charCoords(Pos(0, 200), "local").left; var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100; cm.scrollTo(0, 0); var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected"); var outer = cm.getWrapperElement().getBoundingClientRect(); var sawMiddle, sawTop, sawBottom; for (var i = 0, e = selElt.length; i < e; ++i) { var box = selElt[i].getBoundingClientRect(); var atLeft = box.left - outer.left < 30; var width = box.right - box.left; var atRight = box.right - outer.left > .8 * lineWidth; if (atLeft && atRight) { sawMiddle = true; is(box.bottom - box.top > 90 * lineHeight, "middle high"); is(width > .9 * lineWidth, "middle wide"); } else { is(width > .4 * lineWidth, "top/bot wide enough"); is(width < .6 * lineWidth, "top/bot slim enough"); if (atLeft) { sawBottom = true; is(box.top - outer.top > 96 * lineHeight, "bot below"); } else if (atRight) { sawTop = true; is(box.top - outer.top < 2.1 * lineHeight, "top above"); } } } is(sawTop && sawBottom && sawMiddle, "all parts"); }, null); testCM("restoreHistory", function(cm) { cm.setValue("abc\ndef"); cm.replaceRange("hello", Pos(1, 0), Pos(1)); cm.replaceRange("goop", Pos(0, 0), Pos(0)); cm.undo(); var storedVal = cm.getValue(), storedHist = cm.getHistory(); if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist)); eq(storedVal, "abc\nhello"); cm.setValue(""); cm.clearHistory(); eq(cm.historySize().undo, 0); cm.setValue(storedVal); cm.setHistory(storedHist); cm.redo(); eq(cm.getValue(), "goop\nhello"); cm.undo(); cm.undo(); eq(cm.getValue(), "abc\ndef"); }); testCM("doubleScrollbar", function(cm) { var dummy = document.body.appendChild(document.createElement("p")); dummy.style.cssText = "height: 50px; overflow: scroll; width: 50px"; var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth; document.body.removeChild(dummy); if (scrollbarWidth < 2) return; cm.setSize(null, 100); addDoc(cm, 1, 300); var wrap = cm.getWrapperElement(); is(wrap.offsetWidth - byClassName(wrap, "CodeMirror-lines")[0].offsetWidth <= scrollbarWidth * 1.5); }); testCM("weirdLinebreaks", function(cm) { cm.setValue("foo\nbar\rbaz\r\nquux\n\rplop"); is(cm.getValue(), "foo\nbar\nbaz\nquux\n\nplop"); is(cm.lineCount(), 6); cm.setValue("\n\n"); is(cm.lineCount(), 3); }); testCM("setSize", function(cm) { cm.setSize(100, 100); var wrap = cm.getWrapperElement(); is(wrap.offsetWidth, 100); is(wrap.offsetHeight, 100); cm.setSize("100%", "3em"); is(wrap.style.width, "100%"); is(wrap.style.height, "3em"); cm.setSize(null, 40); is(wrap.style.width, "100%"); is(wrap.style.height, "40px"); }); function foldLines(cm, start, end, autoClear) { return cm.markText(Pos(start, 0), Pos(end - 1), { inclusiveLeft: true, inclusiveRight: true, collapsed: true, clearOnEnter: autoClear }); } testCM("collapsedLines", function(cm) { addDoc(cm, 4, 10); var range = foldLines(cm, 4, 5), cleared = 0; CodeMirror.on(range, "clear", function() {cleared++;}); cm.setCursor(Pos(3, 0)); CodeMirror.commands.goLineDown(cm); eqCharPos(cm.getCursor(), Pos(5, 0)); cm.replaceRange("abcdefg", Pos(3, 0), Pos(3)); cm.setCursor(Pos(3, 6)); CodeMirror.commands.goLineDown(cm); eqCharPos(cm.getCursor(), Pos(5, 4)); cm.replaceRange("ab", Pos(3, 0), Pos(3)); cm.setCursor(Pos(3, 2)); CodeMirror.commands.goLineDown(cm); eqCharPos(cm.getCursor(), Pos(5, 2)); cm.operation(function() {range.clear(); range.clear();}); eq(cleared, 1); }); testCM("collapsedRangeCoordsChar", function(cm) { var pos_1_3 = cm.charCoords(Pos(1, 3)); pos_1_3.left += 2; pos_1_3.top += 2; var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true}; var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts); eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); m1.clear(); var m1 = cm.markText(Pos(0, 0), Pos(1, 1), {collapsed: true, inclusiveLeft: true}); var m2 = cm.markText(Pos(1, 1), Pos(2, 0), {collapsed: true, inclusiveRight: true}); eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); m1.clear(); m2.clear(); var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts); eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3)); }, {value: "123456\nabcdef\nghijkl\nmnopqr\n"}); testCM("collapsedRangeBetweenLinesSelected", function(cm) { if (cm.getOption("inputStyle") != "textarea") return; var widget = document.createElement("span"); widget.textContent = "\u2194"; cm.markText(Pos(0, 3), Pos(1, 0), {replacedWith: widget}); cm.setSelection(Pos(0, 3), Pos(1, 0)); var selElts = byClassName(cm.getWrapperElement(), "CodeMirror-selected"); for (var i = 0, w = 0; i < selElts.length; i++) w += selElts[i].offsetWidth; is(w > 0); }, {value: "one\ntwo"}); testCM("randomCollapsedRanges", function(cm) { addDoc(cm, 20, 500); cm.operation(function() { for (var i = 0; i < 200; i++) { var start = Pos(Math.floor(Math.random() * 500), Math.floor(Math.random() * 20)); if (i % 4) try { cm.markText(start, Pos(start.line + 2, 1), {collapsed: true}); } catch(e) { if (!/overlapping/.test(String(e))) throw e; } else cm.markText(start, Pos(start.line, start.ch + 4), {"className": "foo"}); } }); }); testCM("hiddenLinesAutoUnfold", function(cm) { var range = foldLines(cm, 1, 3, true), cleared = 0; CodeMirror.on(range, "clear", function() {cleared++;}); cm.setCursor(Pos(3, 0)); eq(cleared, 0); cm.execCommand("goCharLeft"); eq(cleared, 1); range = foldLines(cm, 1, 3, true); CodeMirror.on(range, "clear", function() {cleared++;}); eqCursorPos(cm.getCursor(), Pos(3, 0)); cm.setCursor(Pos(0, 3)); cm.execCommand("goCharRight"); eq(cleared, 2); }, {value: "abc\ndef\nghi\njkl"}); testCM("hiddenLinesSelectAll", function(cm) { // Issue #484 addDoc(cm, 4, 20); foldLines(cm, 0, 10); foldLines(cm, 11, 20); CodeMirror.commands.selectAll(cm); eqCursorPos(cm.getCursor(true), Pos(10, 0)); eqCursorPos(cm.getCursor(false), Pos(10, 4)); }); testCM("clickFold", function(cm) { // Issue #5392 cm.setValue("foo { bar }") var widget = document.createElement("span") widget.textContent = "<>" cm.markText(Pos(0, 5), Pos(0, 10), {replacedWith: widget}) var after = cm.charCoords(Pos(0, 10)) var foundOn = cm.coordsChar({left: after.left - 1, top: after.top + 4}) is(foundOn.ch <= 5 || foundOn.ch >= 10, "Position is not inside the folded range") }) testCM("everythingFolded", function(cm) { addDoc(cm, 2, 2); function enterPress() { cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}}); } var fold = foldLines(cm, 0, 2); enterPress(); eq(cm.getValue(), "xx\nxx"); fold.clear(); fold = foldLines(cm, 0, 2, true); eq(fold.find(), null); enterPress(); eq(cm.getValue(), "\nxx\nxx"); }); testCM("structuredFold", function(cm) { if (phantom) return; addDoc(cm, 4, 8); var range = cm.markText(Pos(1, 2), Pos(6, 2), { replacedWith: document.createTextNode("Q") }); cm.setCursor(0, 3); CodeMirror.commands.goLineDown(cm); eqCharPos(cm.getCursor(), Pos(6, 2)); CodeMirror.commands.goCharLeft(cm); eqCharPos(cm.getCursor(), Pos(1, 2)); CodeMirror.commands.delCharAfter(cm); eq(cm.getValue(), "xxxx\nxxxx\nxxxx"); addDoc(cm, 4, 8); range = cm.markText(Pos(1, 2), Pos(6, 2), { replacedWith: document.createTextNode("M"), clearOnEnter: true }); var cleared = 0; CodeMirror.on(range, "clear", function(){++cleared;}); cm.setCursor(0, 3); CodeMirror.commands.goLineDown(cm); eqCharPos(cm.getCursor(), Pos(6, 2)); CodeMirror.commands.goCharLeft(cm); eqCharPos(cm.getCursor(), Pos(6, 1)); eq(cleared, 1); range.clear(); eq(cleared, 1); range = cm.markText(Pos(1, 2), Pos(6, 2), { replacedWith: document.createTextNode("Q"), clearOnEnter: true }); range.clear(); cm.setCursor(1, 2); CodeMirror.commands.goCharRight(cm); eqCharPos(cm.getCursor(), Pos(1, 3)); range = cm.markText(Pos(2, 0), Pos(4, 4), { replacedWith: document.createTextNode("M") }); cm.setCursor(1, 0); CodeMirror.commands.goLineDown(cm); eqCharPos(cm.getCursor(), Pos(2, 0)); }, null); testCM("nestedFold", function(cm) { addDoc(cm, 10, 3); function fold(ll, cl, lr, cr) { return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true}); } 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); cm.setCursor(0, 1); CodeMirror.commands.goCharRight(cm); eqCursorPos(cm.getCursor(), Pos(2, 3)); inner0.clear(); CodeMirror.commands.goCharLeft(cm); eqCursorPos(cm.getCursor(), Pos(0, 1)); outer.clear(); CodeMirror.commands.goCharRight(cm); eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); CodeMirror.commands.goCharRight(cm); eqCursorPos(cm.getCursor(), Pos(1, 8)); inner2.clear(); CodeMirror.commands.goCharLeft(cm); eqCursorPos(cm.getCursor(), Pos(1, 7, "after")); cm.setCursor(0, 5); CodeMirror.commands.goCharRight(cm); eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); CodeMirror.commands.goCharRight(cm); eqCursorPos(cm.getCursor(), Pos(1, 3)); }); testCM("badNestedFold", function(cm) { addDoc(cm, 4, 4); cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true}); var caught; try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});} catch(e) {caught = e;} is(caught instanceof Error, "no error"); is(/overlap/i.test(caught.message), "wrong error"); }); testCM("nestedFoldOnSide", function(cm) { var m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true, inclusiveRight: true}); var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}); cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}).clear(); try { cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true, inclusiveLeft: true}); } catch(e) { var caught = e; } is(caught && /overlap/i.test(caught.message)); var m3 = cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}); var m4 = cm.markText(Pos(2, 0), Pos(2, 1), {collapse: true, inclusiveRight: true}); m1.clear(); m4.clear(); m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true}); cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}).clear(); try { cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true, inclusiveRight: true}); } catch(e) { var caught = e; } is(caught && /overlap/i.test(caught.message)); }, {value: "ab\ncd\ef"}); testCM("editInFold", function(cm) { addDoc(cm, 4, 6); var m = cm.markText(Pos(1, 2), Pos(3, 2), {collapsed: true}); cm.replaceRange("", Pos(0, 0), Pos(1, 3)); cm.replaceRange("", Pos(2, 1), Pos(3, 3)); cm.replaceRange("a\nb\nc\nd", Pos(0, 1), Pos(1, 0)); cm.cursorCoords(Pos(0, 0)); }); testCM("wrappingInlineWidget", function(cm) { cm.setSize("11em"); var w = document.createElement("span"); w.style.color = "red"; w.innerHTML = "one two three four"; cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w}); var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10)); is(cur0.top < cur1.top); is(cur0.bottom < cur1.bottom); var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9)); eq(curL.top, cur0.top); eq(curL.bottom, cur0.bottom); eq(curR.top, cur1.top); eq(curR.bottom, cur1.bottom); cm.replaceRange("", Pos(0, 9), Pos(0)); curR = cm.cursorCoords(Pos(0, 9)); if (phantom) return; eq(curR.top, cur1.top); eq(curR.bottom, cur1.bottom); }, {value: "1 2 3 xxx 4", lineWrapping: true}); testCM("showEmptyWidgetSpan", function(cm) { var marker = cm.markText(Pos(0, 2), Pos(0, 2), { clearWhenEmpty: false, replacedWith: document.createTextNode("X") }); var text = cm.display.view[0].text; eq(text.textContent || text.innerText, "abXc"); }, {value: "abc"}); testCM("changedInlineWidget", function(cm) { cm.setSize("10em"); var w = document.createElement("span"); w.innerHTML = "x"; var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w}); w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; m.changed(); var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; is(hScroll.scrollWidth > hScroll.clientWidth); }, {value: "hello there"}); testCM("changedBookmark", function(cm) { cm.setSize("10em"); var w = document.createElement("span"); w.innerHTML = "x"; var m = cm.setBookmark(Pos(0, 4), {widget: w}); w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed"; m.changed(); var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0]; is(hScroll.scrollWidth > hScroll.clientWidth); }, {value: "abcdefg"}); testCM("inlineWidget", function(cm) { var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")}); cm.setCursor(0, 2); CodeMirror.commands.goLineDown(cm); eqCharPos(cm.getCursor(), Pos(1, 4)); cm.setCursor(0, 2); cm.replaceSelection("hi"); eqCharPos(w.find(), Pos(0, 2)); cm.setCursor(0, 1); cm.replaceSelection("ay"); eqCharPos(w.find(), Pos(0, 4)); eq(cm.getLine(0), "uayuhiuu"); }, {value: "uuuu\nuuuuuu"}); testCM("wrappingAndResizing", function(cm) { cm.setSize(null, "auto"); cm.setOption("lineWrapping", true); var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight; var doc = "xxx xxx xxx xxx xxx"; cm.setValue(doc); for (var step = 10, w = cm.charCoords(Pos(0, 18), "div").right;; w += step) { cm.setSize(w); if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) { if (step == 10) { w -= 10; step = 1; } else break; } } // Ensure that putting the cursor at the end of the maximally long // line doesn't cause wrapping to happen. cm.setCursor(Pos(0, doc.length)); eq(wrap.offsetHeight, h0); cm.replaceSelection("x"); is(wrap.offsetHeight > h0, "wrapping happens"); // Now add a max-height and, in a document consisting of // almost-wrapped lines, go over it so that a scrollbar appears. cm.setValue(doc + "\n" + doc + "\n"); cm.getScrollerElement().style.maxHeight = "100px"; 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)); forEach([Pos(0, doc.length), Pos(0, doc.length - 1), Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)], function(pos) { var coords = cm.charCoords(pos); eqCharPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5})); }); }, null, ie_lt8); testCM("measureEndOfLine", function(cm) { if (phantom) return; cm.setSize(null, "auto"); var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; var lh = inner.offsetHeight; for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { cm.setSize(w); if (inner.offsetHeight < 2.5 * lh) { if (step == 10) { w -= 10; step = 1; } else break; } } cm.setValue(cm.getValue() + "\n\n"); var endPos = cm.charCoords(Pos(0, 18), "local"); is(endPos.top > lh * .8, "not at top"); is(endPos.left > w - 20, "at right"); endPos = cm.charCoords(Pos(0, 18)); eqCursorPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18, "before")); var wrapPos = cm.cursorCoords(Pos(0, 9, "before")); is(wrapPos.top < endPos.top, "wrapPos is actually in first line"); eqCursorPos(cm.coordsChar({left: wrapPos.left + 10, top: wrapPos.top}), Pos(0, 9, "before")); }, {mode: "text/html", value: "", lineWrapping: true}, ie_lt8 || opera_lt10); testCM("measureWrappedEndOfLine", function(cm) { if (phantom) return; cm.setSize(null, "auto"); var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; var lh = inner.offsetHeight; for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { cm.setSize(w); if (inner.offsetHeight < 2.5 * lh) { if (step == 10) { w -= 10; step = 1; } else break; } } for (var i = 0; i < 3; ++i) { var endPos = cm.charCoords(Pos(0, 12)); // Next-to-last since last would wrap (#1862) endPos.left += w; // Add width of editor just to be sure that we are behind last character eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before")); endPos.left += w * 100; eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before")); cm.setValue("0123456789abcابجابجابجابج"); if (i == 1) { var node = document.createElement("div"); node.innerHTML = "hi"; node.style.height = "30px"; cm.addLineWidget(0, node, {above: true}); } } }, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true}, ie_lt8 || opera_lt10); testCM("measureEndOfLineBidi", function(cm) { eqCursorPos(cm.coordsChar({left: 5000, top: cm.charCoords(Pos(0, 0)).top}), Pos(0, 8, "after")) }, {value: "إإإإuuuuإإإإ"}) testCM("measureWrappedBidiLevel2", function(cm) { cm.setSize(cm.charCoords(Pos(0, 6), "editor").right + 60) var c9 = cm.charCoords(Pos(0, 9)) eqCharPos(cm.coordsChar({left: c9.right - 1, top: c9.top + 1}), Pos(0, 9)) }, {value: "foobar إإ إإ إإ إإ 555 بببببب", lineWrapping: true}) testCM("measureWrappedBeginOfLine", function(cm) { if (phantom) return; cm.setSize(null, "auto"); var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild; var lh = inner.offsetHeight; for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) { cm.setSize(w); if (inner.offsetHeight < 2.5 * lh) { if (step == 10) { w -= 10; step = 1; } else break; } } var beginOfSecondLine = Pos(0, 13, "after"); for (var i = 0; i < 2; ++i) { var beginPos = cm.charCoords(Pos(0, 0)); beginPos.left -= w; eqCursorPos(cm.coordsChar(beginPos), Pos(0, 0, "after")); beginPos = cm.cursorCoords(beginOfSecondLine); beginPos.left = 0; eqCursorPos(cm.coordsChar(beginPos), beginOfSecondLine); cm.setValue("0123456789abcابجابجابجابج"); beginOfSecondLine = Pos(0, 25, "before"); } }, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true}); testCM("scrollVerticallyAndHorizontally", function(cm) { if (cm.getOption("inputStyle") != "textarea") return; cm.setSize(100, 100); addDoc(cm, 40, 40); cm.setCursor(39); var wrap = cm.getWrapperElement(), bar = byClassName(wrap, "CodeMirror-vscrollbar")[0]; is(bar.offsetHeight < wrap.offsetHeight, "vertical scrollbar limited by horizontal one"); var cursorBox = byClassName(wrap, "CodeMirror-cursor")[0].getBoundingClientRect(); var editorBox = wrap.getBoundingClientRect(); is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight, "bottom line visible"); }, {lineNumbers: true}); testCM("moveVstuck", function(cm) { var lines = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild, h0 = lines.offsetHeight; var val = "fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\n"; cm.setValue(val); for (var w = cm.charCoords(Pos(0, 26), "div").right * 2.8;; w += 5) { cm.setSize(w); if (lines.offsetHeight <= 3.5 * h0) break; } cm.setCursor(Pos(0, val.length - 1)); cm.moveV(-1, "line"); eqCursorPos(cm.getCursor(), Pos(0, 27, "before")); is(cm.cursorCoords(null, "local").top < h0, "cursor is in first visual line"); }, {lineWrapping: true}, ie_lt8 || opera_lt10); testCM("collapseOnMove", function(cm) { cm.setSelection(Pos(0, 1), Pos(2, 4)); cm.execCommand("goLineUp"); is(!cm.somethingSelected()); eqCharPos(cm.getCursor(), Pos(0, 1)); cm.setSelection(Pos(0, 1), Pos(2, 4)); cm.execCommand("goPageDown"); is(!cm.somethingSelected()); eqCharPos(cm.getCursor(), Pos(2, 4)); cm.execCommand("goLineUp"); cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(0, 4)); cm.setSelection(Pos(0, 1), Pos(2, 4)); cm.execCommand("goCharLeft"); is(!cm.somethingSelected()); eqCharPos(cm.getCursor(), Pos(0, 1)); }, {value: "aaaaa\nb\nccccc"}); testCM("clickTab", function(cm) { var p0 = cm.charCoords(Pos(0, 0)); eqCharPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0)); eqCharPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1)); }, {value: "\t\n\n", lineWrapping: true, tabSize: 8}); testCM("verticalScroll", function(cm) { cm.setSize(100, 200); cm.setValue("foo\nbar\nbaz\n"); var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth; cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0)); is(sc.scrollWidth > baseWidth, "scrollbar present"); cm.replaceRange("foo", Pos(0, 0), Pos(0)); if (!phantom) eq(sc.scrollWidth, baseWidth, "scrollbar gone"); cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0)); cm.replaceRange("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh", Pos(1, 0), Pos(1)); is(sc.scrollWidth > baseWidth, "present again"); var curWidth = sc.scrollWidth; cm.replaceRange("foo", Pos(0, 0), Pos(0)); is(sc.scrollWidth < curWidth, "scrollbar smaller"); is(sc.scrollWidth > baseWidth, "but still present"); }); testCM("extraKeys", function(cm) { var outcome; function fakeKey(expected, code, props) { if (typeof code == "string") code = code.charCodeAt(0); var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}}; if (props) for (var n in props) e[n] = props[n]; outcome = null; cm.triggerOnKeyDown(e); eq(outcome, expected); } CodeMirror.commands.testCommand = function() {outcome = "tc";}; CodeMirror.commands.goTestCommand = function() {outcome = "gtc";}; cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";}, "X": function() {outcome = "x";}, "Ctrl-Alt-U": function() {outcome = "cau";}, "End": "testCommand", "Home": "goTestCommand", "Tab": false}); fakeKey(null, "U"); fakeKey("cau", "U", {ctrlKey: true, altKey: true}); fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true}); fakeKey("x", "X"); fakeKey("sx", "X", {shiftKey: true}); fakeKey("tc", 35); fakeKey(null, 35, {shiftKey: true}); fakeKey("gtc", 36); fakeKey("gtc", 36, {shiftKey: true}); fakeKey(null, 9); }, null, window.opera && mac); testCM("wordMovementCommands", function(cm) { cm.execCommand("goWordLeft"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); eqCursorPos(cm.getCursor(), Pos(0, 7, "before")); cm.execCommand("goWordLeft"); eqCursorPos(cm.getCursor(), Pos(0, 5, "after")); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); eqCursorPos(cm.getCursor(), Pos(0, 12, "before")); cm.execCommand("goWordLeft"); eqCursorPos(cm.getCursor(), Pos(0, 9, "after")); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); eqCursorPos(cm.getCursor(), Pos(0, 24, "before")); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); eqCursorPos(cm.getCursor(), Pos(1, 9, "before")); cm.execCommand("goWordRight"); eqCursorPos(cm.getCursor(), Pos(1, 13, "before")); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); eqCharPos(cm.getCursor(), Pos(2, 0)); }, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"}); testCM("groupMovementCommands", function(cm) { cm.execCommand("goGroupLeft"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(0, 7, "before")); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(0, 10, "before")); cm.execCommand("goGroupLeft"); eqCursorPos(cm.getCursor(), Pos(0, 7, "after")); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(0, 15, "before")); cm.setCursor(Pos(0, 17)); cm.execCommand("goGroupLeft"); eqCursorPos(cm.getCursor(), Pos(0, 16, "after")); cm.execCommand("goGroupLeft"); eqCursorPos(cm.getCursor(), Pos(0, 14, "after")); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(0, 20, "before")); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(1, 2, "before")); cm.execCommand("goGroupRight"); eqCursorPos(cm.getCursor(), Pos(1, 5, "before")); cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft"); eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); cm.execCommand("goGroupLeft"); eqCursorPos(cm.getCursor(), Pos(0, 20, "after")); cm.execCommand("goGroupLeft"); eqCursorPos(cm.getCursor(), Pos(0, 16, "after")); }, {value: "booo ba---quux. ffff\n abc d"}); testCM("groupsAndWhitespace", function(cm) { var positions = [Pos(0, 0), Pos(0, 2), Pos(0, 5), Pos(0, 9), Pos(0, 11), Pos(1, 0), Pos(1, 2), Pos(1, 5)]; for (var i = 1; i < positions.length; i++) { cm.execCommand("goGroupRight"); eqCharPos(cm.getCursor(), positions[i]); } for (var i = positions.length - 2; i >= 0; i--) { cm.execCommand("goGroupLeft"); eqCharPos(cm.getCursor(), i == 2 ? Pos(0, 6, "before") : positions[i]); } }, {value: " foo +++ \n bar"}); testCM("charMovementCommands", function(cm) { cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); cm.setCursor(Pos(1, 0)); cm.execCommand("goColumnLeft"); eqCursorPos(cm.getCursor(), Pos(1, 0)); cm.execCommand("goCharLeft"); eqCursorPos(cm.getCursor(), Pos(0, 5, "before")); cm.execCommand("goColumnRight"); eqCursorPos(cm.getCursor(), Pos(0, 5, "before")); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); cm.execCommand("goLineEnd"); eqCursorPos(cm.getCursor(), Pos(1, 5, "before")); cm.execCommand("goLineStartSmart"); eqCursorPos(cm.getCursor(), Pos(1, 1, "after")); cm.execCommand("goLineStartSmart"); eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); cm.setCursor(Pos(2, 0)); cm.execCommand("goCharRight"); cm.execCommand("goColumnRight"); eqCursorPos(cm.getCursor(), Pos(2, 0)); }, {value: "line1\n ine2\n"}); testCM("verticalMovementCommands", function(cm) { cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goLineDown"); if (!phantom) // This fails in PhantomJS, though not in a real Webkit eqCharPos(cm.getCursor(), Pos(1, 0)); cm.setCursor(Pos(1, 12)); cm.execCommand("goLineDown"); eqCharPos(cm.getCursor(), Pos(2, 5)); cm.execCommand("goLineDown"); eqCharPos(cm.getCursor(), Pos(3, 0)); cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(2, 5)); cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(1, 12)); cm.execCommand("goPageDown"); eqCharPos(cm.getCursor(), Pos(5, 0)); cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); eqCharPos(cm.getCursor(), Pos(5, 0)); cm.execCommand("goPageUp"); eqCharPos(cm.getCursor(), Pos(0, 0)); }, {value: "line1\nlong long line2\nline3\n\nline5\n"}); testCM("verticalMovementCommandsWrapping", function(cm) { cm.setSize(120); cm.setCursor(Pos(0, 5)); cm.execCommand("goLineDown"); eq(cm.getCursor().line, 0); is(cm.getCursor().ch > 5, "moved beyond wrap"); for (var i = 0; ; ++i) { is(i < 20, "no endless loop"); cm.execCommand("goLineDown"); var cur = cm.getCursor(); if (cur.line == 1) eq(cur.ch, 5); if (cur.line == 2) { eq(cur.ch, 1); break; } } }, {value: "a very long line that wraps around somehow so that we can test cursor movement\nshortone\nk", lineWrapping: true}); testCM("verticalMovementCommandsSingleLine", function(cm) { cm.display.wrapper.style.height = "auto"; cm.refresh(); cm.execCommand("goLineUp"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goLineDown"); eqCursorPos(cm.getCursor(), Pos(0, 11)); cm.setCursor(Pos(0, 5)); cm.execCommand("goLineDown"); eqCursorPos(cm.getCursor(), Pos(0, 11)); cm.execCommand("goLineDown"); eqCursorPos(cm.getCursor(), Pos(0, 11)); cm.execCommand("goLineUp"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goLineUp"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.execCommand("goPageDown"); eqCursorPos(cm.getCursor(), Pos(0, 11)); cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); eqCursorPos(cm.getCursor(), Pos(0, 11)); cm.execCommand("goPageUp"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.setCursor(Pos(0, 5)); cm.execCommand("goPageUp"); eqCursorPos(cm.getCursor(), Pos(0, 0)); cm.setCursor(Pos(0, 5)); cm.execCommand("goPageDown"); eqCursorPos(cm.getCursor(), Pos(0, 11)); }, {value: "single line"}); testCM("rtlMovement", function(cm) { if (cm.getOption("inputStyle") != "textarea") return; forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج", "خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر", "خ ة ق", "", "يتم السحب في 05 فبراير 2014"], function(line) { cm.setValue(line + "\n"); cm.execCommand("goLineStart"); var cursors = byClassName(cm.getWrapperElement(), "CodeMirror-cursors")[0]; var cursor = cursors.firstChild; var prevX = cursor.offsetLeft, prevY = cursor.offsetTop; for (var i = 0; i <= line.length; ++i) { cm.execCommand("goCharRight"); cursor = cursors.firstChild; if (i == line.length) is(cursor.offsetTop > prevY, "next line"); else is(cursor.offsetLeft > prevX, "moved right"); prevX = cursor.offsetLeft; prevY = cursor.offsetTop; } cm.setCursor(0, 0); cm.execCommand("goLineEnd"); prevX = cursors.firstChild.offsetLeft; for (var i = 0; i < line.length; ++i) { cm.execCommand("goCharLeft"); cursor = cursors.firstChild; is(cursor.offsetLeft < prevX, "moved left"); prevX = cursor.offsetLeft; } }); }, null, ie_lt9); // Verify that updating a line clears its bidi ordering testCM("bidiUpdate", function(cm) { cm.setCursor(Pos(0, 2, "before")); cm.replaceSelection("خحج", "start"); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); }, {value: "abcd\n"}); testCM("movebyTextUnit", function(cm) { cm.setValue("בְּרֵאשִ\nééé́\n"); cm.execCommand("goLineStart"); for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(0, 0, "after")); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(1, 0, "after")); cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(1, 4, "before")); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(1, 7, "before")); }); testCM("lineChangeEvents", function(cm) { addDoc(cm, 3, 5); var log = [], want = ["ch 0", "ch 1", "del 2", "ch 0", "ch 0", "del 1", "del 3", "del 4"]; for (var i = 0; i < 5; ++i) { CodeMirror.on(cm.getLineHandle(i), "delete", function(i) { return function() {log.push("del " + i);}; }(i)); CodeMirror.on(cm.getLineHandle(i), "change", function(i) { return function() {log.push("ch " + i);}; }(i)); } cm.replaceRange("x", Pos(0, 1)); cm.replaceRange("xy", Pos(1, 1), Pos(2)); cm.replaceRange("foo\nbar", Pos(0, 1)); cm.replaceRange("", Pos(0, 0), Pos(cm.lineCount())); eq(log.length, want.length, "same length"); for (var i = 0; i < log.length; ++i) eq(log[i], want[i]); }); testCM("scrollEntirelyToRight", function(cm) { if (phantom || cm.getOption("inputStyle") != "textarea") return; addDoc(cm, 500, 2); cm.setCursor(Pos(0, 500)); var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0]; is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left); }); testCM("lineWidgets", function(cm) { addDoc(cm, 500, 3); var last = cm.charCoords(Pos(2, 0)); var node = document.createElement("div"); node.innerHTML = "hi"; var widget = cm.addLineWidget(1, node); is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space"); cm.setCursor(Pos(1, 1)); cm.execCommand("goLineDown"); eqCharPos(cm.getCursor(), Pos(2, 1)); cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(1, 1)); }); testCM("lineWidgetFocus", function(cm) { var place = document.getElementById("testground"); place.className = "offscreen"; try { addDoc(cm, 500, 10); var node = document.createElement("input"); var widget = cm.addLineWidget(1, node); node.focus(); eq(document.activeElement, node); cm.replaceRange("new stuff", Pos(1, 0)); eq(document.activeElement, node); } finally { place.className = ""; } }); testCM("lineWidgetCautiousRedraw", function(cm) { var node = document.createElement("div"); node.innerHTML = "hahah"; var w = cm.addLineWidget(0, node); var redrawn = false; w.on("redraw", function() { redrawn = true; }); cm.replaceSelection("0"); is(!redrawn); }, {value: "123\n456"}); var knownScrollbarWidth; function scrollbarWidth(measure) { if (knownScrollbarWidth != null) return knownScrollbarWidth; var div = document.createElement('div'); div.style.cssText = "width: 50px; height: 50px; overflow-x: scroll"; document.body.appendChild(div); knownScrollbarWidth = div.offsetHeight - div.clientHeight; document.body.removeChild(div); return knownScrollbarWidth || 0; } testCM("lineWidgetChanged", function(cm) { addDoc(cm, 2, 300); var halfScrollbarWidth = scrollbarWidth(cm.display.measure)/2; cm.setOption('lineNumbers', true); cm.setSize(600, cm.defaultTextHeight() * 50); cm.scrollTo(null, cm.heightAtLine(125, "local")); var expectedWidgetHeight = 60; var expectedLinesInWidget = 3; function w() { var node = document.createElement("div"); // we use these children with just under half width of the line to check measurements are made with correct width // when placed in the measure div. // 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. // If the widget is measured at a width much wider than it is displayed at, the overHalf children will combine and break the test. // Note that this test only checks widgets where coverGutter is true, because these require extra styling to get the width right. // It may also be worthwhile to check this for non-coverGutter widgets. // Visually: // Good: // | ------------- display width ------------- | // | ------- widget-width when measured ------ | // | | -- under-half -- | | -- under-half -- | | // | | --- over-half --- | | // | | --- over-half --- | | // Height: measured as 3 lines, same as it will be when actually displayed // Bad (too narrow): // | ------------- display width ------------- | // | ------ widget-width when measured ----- | < -- uh oh // | | -- under-half -- | | // | | -- under-half -- | | < -- when measured, shoved to next line // | | --- over-half --- | | // | | --- over-half --- | | // Height: measured as 4 lines, more than expected . Will be displayed as 3 lines! // Bad (too wide): // | ------------- display width ------------- | // | -------- widget-width when measured ------- | < -- uh oh // | | -- under-half -- | | -- under-half -- | | // | | --- over-half --- | | --- over-half --- | | < -- when measured, combined on one line // Height: measured as 2 lines, less than expected. Will be displayed as 3 lines! var barelyUnderHalfWidthHtml = '
    '; var barelyOverHalfWidthHtml = '
    '; node.innerHTML = new Array(3).join(barelyUnderHalfWidthHtml) + new Array(3).join(barelyOverHalfWidthHtml); node.style.cssText = "background: yellow;font-size:0;line-height: " + (expectedWidgetHeight/expectedLinesInWidget) + "px;"; return node; } var info0 = cm.getScrollInfo(); var w0 = cm.addLineWidget(0, w(), { coverGutter: true }); var w150 = cm.addLineWidget(150, w(), { coverGutter: true }); var w300 = cm.addLineWidget(300, w(), { coverGutter: true }); var info1 = cm.getScrollInfo(); eq(info0.height + (3 * expectedWidgetHeight), info1.height); eq(info0.top + expectedWidgetHeight, info1.top); expectedWidgetHeight = 12; w0.node.style.lineHeight = w150.node.style.lineHeight = w300.node.style.lineHeight = (expectedWidgetHeight/expectedLinesInWidget) + "px"; w0.changed(); w150.changed(); w300.changed(); var info2 = cm.getScrollInfo(); eq(info0.height + (3 * expectedWidgetHeight), info2.height); eq(info0.top + expectedWidgetHeight, info2.top); }); testCM("lineWidgetIssue5486", function(cm) { // [prepare] // 2nd line is combined to 1st line due to markText // 2nd line has a lineWidget below cm.setValue("Lorem\nIpsue\nDollar") var el = document.createElement('div') el.style.height='50px' el.textContent = '[[LINE WIDGET]]' var lineWidget = cm.addLineWidget(1, el, { above: false, coverGutter: false, noHScroll: false, showIfHidden: false, }) var marker = document.createElement('span') marker.textContent = '[--]' cm.markText({line:0, ch: 1}, {line:1, ch: 4}, { replacedWith: marker }) // before resizing the lineWidget, measure 3rd line position var measure_1 = Math.round(cm.charCoords({line:2, ch:0}).top) // resize lineWidget, height + 50 px el.style.height='100px' el.textContent += "\nlineWidget size changed.\nTry moving cursor to line 3?" lineWidget.changed() // re-measure 3rd line position var measure_2 = Math.round(cm.charCoords({line:2, ch:0}).top) eq(measure_2, measure_1 + 50) // (extra test) // // add char to the right of the folded marker // and re-measure 3rd line position cm.replaceRange('-', {line:1, ch: 5}) var measure_3 = Math.round(cm.charCoords({line:2, ch:0}).top) eq(measure_3, measure_2) }); testCM("getLineNumber", function(cm) { addDoc(cm, 2, 20); var h1 = cm.getLineHandle(1); eq(cm.getLineNumber(h1), 1); cm.replaceRange("hi\nbye\n", Pos(0, 0)); eq(cm.getLineNumber(h1), 3); cm.setValue(""); eq(cm.getLineNumber(h1), null); }); testCM("jumpTheGap", function(cm) { if (phantom) return; var longLine = "abcdef ghiklmnop qrstuvw xyz "; longLine += longLine; longLine += longLine; longLine += longLine; cm.replaceRange(longLine, Pos(2, 0), Pos(2)); cm.setSize("200px", null); cm.getWrapperElement().style.lineHeight = 2; cm.refresh(); cm.setCursor(Pos(0, 1)); cm.execCommand("goLineDown"); eqCharPos(cm.getCursor(), Pos(1, 1)); cm.execCommand("goLineDown"); eqCharPos(cm.getCursor(), Pos(2, 1)); cm.execCommand("goLineDown"); eq(cm.getCursor().line, 2); is(cm.getCursor().ch > 1); cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(2, 1)); cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(1, 1)); var node = document.createElement("div"); node.innerHTML = "hi"; node.style.height = "30px"; cm.addLineWidget(0, node); cm.addLineWidget(1, node.cloneNode(true), {above: true}); cm.setCursor(Pos(0, 2)); cm.execCommand("goLineDown"); eqCharPos(cm.getCursor(), Pos(1, 2)); cm.execCommand("goLineUp"); eqCharPos(cm.getCursor(), Pos(0, 2)); }, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"}); testCM("addLineClass", function(cm) { function cls(line, text, bg, wrap, gutter) { var i = cm.lineInfo(line); eq(i.textClass, text); eq(i.bgClass, bg); eq(i.wrapClass, wrap); if (typeof i.handle.gutterClass !== 'undefined') { eq(i.handle.gutterClass, gutter); } } cm.addLineClass(0, "text", "foo"); cm.addLineClass(0, "text", "bar"); cm.addLineClass(1, "background", "baz"); cm.addLineClass(1, "wrap", "foo"); cm.addLineClass(1, "gutter", "gutter-class"); cls(0, "foo bar", null, null, null); cls(1, null, "baz", "foo", "gutter-class"); var lines = cm.display.lineDiv; eq(byClassName(lines, "foo").length, 2); eq(byClassName(lines, "bar").length, 1); eq(byClassName(lines, "baz").length, 1); eq(byClassName(lines, "gutter-class").length, 2); // Gutter classes are reflected in 2 nodes cm.removeLineClass(0, "text", "foo"); cls(0, "bar", null, null, null); cm.removeLineClass(0, "text", "foo"); cls(0, "bar", null, null, null); cm.removeLineClass(0, "text", "bar"); cls(0, null, null, null); cm.addLineClass(1, "wrap", "quux"); cls(1, null, "baz", "foo quux", "gutter-class"); cm.removeLineClass(1, "wrap"); cls(1, null, "baz", null, "gutter-class"); cm.removeLineClass(1, "gutter", "gutter-class"); eq(byClassName(lines, "gutter-class").length, 0); cls(1, null, "baz", null, null); cm.addLineClass(1, "gutter", "gutter-class"); cls(1, null, "baz", null, "gutter-class"); cm.removeLineClass(1, "gutter", "gutter-class"); cls(1, null, "baz", null, null); }, {value: "hohoho\n", lineNumbers: true}); testCM("atomicMarker", function(cm) { addDoc(cm, 10, 10); function atom(ll, cl, lr, cr, li, ri) { return cm.markText(Pos(ll, cl), Pos(lr, cr), {atomic: true, inclusiveLeft: li, inclusiveRight: ri}); } var m = atom(0, 1, 0, 5); cm.setCursor(Pos(0, 1)); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(0, 5)); cm.execCommand("goCharLeft"); eqCursorPos(cm.getCursor(), Pos(0, 1)); m.clear(); m = atom(0, 0, 0, 5, true); eqCursorPos(cm.getCursor(), Pos(0, 5), "pushed out"); cm.execCommand("goCharLeft"); eqCursorPos(cm.getCursor(), Pos(0, 5)); m.clear(); m = atom(8, 4, 9, 10, false, true); cm.setCursor(Pos(9, 8)); eqCursorPos(cm.getCursor(), Pos(8, 4), "set"); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(8, 4), "char right"); cm.execCommand("goLineDown"); eqCursorPos(cm.getCursor(), Pos(8, 4), "line down"); cm.execCommand("goCharLeft"); eqCursorPos(cm.getCursor(), Pos(8, 3, "after")); m.clear(); m = atom(1, 1, 3, 8); cm.setCursor(Pos(0, 0)); cm.setCursor(Pos(2, 0)); eqCursorPos(cm.getCursor(), Pos(3, 8)); cm.execCommand("goCharLeft"); eqCursorPos(cm.getCursor(), Pos(1, 1)); cm.execCommand("goCharRight"); eqCursorPos(cm.getCursor(), Pos(3, 8)); cm.execCommand("goLineUp"); eqCursorPos(cm.getCursor(), Pos(1, 1)); cm.execCommand("goLineDown"); eqCursorPos(cm.getCursor(), Pos(3, 8)); cm.execCommand("delCharBefore"); eq(cm.getValue().length, 80, "del chunk"); m = atom(3, 0, 5, 5); cm.setCursor(Pos(3, 0)); cm.execCommand("delWordAfter"); eq(cm.getValue().length, 53, "del chunk"); }); testCM("selectionBias", function(cm) { cm.markText(Pos(0, 1), Pos(0, 3), {atomic: true}); cm.setCursor(Pos(0, 2)); eqCursorPos(cm.getCursor(), Pos(0, 1)); cm.setCursor(Pos(0, 2)); eqCursorPos(cm.getCursor(), Pos(0, 3)); cm.setCursor(Pos(0, 2)); eqCursorPos(cm.getCursor(), Pos(0, 1)); cm.setCursor(Pos(0, 2), null, {bias: -1}); eqCursorPos(cm.getCursor(), Pos(0, 1)); cm.setCursor(Pos(0, 4)); cm.setCursor(Pos(0, 2), null, {bias: 1}); eqCursorPos(cm.getCursor(), Pos(0, 3)); }, {value: "12345"}); testCM("selectionHomeEnd", function(cm) { cm.markText(Pos(1, 0), Pos(1, 1), {atomic: true, inclusiveLeft: true}); cm.markText(Pos(1, 3), Pos(1, 4), {atomic: true, inclusiveRight: true}); cm.setCursor(Pos(1, 2)); cm.execCommand("goLineStart"); eqCursorPos(cm.getCursor(), Pos(1, 1)); cm.execCommand("goLineEnd"); eqCursorPos(cm.getCursor(), Pos(1, 3)); }, {value: "ab\ncdef\ngh"}); testCM("readOnlyMarker", function(cm) { function mark(ll, cl, lr, cr, at) { return cm.markText(Pos(ll, cl), Pos(lr, cr), {readOnly: true, atomic: at}); } var m = mark(0, 1, 0, 4); cm.setCursor(Pos(0, 2)); cm.replaceSelection("hi", "end"); eqCursorPos(cm.getCursor(), Pos(0, 2)); eq(cm.getLine(0), "abcde"); cm.execCommand("selectAll"); cm.replaceSelection("oops", "around"); eq(cm.getValue(), "oopsbcd"); cm.undo(); eqCursorPos(m.find().from, Pos(0, 1)); eqCursorPos(m.find().to, Pos(0, 4)); m.clear(); cm.setCursor(Pos(0, 2)); cm.replaceSelection("hi", "around"); eq(cm.getLine(0), "abhicde"); eqCursorPos(cm.getCursor(), Pos(0, 4)); m = mark(0, 2, 2, 2, true); cm.setSelection(Pos(1, 1), Pos(2, 4)); cm.replaceSelection("t", "end"); eqCursorPos(cm.getCursor(), Pos(2, 3)); eq(cm.getLine(2), "klto"); cm.execCommand("goCharLeft"); cm.execCommand("goCharLeft"); eqCursorPos(cm.getCursor(), Pos(0, 2)); cm.setSelection(Pos(0, 1), Pos(0, 3)); cm.replaceSelection("xx", "around"); eqCursorPos(cm.getCursor(), Pos(0, 3)); eq(cm.getLine(0), "axxhicde"); }, {value: "abcde\nfghij\nklmno\n"}); testCM("dirtyBit", function(cm) { eq(cm.isClean(), true); cm.replaceSelection("boo", null, "test"); eq(cm.isClean(), false); cm.undo(); eq(cm.isClean(), true); cm.replaceSelection("boo", null, "test"); cm.replaceSelection("baz", null, "test"); cm.undo(); eq(cm.isClean(), false); cm.markClean(); eq(cm.isClean(), true); cm.undo(); eq(cm.isClean(), false); cm.redo(); eq(cm.isClean(), true); }); testCM("changeGeneration", function(cm) { cm.replaceSelection("x"); var softGen = cm.changeGeneration(); cm.replaceSelection("x"); cm.undo(); eq(cm.getValue(), ""); is(!cm.isClean(softGen)); cm.replaceSelection("x"); var hardGen = cm.changeGeneration(true); cm.replaceSelection("x"); cm.undo(); eq(cm.getValue(), "x"); is(cm.isClean(hardGen)); }); testCM("addKeyMap", function(cm) { function sendKey(code) { cm.triggerOnKeyDown({type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}}); } sendKey(39); eqCursorPos(cm.getCursor(), Pos(0, 1, "before")); var test = 0; var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }} cm.addKeyMap(map1); sendKey(39); eqCursorPos(cm.getCursor(), Pos(0, 1, "before")); eq(test, 1); cm.addKeyMap(map2, true); sendKey(39); eq(test, 2); cm.removeKeyMap(map1); sendKey(39); eq(test, 12); cm.removeKeyMap(map2); sendKey(39); eq(test, 12); eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"}); sendKey(39); eq(test, 55); cm.removeKeyMap("mymap"); sendKey(39); eqCursorPos(cm.getCursor(), Pos(0, 3, "before")); }, {value: "abc"}); function mouseDown(cm, button, pos, mods) { var coords = cm.charCoords(pos, "window") var event = {type: "mousedown", preventDefault: Math.min, which: button, target: cm.display.lineDiv, clientX: coords.left, clientY: coords.top} if (mods) for (var prop in mods) event[prop] = mods[prop] cm.triggerOnMouseDown(event) } testCM("mouseBinding", function(cm) { var fired = [] cm.addKeyMap({ "Shift-LeftClick": function(_cm, pos) { eqCharPos(pos, Pos(1, 2)) fired.push("a") }, "Shift-LeftDoubleClick": function() { fired.push("b") }, "Shift-LeftTripleClick": function() { fired.push("c") } }) function send(button, mods) { mouseDown(cm, button, Pos(1, 2), mods) } send(1, {shiftKey: true}) send(1, {shiftKey: true}) send(1, {shiftKey: true}) send(1, {}) send(2, {ctrlKey: true}) send(2, {ctrlKey: true}) eq(fired.join(" "), "a b c") }, {value: "foo\nbar\nbaz"}) testCM("configureMouse", function(cm) { cm.setOption("configureMouse", function() { return {unit: "word"} }) mouseDown(cm, 1, Pos(0, 5)) eqCharPos(cm.getCursor("from"), Pos(0, 4)) eqCharPos(cm.getCursor("to"), Pos(0, 7)) cm.setOption("configureMouse", function() { return {extend: true} }) mouseDown(cm, 1, Pos(0, 0)) eqCharPos(cm.getCursor("from"), Pos(0, 0)) eqCharPos(cm.getCursor("to"), Pos(0, 4)) }, {value: "foo bar baz"}) testCM("findPosH", function(cm) { forEach([{from: Pos(0, 0), to: Pos(0, 1, "before"), by: 1}, {from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true}, {from: Pos(0, 0), to: Pos(0, 4, "before"), by: 1, unit: "word"}, {from: Pos(0, 0), to: Pos(0, 8, "before"), by: 2, unit: "word"}, {from: Pos(0, 0), to: Pos(2, 0, "after"), by: 20, unit: "word", hitSide: true}, {from: Pos(0, 7), to: Pos(0, 5, "after"), by: -1, unit: "word"}, {from: Pos(0, 4), to: Pos(0, 8, "before"), by: 1, unit: "word"}, {from: Pos(1, 0), to: Pos(1, 18, "before"), by: 3, unit: "word"}, {from: Pos(1, 22), to: Pos(1, 5, "after"), by: -3, unit: "word"}, {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5}, {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5, unit: "column"}, {from: Pos(1, 15), to: Pos(1, 0, "after"), by: -50, unit: "column", hitSide: true}, {from: Pos(1, 15), to: Pos(1, 24, "before"), by: 50, unit: "column", hitSide: true}, {from: Pos(1, 15), to: Pos(2, 0, "after"), by: 50, hitSide: true}], function(t) { var r = cm.findPosH(t.from, t.by, t.unit || "char"); eqCursorPos(r, t.to); eq(!!r.hitSide, !!t.hitSide); }); }, {value: "line one\nline two.something.other\n"}); testCM("beforeChange", function(cm) { cm.on("beforeChange", function(cm, change) { var text = []; for (var i = 0; i < change.text.length; ++i) text.push(change.text[i].replace(/\s/g, "_")); change.update(null, null, text); }); cm.setValue("hello, i am a\nnew document\n"); eq(cm.getValue(), "hello,_i_am_a\nnew_document\n"); CodeMirror.on(cm.getDoc(), "beforeChange", function(doc, change) { if (change.from.line == 0) change.cancel(); }); cm.setValue("oops"); // Canceled eq(cm.getValue(), "hello,_i_am_a\nnew_document\n"); cm.replaceRange("hey hey hey", Pos(1, 0), Pos(2, 0)); eq(cm.getValue(), "hello,_i_am_a\nhey_hey_hey"); }, {value: "abcdefghijk"}); testCM("beforeChangeUndo", function(cm) { cm.replaceRange("hi", Pos(0, 0), Pos(0)); cm.replaceRange("bye", Pos(0, 0), Pos(0)); eq(cm.historySize().undo, 2); cm.on("beforeChange", function(cm, change) { is(!change.update); change.cancel(); }); cm.undo(); eq(cm.historySize().undo, 0); eq(cm.getValue(), "bye\ntwo"); }, {value: "one\ntwo"}); testCM("beforeSelectionChange", function(cm) { function notAtEnd(cm, pos) { var len = cm.getLine(pos.line).length; if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1); return pos; } cm.on("beforeSelectionChange", function(cm, obj) { obj.update([{anchor: notAtEnd(cm, obj.ranges[0].anchor), head: notAtEnd(cm, obj.ranges[0].head)}]); }); addDoc(cm, 10, 10); cm.execCommand("goLineEnd"); eqCursorPos(cm.getCursor(), Pos(0, 9)); cm.execCommand("selectAll"); eqCursorPos(cm.getCursor("start"), Pos(0, 0)); eqCursorPos(cm.getCursor("end"), Pos(9, 9)); }); testCM("change_removedText", function(cm) { cm.setValue("abc\ndef"); var removedText = []; cm.on("change", function(cm, change) { removedText.push(change.removed); }); cm.operation(function() { cm.replaceRange("xyz", Pos(0, 0), Pos(1,1)); cm.replaceRange("123", Pos(0,0)); }); eq(removedText.length, 2); eq(removedText[0].join("\n"), "abc\nd"); eq(removedText[1].join("\n"), ""); var removedText = []; cm.undo(); eq(removedText.length, 2); eq(removedText[0].join("\n"), "123"); eq(removedText[1].join("\n"), "xyz"); var removedText = []; cm.redo(); eq(removedText.length, 2); eq(removedText[0].join("\n"), "abc\nd"); eq(removedText[1].join("\n"), ""); }); testCM("lineStyleFromMode", function(cm) { CodeMirror.defineMode("test_mode", function() { return {token: function(stream) { if (stream.match(/^\[[^\]]*\]/)) return " line-brackets "; if (stream.match(/^\([^\)]*\)/)) return " line-background-parens "; if (stream.match(/^<[^>]*>/)) return " span line-line line-background-bg "; stream.match(/^\s+|^\S+/); }}; }); cm.setOption("mode", "test_mode"); var bracketElts = byClassName(cm.getWrapperElement(), "brackets"); eq(bracketElts.length, 1, "brackets count"); eq(bracketElts[0].nodeName, "PRE"); is(!/brackets.*brackets/.test(bracketElts[0].className)); var parenElts = byClassName(cm.getWrapperElement(), "parens"); eq(parenElts.length, 1, "parens count"); eq(parenElts[0].nodeName, "DIV"); is(!/parens.*parens/.test(parenElts[0].className)); eq(parenElts[0].parentElement.nodeName, "DIV"); is(byClassName(cm.getWrapperElement(), "bg").length > 0); is(byClassName(cm.getWrapperElement(), "line").length > 0); var spanElts = byClassName(cm.getWrapperElement(), "cm-span"); eq(spanElts.length, 2); is(/^\s*cm-span\s*$/.test(spanElts[0].className)); }, {value: "line1: [br] [br]\nline2: (par) (par)\nline3: "}); testCM("lineStyleFromBlankLine", function(cm) { CodeMirror.defineMode("lineStyleFromBlankLine_mode", function() { return {token: function(stream) { stream.skipToEnd(); return "comment"; }, blankLine: function() { return "line-blank"; }}; }); cm.setOption("mode", "lineStyleFromBlankLine_mode"); var blankElts = byClassName(cm.getWrapperElement(), "blank"); eq(blankElts.length, 1); eq(blankElts[0].nodeName, "PRE"); cm.replaceRange("x", Pos(1, 0)); blankElts = byClassName(cm.getWrapperElement(), "blank"); eq(blankElts.length, 0); }, {value: "foo\n\nbar"}); CodeMirror.registerHelper("xxx", "a", "A"); CodeMirror.registerHelper("xxx", "b", "B"); CodeMirror.defineMode("yyy", function() { return { token: function(stream) { stream.skipToEnd(); }, xxx: ["a", "b", "q"] }; }); CodeMirror.registerGlobalHelper("xxx", "c", function(m) { return m.enableC; }, "C"); testCM("helpers", function(cm) { cm.setOption("mode", "yyy"); eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "A/B"); cm.setOption("mode", {name: "yyy", modeProps: {xxx: "b", enableC: true}}); eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "B/C"); cm.setOption("mode", "javascript"); eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), ""); }); testCM("selectionHistory", function(cm) { for (var i = 0; i < 3; i++) { cm.setExtending(true); cm.execCommand("goCharRight"); cm.setExtending(false); cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); } cm.execCommand("undoSelection"); eq(cm.getSelection(), "c"); cm.execCommand("undoSelection"); eq(cm.getSelection(), ""); eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); cm.execCommand("undoSelection"); eq(cm.getSelection(), "b"); cm.execCommand("redoSelection"); eq(cm.getSelection(), ""); eqCursorPos(cm.getCursor(), Pos(0, 4, "before")); cm.execCommand("redoSelection"); eq(cm.getSelection(), "c"); cm.execCommand("redoSelection"); eq(cm.getSelection(), ""); eqCursorPos(cm.getCursor(), Pos(0, 6, "before")); }, {value: "a b c d"}); testCM("selectionChangeReducesRedo", function(cm) { cm.replaceSelection("X"); cm.execCommand("goCharRight"); cm.undoSelection(); cm.execCommand("selectAll"); cm.undoSelection(); eq(cm.getValue(), "Xabc"); eqCursorPos(cm.getCursor(), Pos(0, 1)); cm.undoSelection(); eq(cm.getValue(), "abc"); }, {value: "abc"}); testCM("selectionHistoryNonOverlapping", function(cm) { cm.setSelection(Pos(0, 0), Pos(0, 1)); cm.setSelection(Pos(0, 2), Pos(0, 3)); cm.execCommand("undoSelection"); eqCursorPos(cm.getCursor("anchor"), Pos(0, 0)); eqCursorPos(cm.getCursor("head"), Pos(0, 1)); }, {value: "1234"}); testCM("cursorMotionSplitsHistory", function(cm) { cm.replaceSelection("a"); cm.execCommand("goCharRight"); cm.replaceSelection("b"); cm.replaceSelection("c"); cm.undo(); eq(cm.getValue(), "a1234"); eqCursorPos(cm.getCursor(), Pos(0, 2, "before")); cm.undo(); eq(cm.getValue(), "1234"); eqCursorPos(cm.getCursor(), Pos(0, 0)); }, {value: "1234"}); testCM("selChangeInOperationDoesNotSplit", function(cm) { for (var i = 0; i < 4; i++) { cm.operation(function() { cm.replaceSelection("x"); cm.setCursor(Pos(0, cm.getCursor().ch - 1)); }); } eqCursorPos(cm.getCursor(), Pos(0, 0)); eq(cm.getValue(), "xxxxa"); cm.undo(); eq(cm.getValue(), "a"); }, {value: "a"}); testCM("alwaysMergeSelEventWithChangeOrigin", function(cm) { cm.replaceSelection("U", null, "foo"); cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "foo"}); cm.undoSelection(); eq(cm.getValue(), "a"); cm.replaceSelection("V", null, "foo"); cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "bar"}); cm.undoSelection(); eq(cm.getValue(), "Va"); }, {value: "a"}); testCM("getTokenAt", function(cm) { var tokPlus = cm.getTokenAt(Pos(0, 2)); eq(tokPlus.type, "operator"); eq(tokPlus.string, "+"); var toks = cm.getLineTokens(0); eq(toks.length, 3); forEach([["number", "1"], ["operator", "+"], ["number", "2"]], function(expect, i) { eq(toks[i].type, expect[0]); eq(toks[i].string, expect[1]); }); }, {value: "1+2", mode: "javascript"}); testCM("getTokenTypeAt", function(cm) { eq(cm.getTokenTypeAt(Pos(0, 0)), "number"); eq(cm.getTokenTypeAt(Pos(0, 6)), "string"); cm.addOverlay({ token: function(stream) { if (stream.match("foo")) return "foo"; else stream.next(); } }); eq(byClassName(cm.getWrapperElement(), "cm-foo").length, 1); eq(cm.getTokenTypeAt(Pos(0, 6)), "string"); }, {value: "1 + 'foo'", mode: "javascript"}); testCM("addOverlay", function(cm) { cm.addOverlay({ token: function(stream) { var base = stream.baseToken() if (!/comment/.test(base.type) && stream.match(/\d+/)) return "x" stream.next() } }) var x = byClassName(cm.getWrapperElement(), "cm-x") is(x.length, 1) is(x[0].textContent, "233") cm.replaceRange("", Pos(0, 4), Pos(0, 6)) is(byClassName(cm.getWrapperElement(), "cm-x").length, 2) }, {value: "foo /* 100 */\nbar + 233;\nbaz", mode: "javascript"}) testCM("resizeLineWidget", function(cm) { addDoc(cm, 200, 3); var widget = document.createElement("pre"); widget.innerHTML = "imwidget"; widget.style.background = "yellow"; cm.addLineWidget(1, widget, {noHScroll: true}); cm.setSize(40); is(widget.parentNode.offsetWidth < 42); }); testCM("combinedOperations", function(cm) { var place = document.getElementById("testground"); var other = CodeMirror(place, {value: "123"}); try { cm.operation(function() { cm.addLineClass(0, "wrap", "foo"); other.addLineClass(0, "wrap", "foo"); }); eq(byClassName(cm.getWrapperElement(), "foo").length, 1); eq(byClassName(other.getWrapperElement(), "foo").length, 1); cm.operation(function() { cm.removeLineClass(0, "wrap", "foo"); other.removeLineClass(0, "wrap", "foo"); }); eq(byClassName(cm.getWrapperElement(), "foo").length, 0); eq(byClassName(other.getWrapperElement(), "foo").length, 0); } finally { place.removeChild(other.getWrapperElement()); } }, {value: "abc"}); testCM("eventOrder", function(cm) { var seen = []; cm.on("change", function() { if (!seen.length) cm.replaceSelection("."); seen.push("change"); }); cm.on("cursorActivity", function() { cm.replaceSelection("!"); seen.push("activity"); }); cm.replaceSelection("/"); eq(seen.join(","), "change,change,activity,change"); }); testCM("splitSpaces_nonspecial", function(cm) { eq(byClassName(cm.getWrapperElement(), "cm-invalidchar").length, 0); }, { specialChars: /[\u00a0]/, value: "spaces -> <- between" }); test("core_rmClass", function() { var node = document.createElement("div"); node.className = "foo-bar baz-quux yadda"; CodeMirror.rmClass(node, "quux"); eq(node.className, "foo-bar baz-quux yadda"); CodeMirror.rmClass(node, "baz-quux"); eq(node.className, "foo-bar yadda"); CodeMirror.rmClass(node, "yadda"); eq(node.className, "foo-bar"); CodeMirror.rmClass(node, "foo-bar"); eq(node.className, ""); node.className = " foo "; CodeMirror.rmClass(node, "foo"); eq(node.className, ""); }); test("core_addClass", function() { var node = document.createElement("div"); CodeMirror.addClass(node, "a"); eq(node.className, "a"); CodeMirror.addClass(node, "a"); eq(node.className, "a"); CodeMirror.addClass(node, "b"); eq(node.className, "a b"); CodeMirror.addClass(node, "a"); CodeMirror.addClass(node, "b"); eq(node.className, "a b"); }); testCM("lineSeparator", function(cm) { eq(cm.lineCount(), 3); eq(cm.getLine(1), "bar\r"); eq(cm.getLine(2), "baz\rquux"); cm.setOption("lineSeparator", "\r"); eq(cm.lineCount(), 5); eq(cm.getLine(4), "quux"); eq(cm.getValue(), "foo\rbar\r\rbaz\rquux"); eq(cm.getValue("\n"), "foo\nbar\n\nbaz\nquux"); cm.setOption("lineSeparator", null); cm.setValue("foo\nbar\r\nbaz\rquux"); eq(cm.lineCount(), 4); }, {value: "foo\nbar\r\nbaz\rquux", lineSeparator: "\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]/ var 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 } var getString = function (n) { var res = getChar(true); while (--n > 0) res += getChar(); return res } function makeItWrapAfter(cm, pos) { var firstLineTop = cm.cursorCoords(Pos(0, 0)).top; for(var w = 0, posTop; posTop != firstLineTop; ++w) { cm.setSize(w); posTop = cm.charCoords(pos).top; } } function countIf(arr, f) { var result = 0 for (var i = 0; i < arr.length; i++) if (f[arr[i]]) result++ return result } function testMoveBidi(str) { testCM("move_bidi_" + str, function(cm) { if (cm.getOption("inputStyle") != "textarea" || !cm.getOption("rtlMoveVisually")) return; cm.getScrollerElement().style.fontFamily = "monospace"; makeItWrapAfter(cm, Pos(0, 5)); var steps = str.length - countIf(str.split(""), function(ch) { return extendingChars.test(ch) }); var lineBreaks = {} lineBreaks[6 - countIf(str.substr(0, 5).split(""), function(ch) { return extendingChars.test(ch) })] = 'w'; if (str.indexOf("\n") != -1) { lineBreaks[steps - 2] = 'n'; } // Make sure we are at the visual beginning of the first line cm.execCommand("goLineStart"); var prevCoords = cm.cursorCoords(), coords; for(var i = 0; i < steps; ++i) { cm.execCommand("goCharRight"); coords = cm.cursorCoords(); if ((i >= 10 && i <= 12) && !lineBreaks[i] && coords.left < prevCoords.left && coords.top > prevCoords.top) { // The first line wraps twice lineBreaks[i] = 'w'; } if (!lineBreaks[i]) { is(coords.left > prevCoords.left, "In step " + i + ", cursor didn't move right"); eq(coords.top, prevCoords.top, "In step " + i + ", cursor moved out of line"); } else { is(coords.left < prevCoords.left, i); is(coords.top > prevCoords.top, i); } prevCoords = coords; } cm.execCommand("goCharRight"); coords = cm.cursorCoords(); eq(coords.left, prevCoords.left, "Moving " + steps + " steps right didn't reach the end"); eq(coords.top, prevCoords.top, "Moving " + steps + " steps right didn't reach the end"); for(i = steps - 1; i >= 0; --i) { cm.execCommand("goCharLeft"); coords = cm.cursorCoords(); if (!(lineBreaks[i] == 'n' || lineBreaks[i + 1] == 'w')) { is(coords.left < prevCoords.left, "In step " + i + ", cursor didn't move left"); eq(coords.top, prevCoords.top, "In step " + i + ", cursor is not at the same line anymore"); } else { is(coords.left > prevCoords.left, i); is(coords.top < prevCoords.top, i); } prevCoords = coords; } cm.execCommand("goCharLeft"); coords = cm.cursorCoords(); eq(coords.left, prevCoords.left, "Moving " + steps + " steps left didn't reach the beginning"); eq(coords.top, prevCoords.top, "Moving " + steps + " steps left didn't reach the beginning"); }, {value: str, lineWrapping: true}) }; function testMoveEndBidi(str) { testCM("move_end_bidi_" + str, function(cm) { cm.getScrollerElement().style.fontFamily = "monospace"; makeItWrapAfter(cm, Pos(0, 5)); cm.execCommand("goLineStart"); var pos = cm.doc.getCursor(); cm.execCommand("goCharLeft"); eqCursorPos(pos, cm.doc.getCursor()); cm.execCommand("goLineEnd"); pos = cm.doc.getCursor(); cm.execCommand("goColumnRight"); eqCursorPos(pos, cm.doc.getCursor()); }, {value: str, lineWrapping: true}) }; var bidiTests = []; // We don't correctly implement L1 UBA // See https://bugzilla.mozilla.org/show_bug.cgi?id=1331501 // and https://bugs.chromium.org/p/chromium/issues/detail?id=673405 /* bidiTests.push("Say ا ب جabj\nS"); bidiTests.push("Sayyy ا ا ب ج"); */ if (!phantom) { bidiTests.push("Όȝǝڪȉۥ״ۺ׆ɀҩۏ\nҳ"); bidiTests.push("ŌӰтقȤ؁ƥ؅٣ĎȺ١\nϚ"); bidiTests.push("ٻоҤѕѽΩ־؉ïίքdz\nٵ"); bidiTests.push("؅؁ĆՕƿɁǞϮؠȩóć\nď"); bidiTests.push("RŨďңŪzϢŎƏԖڇڦ\nӈ"); bidiTests.push("ό׊۷٢ԜһОצЉيčǟ\nѩ"); bidiTests.push("ۑÚҳҕڬġڹհяųKV\nr"); bidiTests.push("źڻғúہ4ם1Ƞc1a\nԁ"); bidiTests.push("ҒȨҟփƞ٦ԓȦڰғâƥ\nڤ"); bidiTests.push("ϖسՉȏŧΔԛdžĎӟیڡ\nέ"); bidiTests.push("۹ؼL۵ĺȧКԙػא7״\nم"); bidiTests.push("ن (ي)\u2009أقواس"); // thin space to throw off Firefox 51's broken white-space compressing behavior } bidiTests.push("քմѧǮßپüŢҍҞўڳ\nӧ"); //bidiTests.push("Count ١ ٢ ٣ ٤"); //bidiTests.push("ӣאƦϰ؊ȓېÛوը٬ز\nϪ"); //bidiTests.push("ҾճٳџIՖӻ٥׭֐؜ڏ\nێ"); //bidiTests.push("ҬÓФ؜ڂį٦Ͽɓڐͳٵ\nՈ"); //bidiTests.push("aѴNijȻهˇ҃ڱӧǻֵ\na"); //bidiTests.push(" a٧ا٢ ب جa\nS"); for (var i = 0; i < bidiTests.length; ++i) { testMoveBidi(bidiTests[i]); testMoveEndBidi(bidiTests[i]); } /* for (var i = 0; i < 5; ++i) { testMoveBidi(getString(12) + "\n" + getString(1)); } */ function testCoordsWrappedBidi(str) { testCM("coords_wrapped_bidi_" + str, function(cm) { cm.getScrollerElement().style.fontFamily = "monospace"; makeItWrapAfter(cm, Pos(0, 5)); // Make sure we are at the visual beginning of the first line var pos = Pos(0, 0), lastPos; cm.doc.setCursor(pos); do { lastPos = pos; cm.execCommand("goCharLeft"); pos = cm.doc.getCursor(); } while (pos != lastPos) var top = cm.charCoords(Pos(0, 0)).top, lastTop; for (var i = 1; i < str.length; ++i) { lastTop = top; top = cm.charCoords(Pos(0, i)).top; is(top >= lastTop); } }, {value: str, lineWrapping: true}) }; testCoordsWrappedBidi("Count ١ ٢ ٣ ٤"); /* for (var i = 0; i < 5; ++i) { testCoordsWrappedBidi(getString(50)); } */ testCM("rtl_wrapped_selection", function(cm) { cm.setSelection(Pos(0, 10), Pos(0, 190)) is(byClassName(cm.getWrapperElement(), "CodeMirror-selected").length >= 3) }, {value: new Array(10).join(" فتي تم تضمينها فتي تم"), lineWrapping: true}) testCM("bidi_wrapped_selection", function(cm) { if (phantom) return cm.setSize(cm.charCoords(Pos(0, 10), "editor").left) cm.setSelection(Pos(0, 37), Pos(0, 80)) var blocks = byClassName(cm.getWrapperElement(), "CodeMirror-selected") is(blocks.length >= 2) is(blocks.length <= 3) var boxTop = blocks[0].getBoundingClientRect(), boxBot = blocks[blocks.length - 1].getBoundingClientRect() is(boxTop.left > cm.charCoords(Pos(0, 1)).right) is(boxBot.right < cm.charCoords(Pos(0, cm.getLine(0).length - 2)).left) }, {value: "

    مفتي11 تم تضمينهفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تا فت10ي ت

    ", lineWrapping: true}) testCM("delete_wrapped", function(cm) { makeItWrapAfter(cm, Pos(0, 2)); cm.doc.setCursor(Pos(0, 3, "after")); cm.deleteH(-1, "char"); eq(cm.getLine(0), "1245"); }, {value: "12345", lineWrapping: true}) testCM("issue_4878", function(cm) { if (phantom) return cm.setCursor(Pos(1, 12, "after")); cm.moveH(-1, "char"); eqCursorPos(cm.getCursor(), Pos(0, 113, "before")); }, {value: " في تطبيق السمات مرة واحدة https://github.com/codemirror/CodeMirror/issues/4878#issuecomment-330550964على سبيل المثال \"foo bar\"\n" + " سيتم تعيين", direction: "rtl", lineWrapping: true}); CodeMirror.defineMode("lookahead_mode", function() { // Colors text as atom if the line two lines down has an x in it return { token: function(stream) { stream.skipToEnd() return /x/.test(stream.lookAhead(2)) ? "atom" : null } } }) testCM("mode_lookahead", function(cm) { eq(cm.getTokenAt(Pos(0, 1)).type, "atom") eq(cm.getTokenAt(Pos(1, 1)).type, "atom") eq(cm.getTokenAt(Pos(2, 1)).type, null) cm.replaceRange("\n", Pos(2, 0)) eq(cm.getTokenAt(Pos(0, 1)).type, null) eq(cm.getTokenAt(Pos(1, 1)).type, "atom") }, {value: "foo\na\nx\nx\n", mode: "lookahead_mode"}) ================================================ FILE: third_party/CodeMirror/test/vim_test.js ================================================ var Pos = CodeMirror.Pos; CodeMirror.Vim.suppressErrorLogging = true; var code = '' + ' wOrd1 (#%\n' + ' word3] \n' + 'aopop pop 0 1 2 3 4\n' + ' (a) [b] {c} \n' + 'int getchar(void) {\n' + ' static char buf[BUFSIZ];\n' + ' static char *bufp = buf;\n' + ' if (n == 0) { /* buffer is empty */\n' + ' n = read(0, buf, sizeof buf);\n' + ' bufp = buf;\n' + ' }\n' + '\n' + ' return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n' + ' \n' + '}\n'; var lines = (function() { lineText = code.split('\n'); var ret = []; for (var i = 0; i < lineText.length; i++) { ret[i] = { line: i, length: lineText[i].length, lineText: lineText[i], textStart: /^\s*/.exec(lineText[i])[0].length }; } return ret; })(); var endOfDocument = makeCursor(lines.length - 1, lines[lines.length - 1].length); var wordLine = lines[0]; var bigWordLine = lines[1]; var charLine = lines[2]; var bracesLine = lines[3]; var seekBraceLine = lines[4]; var word1 = { start: new Pos(wordLine.line, 1), end: new Pos(wordLine.line, 5) }; var word2 = { start: new Pos(wordLine.line, word1.end.ch + 2), end: new Pos(wordLine.line, word1.end.ch + 4) }; var word3 = { start: new Pos(bigWordLine.line, 1), end: new Pos(bigWordLine.line, 5) }; var bigWord1 = word1; var bigWord2 = word2; var bigWord3 = { start: new Pos(bigWordLine.line, 1), end: new Pos(bigWordLine.line, 7) }; var bigWord4 = { start: new Pos(bigWordLine.line, bigWord1.end.ch + 3), end: new Pos(bigWordLine.line, bigWord1.end.ch + 7) }; var oChars = [ new Pos(charLine.line, 1), new Pos(charLine.line, 3), new Pos(charLine.line, 7) ]; var pChars = [ new Pos(charLine.line, 2), new Pos(charLine.line, 4), new Pos(charLine.line, 6), new Pos(charLine.line, 8) ]; var numChars = [ new Pos(charLine.line, 10), new Pos(charLine.line, 12), new Pos(charLine.line, 14), new Pos(charLine.line, 16), new Pos(charLine.line, 18)]; var parens1 = { start: new Pos(bracesLine.line, 1), end: new Pos(bracesLine.line, 3) }; var squares1 = { start: new Pos(bracesLine.line, 5), end: new Pos(bracesLine.line, 7) }; var curlys1 = { start: new Pos(bracesLine.line, 9), end: new Pos(bracesLine.line, 11) }; var seekOutside = { start: new Pos(seekBraceLine.line, 1), end: new Pos(seekBraceLine.line, 16) }; var seekInside = { start: new Pos(seekBraceLine.line, 14), end: new Pos(seekBraceLine.line, 11) }; function copyCursor(cur) { return new Pos(cur.line, cur.ch); } function forEach(arr, func) { for (var i = 0; i < arr.length; i++) { func(arr[i], i, arr); } } function testVim(name, run, opts, expectedFail) { var vimOpts = { lineNumbers: true, vimMode: true, showCursorWhenSelecting: true, value: code }; for (var prop in opts) { if (opts.hasOwnProperty(prop)) { vimOpts[prop] = opts[prop]; } } return test('vim_' + name, function() { var place = document.getElementById("testground"); var cm = CodeMirror(place, vimOpts); var vim = CodeMirror.Vim.maybeInitVimState_(cm); function doKeysFn(cm) { return function(args) { if (args instanceof Array) { arguments = args; } for (var i = 0; i < arguments.length; i++) { var result = CodeMirror.Vim.handleKey(cm, arguments[i]); if (!result && cm.state.vim.insertMode) { cm.replaceSelections(fillArray(arguments[i], cm.listSelections().length)); } } } } function doInsertModeKeysFn(cm) { return function(args) { if (args instanceof Array) { arguments = args; } function executeHandler(handler) { if (typeof handler == 'string') { CodeMirror.commands[handler](cm); } else { handler(cm); } return true; } for (var i = 0; i < arguments.length; i++) { var key = arguments[i]; // Find key in keymap and handle. var handled = CodeMirror.lookupKey(key, cm.getOption('keyMap'), executeHandler, cm); // Record for insert mode. if (handled == "handled" && cm.state.vim.insertMode && arguments[i] != 'Esc') { var lastChange = CodeMirror.Vim.getVimGlobalState_().macroModeState.lastInsertModeChanges; if (lastChange && (key.indexOf('Delete') != -1 || key.indexOf('Backspace') != -1)) { lastChange.changes.push(new CodeMirror.Vim.InsertModeKey(key)); } } } } } function doExFn(cm) { return function(command) { cm.openDialog = helpers.fakeOpenDialog(command); helpers.doKeys(':'); } } function assertCursorAtFn(cm) { return function(line, ch) { var pos; if (ch == null && typeof line.line == 'number') { pos = line; } else { pos = makeCursor(line, ch); } eqCursorPos(cm.getCursor(), pos); } } function fakeOpenDialog(result) { return function(text, callback) { return callback(result); } } function fakeOpenNotification(matcher) { return function(text) { matcher(text); } } var helpers = { doKeys: doKeysFn(cm), // Warning: Only emulates keymap events, not character insertions. Use // replaceRange to simulate character insertions. // Keys are in CodeMirror format, NOT vim format. doInsertModeKeys: doInsertModeKeysFn(cm), doEx: doExFn(cm), assertCursorAt: assertCursorAtFn(cm), fakeOpenDialog: fakeOpenDialog, fakeOpenNotification: fakeOpenNotification, getRegisterController: function() { return CodeMirror.Vim.getRegisterController(); } } CodeMirror.Vim.resetVimGlobalState_(); var successful = false; var savedOpenNotification = cm.openNotification; var savedOpenDialog = cm.openDialog; try { run(cm, vim, helpers); successful = true; } finally { cm.openNotification = savedOpenNotification; cm.openDialog = savedOpenDialog; if (!successful || verbose) { place.style.visibility = "visible"; } else { place.removeChild(cm.getWrapperElement()); } } }, expectedFail); }; testVim('qq@q', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'q', 'l', 'l', 'q'); helpers.assertCursorAt(0,2); helpers.doKeys('@', 'q'); helpers.assertCursorAt(0,4); }, { value: ' '}); testVim('@@', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'q', 'l', 'l', 'q'); helpers.assertCursorAt(0,2); helpers.doKeys('@', 'q'); helpers.assertCursorAt(0,4); helpers.doKeys('@', '@'); helpers.assertCursorAt(0,6); }, { value: ' '}); var jumplistScene = ''+ 'word\n'+ '(word)\n'+ '{word\n'+ 'word.\n'+ '\n'+ 'word search\n'+ '}word\n'+ 'word\n'+ 'word\n'; function testJumplist(name, keys, endPos, startPos, dialog) { endPos = makeCursor(endPos[0], endPos[1]); startPos = makeCursor(startPos[0], startPos[1]); testVim(name, function(cm, vim, helpers) { CodeMirror.Vim.resetVimGlobalState_(); if(dialog)cm.openDialog = helpers.fakeOpenDialog('word'); cm.setCursor(startPos); helpers.doKeys.apply(null, keys); helpers.assertCursorAt(endPos); }, {value: jumplistScene}); } testJumplist('jumplist_H', ['H', ''], [5,2], [5,2]); testJumplist('jumplist_M', ['M', ''], [2,2], [2,2]); testJumplist('jumplist_L', ['L', ''], [2,2], [2,2]); testJumplist('jumplist_[[', ['[', '[', ''], [5,2], [5,2]); testJumplist('jumplist_]]', [']', ']', ''], [2,2], [2,2]); testJumplist('jumplist_G', ['G', ''], [5,2], [5,2]); testJumplist('jumplist_gg', ['g', 'g', ''], [5,2], [5,2]); testJumplist('jumplist_%', ['%', ''], [1,5], [1,5]); testJumplist('jumplist_{', ['{', ''], [1,5], [1,5]); testJumplist('jumplist_}', ['}', ''], [1,5], [1,5]); testJumplist('jumplist_\'', ['m', 'a', 'h', '\'', 'a', 'h', ''], [1,0], [1,5]); testJumplist('jumplist_`', ['m', 'a', 'h', '`', 'a', 'h', ''], [1,5], [1,5]); testJumplist('jumplist_*_cachedCursor', ['*', ''], [1,3], [1,3]); testJumplist('jumplist_#_cachedCursor', ['#', ''], [1,3], [1,3]); testJumplist('jumplist_n', ['#', 'n', ''], [1,1], [2,3]); testJumplist('jumplist_N', ['#', 'N', ''], [1,1], [2,3]); testJumplist('jumplist_repeat_', ['*', '*', '*', '3', ''], [2,3], [2,3]); testJumplist('jumplist_repeat_', ['*', '*', '*', '3', '', '2', ''], [5,0], [2,3]); testJumplist('jumplist_repeated_motion', ['3', '*', ''], [2,3], [2,3]); testJumplist('jumplist_/', ['/', ''], [2,3], [2,3], 'dialog'); testJumplist('jumplist_?', ['?', ''], [2,3], [2,3], 'dialog'); testJumplist('jumplist_skip_deleted_mark', ['*', 'n', 'n', 'k', 'd', 'k', '', '', ''], [0,2], [0,2]); testJumplist('jumplist_skip_deleted_mark', ['*', 'n', 'n', 'k', 'd', 'k', '', '', ''], [1,0], [0,2]); /** * @param name Name of the test * @param keys An array of keys or a string with a single key to simulate. * @param endPos The expected end position of the cursor. * @param startPos The position the cursor should start at, defaults to 0, 0. */ function testMotion(name, keys, endPos, startPos) { testVim(name, function(cm, vim, helpers) { if (!startPos) { startPos = new Pos(0, 0); } cm.setCursor(startPos); helpers.doKeys(keys); helpers.assertCursorAt(endPos); }); } function makeCursor(line, ch) { return new Pos(line, ch); } function offsetCursor(cur, offsetLine, offsetCh) { return new Pos(cur.line + offsetLine, cur.ch + offsetCh); } // Motion tests testMotion('|', '|', makeCursor(0, 0), makeCursor(0,4)); testMotion('|_repeat', ['3', '|'], makeCursor(0, 2), makeCursor(0,4)); testMotion('h', 'h', makeCursor(0, 0), word1.start); testMotion('h_repeat', ['3', 'h'], offsetCursor(word1.end, 0, -3), word1.end); testMotion('l', 'l', makeCursor(0, 1)); testMotion('l_repeat', ['2', 'l'], makeCursor(0, 2)); testMotion('j', 'j', offsetCursor(word1.end, 1, 0), word1.end); testMotion('j_repeat', ['2', 'j'], offsetCursor(word1.end, 2, 0), word1.end); testMotion('j_repeat_clip', ['1000', 'j'], endOfDocument); testMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end); testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4)); testMotion('k_repeat_clip', ['1000', 'k'], makeCursor(0, 4), makeCursor(2, 4)); testMotion('w', 'w', word1.start); testMotion('w_multiple_newlines_no_space', 'w', makeCursor(12, 2), makeCursor(11, 2)); testMotion('w_multiple_newlines_with_space', 'w', makeCursor(14, 0), makeCursor(12, 51)); testMotion('w_repeat', ['2', 'w'], word2.start); testMotion('w_wrap', ['w'], word3.start, word2.start); testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument); testMotion('w_start_to_end', ['1000', 'w'], endOfDocument, makeCursor(0, 0)); testMotion('W', 'W', bigWord1.start); testMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start); testMotion('e', 'e', word1.end); testMotion('e_repeat', ['2', 'e'], word2.end); testMotion('e_wrap', 'e', word3.end, word2.end); testMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument); testMotion('e_start_to_end', ['1000', 'e'], endOfDocument, makeCursor(0, 0)); testMotion('b', 'b', word3.start, word3.end); testMotion('b_repeat', ['2', 'b'], word2.start, word3.end); testMotion('b_wrap', 'b', word2.start, word3.start); testMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0)); testMotion('b_end_to_start', ['1000', 'b'], makeCursor(0, 0), endOfDocument); testMotion('ge', ['g', 'e'], word2.end, word3.end); testMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start); testMotion('ge_wrap', ['g', 'e'], word2.end, word3.start); testMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0), makeCursor(0, 0)); testMotion('ge_end_to_start', ['1000', 'g', 'e'], makeCursor(0, 0), endOfDocument); testMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart), makeCursor(3, 1)); testMotion('gg_repeat', ['3', 'g', 'g'], makeCursor(lines[2].line, lines[2].textStart)); testMotion('G', 'G', makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart), makeCursor(3, 1)); testMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line, lines[2].textStart)); // TODO: Make the test code long enough to test Ctrl-F and Ctrl-B. testMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8)); testMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8)); testMotion('+', '+', makeCursor(1, lines[1].textStart), makeCursor(0, 8)); testMotion('-', '-', makeCursor(0, lines[0].textStart), makeCursor(1, 4)); testMotion('_', ['6','_'], makeCursor(5, lines[5].textStart), makeCursor(0, 8)); testMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1)); testMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1), makeCursor(0, 3)); testMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0)); testMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]); testMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0)); testMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1), makeCursor(charLine.line, 0)); testMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1), pChars[0]); testMotion('F', ['F', 'p'], pChars[0], pChars[1]); testMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]); testMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]); testMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]); testMotion('%_parens', ['%'], parens1.end, parens1.start); testMotion('%_squares', ['%'], squares1.end, squares1.start); testMotion('%_braces', ['%'], curlys1.end, curlys1.start); testMotion('%_seek_outside', ['%'], seekOutside.end, seekOutside.start); testMotion('%_seek_inside', ['%'], seekInside.end, seekInside.start); testVim('%_seek_skip', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['%']); helpers.assertCursorAt(0,9); }, {value:'01234"("()'}); testVim('%_skip_string', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['%']); helpers.assertCursorAt(0,4); cm.setCursor(0,2); helpers.doKeys(['%']); helpers.assertCursorAt(0,0); }, {value:'(")")'}); testVim('%_skip_comment', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['%']); helpers.assertCursorAt(0,6); cm.setCursor(0,3); helpers.doKeys(['%']); helpers.assertCursorAt(0,0); }, {value:'(/*)*/)'}); // Make sure that moving down after going to the end of a line always leaves you // at the end of a line, but preserves the offset in other cases testVim('Changing lines after Eol operation', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys(['$']); helpers.doKeys(['j']); // After moving to Eol and then down, we should be at Eol of line 2 helpers.assertCursorAt(new Pos(1, lines[1].length - 1)); helpers.doKeys(['j']); // After moving down, we should be at Eol of line 3 helpers.assertCursorAt(new Pos(2, lines[2].length - 1)); helpers.doKeys(['h']); helpers.doKeys(['j']); // After moving back one space and then down, since line 4 is shorter than line 2, we should // be at Eol of line 2 - 1 helpers.assertCursorAt(new Pos(3, lines[3].length - 1)); helpers.doKeys(['j']); helpers.doKeys(['j']); // After moving down again, since line 3 has enough characters, we should be back to the // same place we were at on line 1 helpers.assertCursorAt(new Pos(5, lines[2].length - 2)); }); //making sure gj and gk recover from clipping testVim('gj_gk_clipping', function(cm,vim,helpers){ cm.setCursor(0, 1); helpers.doKeys('g','j','g','j'); helpers.assertCursorAt(2, 1); helpers.doKeys('g','k','g','k'); helpers.assertCursorAt(0, 1); },{value: 'line 1\n\nline 2'}); //testing a mix of j/k and gj/gk testVim('j_k_and_gj_gk', function(cm,vim,helpers){ cm.setSize(120); cm.setCursor(0, 0); //go to the last character on the first line helpers.doKeys('$'); //move up/down on the column within the wrapped line //side-effect: cursor is not locked to eol anymore helpers.doKeys('g','k'); var cur=cm.getCursor(); eq(cur.line,0); is((cur.ch<176),'gk didn\'t move cursor back (1)'); helpers.doKeys('g','j'); helpers.assertCursorAt(0, 176); //should move to character 177 on line 2 (j/k preserve character index within line) helpers.doKeys('j'); //due to different line wrapping, the cursor can be on a different screen-x now //gj and gk preserve screen-x on movement, much like moveV helpers.doKeys('3','g','k'); cur=cm.getCursor(); eq(cur.line,1); is((cur.ch<176),'gk didn\'t move cursor back (2)'); helpers.doKeys('g','j','2','g','j'); //should return to the same character-index helpers.doKeys('k'); helpers.assertCursorAt(0, 176); },{ 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.'}); testVim('gj_gk', function(cm, vim, helpers) { if (phantom) return; cm.setSize(120); // Test top of document edge case. cm.setCursor(0, 4); helpers.doKeys('g', 'j'); helpers.doKeys('10', 'g', 'k'); helpers.assertCursorAt(0, 4); // Test moving down preserves column position. helpers.doKeys('g', 'j'); var pos1 = cm.getCursor(); var expectedPos2 = new Pos(0, (pos1.ch - 4) * 2 + 4); helpers.doKeys('g', 'j'); helpers.assertCursorAt(expectedPos2); // Move to the last character cm.setCursor(0, 0); // Move left to reset HSPos helpers.doKeys('h'); // Test bottom of document edge case. helpers.doKeys('100', 'g', 'j'); var endingPos = cm.getCursor(); is(endingPos != 0, 'gj should not be on wrapped line 0'); var topLeftCharCoords = cm.charCoords(makeCursor(0, 0)); var endingCharCoords = cm.charCoords(endingPos); is(topLeftCharCoords.left == endingCharCoords.left, 'gj should end up on column 0'); },{ lineNumbers: false, lineWrapping:true, value: 'Thislineisintentionallylongtotestmovementofgjandgkoverwrappedlines.' }); testVim('}', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('}'); helpers.assertCursorAt(1, 0); cm.setCursor(0, 0); helpers.doKeys('2', '}'); helpers.assertCursorAt(4, 0); cm.setCursor(0, 0); helpers.doKeys('6', '}'); helpers.assertCursorAt(5, 0); }, { value: 'a\n\nb\nc\n\nd' }); testVim('{', function(cm, vim, helpers) { cm.setCursor(5, 0); helpers.doKeys('{'); helpers.assertCursorAt(4, 0); cm.setCursor(5, 0); helpers.doKeys('2', '{'); helpers.assertCursorAt(1, 0); cm.setCursor(5, 0); helpers.doKeys('6', '{'); helpers.assertCursorAt(0, 0); }, { value: 'a\n\nb\nc\n\nd' }); testVim('(', function(cm, vim, helpers) { cm.setCursor(6, 23); helpers.doKeys('('); helpers.assertCursorAt(6, 14); helpers.doKeys('2', '('); helpers.assertCursorAt(5, 0); helpers.doKeys('('); helpers.assertCursorAt(4, 0); helpers.doKeys('('); helpers.assertCursorAt(3, 0); helpers.doKeys('('); helpers.assertCursorAt(2, 0); helpers.doKeys('('); helpers.assertCursorAt(0, 0); helpers.doKeys('('); helpers.assertCursorAt(0, 0); }, { value: 'sentence1.\n\n\nsentence2\n\nsentence3. sentence4\n sentence5? sentence6!' }); testVim(')', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('2', ')'); helpers.assertCursorAt(3, 0); helpers.doKeys(')'); helpers.assertCursorAt(4, 0); helpers.doKeys(')'); helpers.assertCursorAt(5, 0); helpers.doKeys(')'); helpers.assertCursorAt(5, 11); helpers.doKeys(')'); helpers.assertCursorAt(6, 14); helpers.doKeys(')'); helpers.assertCursorAt(6, 23); helpers.doKeys(')'); helpers.assertCursorAt(6, 23); }, { value: 'sentence1.\n\n\nsentence2\n\nsentence3. sentence4\n sentence5? sentence6!' }); testVim('paragraph_motions', function(cm, vim, helpers) { cm.setCursor(10, 0); helpers.doKeys('{'); helpers.assertCursorAt(4, 0); helpers.doKeys('{'); helpers.assertCursorAt(0, 0); helpers.doKeys('2', '}'); helpers.assertCursorAt(7, 0); helpers.doKeys('2', '}'); helpers.assertCursorAt(16, 0); cm.setCursor(9, 0); helpers.doKeys('}'); helpers.assertCursorAt(14, 0); cm.setCursor(6, 0); helpers.doKeys('}'); helpers.assertCursorAt(7, 0); // ip inside empty space cm.setCursor(10, 0); helpers.doKeys('v', 'i', 'p'); eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); eqCursorPos(Pos(12, 0), cm.getCursor('head')); helpers.doKeys('i', 'p'); eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); eqCursorPos(Pos(13, 1), cm.getCursor('head')); helpers.doKeys('2', 'i', 'p'); eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); eqCursorPos(Pos(16, 1), cm.getCursor('head')); // should switch to visualLine mode cm.setCursor(14, 0); helpers.doKeys('', 'v', 'i', 'p'); helpers.assertCursorAt(14, 0); cm.setCursor(14, 0); helpers.doKeys('', 'V', 'i', 'p'); eqCursorPos(Pos(16, 1), cm.getCursor('head')); // ap inside empty space cm.setCursor(10, 0); helpers.doKeys('', 'v', 'a', 'p'); eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); eqCursorPos(Pos(13, 1), cm.getCursor('head')); helpers.doKeys('a', 'p'); eqCursorPos(Pos(7, 0), cm.getCursor('anchor')); eqCursorPos(Pos(16, 1), cm.getCursor('head')); cm.setCursor(13, 0); helpers.doKeys('v', 'a', 'p'); eqCursorPos(Pos(13, 0), cm.getCursor('anchor')); eqCursorPos(Pos(14, 0), cm.getCursor('head')); cm.setCursor(16, 0); helpers.doKeys('v', 'a', 'p'); eqCursorPos(Pos(14, 0), cm.getCursor('anchor')); eqCursorPos(Pos(16, 1), cm.getCursor('head')); cm.setCursor(0, 0); helpers.doKeys('v', 'a', 'p'); eqCursorPos(Pos(0, 0), cm.getCursor('anchor')); eqCursorPos(Pos(4, 0), cm.getCursor('head')); cm.setCursor(0, 0); helpers.doKeys('d', 'i', 'p'); var register = helpers.getRegisterController().getRegister(); eq('a\na\n', register.toString()); is(register.linewise); helpers.doKeys('3', 'j', 'p'); helpers.doKeys('y', 'i', 'p'); is(register.linewise); eq('b\na\na\nc\n', register.toString()); }, { value: 'a\na\n\n\n\nb\nc\n\n\n\n\n\n\nd\n\ne\nf' }); // Operator tests testVim('dl', function(cm, vim, helpers) { var curStart = makeCursor(0, 0); cm.setCursor(curStart); helpers.doKeys('d', 'l'); eq('word1 ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' ', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1 ' }); testVim('dl_eol', function(cm, vim, helpers) { cm.setCursor(0, 6); helpers.doKeys('d', 'l'); eq(' word1', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' ', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 5); }, { value: ' word1 ' }); testVim('dl_repeat', function(cm, vim, helpers) { var curStart = makeCursor(0, 0); cm.setCursor(curStart); helpers.doKeys('2', 'd', 'l'); eq('ord1 ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' w', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1 ' }); testVim('dh', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('d', 'h'); eq(' wrd1 ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('o', register.toString()); is(!register.linewise); eqCursorPos(offsetCursor(curStart, 0 , -1), cm.getCursor()); }, { value: ' word1 ' }); testVim('dj', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('d', 'j'); eq(' word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' word1\nword2\n', register.toString()); is(register.linewise); helpers.assertCursorAt(0, 1); }, { value: ' word1\nword2\n word3' }); testVim('dj_end_of_document', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('d', 'j'); eq('', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' word1 \n', register.toString()); is(register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1 ' }); testVim('dk', function(cm, vim, helpers) { var curStart = makeCursor(1, 3); cm.setCursor(curStart); helpers.doKeys('d', 'k'); eq(' word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' word1\nword2\n', register.toString()); is(register.linewise); helpers.assertCursorAt(0, 1); }, { value: ' word1\nword2\n word3' }); testVim('dk_start_of_document', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('d', 'k'); eq('', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' word1 \n', register.toString()); is(register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1 ' }); testVim('dw_space', function(cm, vim, helpers) { var curStart = makeCursor(0, 0); cm.setCursor(curStart); helpers.doKeys('d', 'w'); eq('word1 ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' ', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1 ' }); testVim('dw_word', function(cm, vim, helpers) { var curStart = makeCursor(0, 1); cm.setCursor(curStart); helpers.doKeys('d', 'w'); eq(' word2', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1 ', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1 word2' }); testVim('dw_unicode_word', function(cm, vim, helpers) { helpers.doKeys('d', 'w'); eq(cm.getValue().length, 10); helpers.doKeys('d', 'w'); eq(cm.getValue().length, 6); helpers.doKeys('d', 'w'); eq(cm.getValue().length, 5); helpers.doKeys('d', 'e'); eq(cm.getValue().length, 2); }, { value: ' \u0562\u0561\u0580\u0587\xbbe\xb5g ' }); testVim('dw_only_word', function(cm, vim, helpers) { // Test that if there is only 1 word left, dw deletes till the end of the // line. cm.setCursor(0, 1); helpers.doKeys('d', 'w'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1 ', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1 ' }); testVim('dw_eol', function(cm, vim, helpers) { // Assert that dw does not delete the newline if last word to delete is at end // of line. cm.setCursor(0, 1); helpers.doKeys('d', 'w'); eq(' \nword2', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1\nword2' }); testVim('dw_eol_with_multiple_newlines', function(cm, vim, helpers) { // Assert that dw does not delete the newline if last word to delete is at end // of line and it is followed by multiple newlines. cm.setCursor(0, 1); helpers.doKeys('d', 'w'); eq(' \n\nword2', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1\n\nword2' }); testVim('dw_empty_line_followed_by_whitespace', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq(' \nword', cm.getValue()); }, { value: '\n \nword' }); testVim('dw_empty_line_followed_by_word', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('word', cm.getValue()); }, { value: '\nword' }); testVim('dw_empty_line_followed_by_empty_line', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n', cm.getValue()); }, { value: '\n\n' }); testVim('dw_whitespace_followed_by_whitespace', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n \n', cm.getValue()); }, { value: ' \n \n' }); testVim('dw_whitespace_followed_by_empty_line', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n\n', cm.getValue()); }, { value: ' \n\n' }); testVim('dw_word_whitespace_word', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'w'); eq('\n \nword2', cm.getValue()); }, { value: 'word1\n \nword2'}) testVim('dw_end_of_document', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('d', 'w'); eq('\nab', cm.getValue()); }, { value: '\nabc' }); testVim('dw_repeat', function(cm, vim, helpers) { // Assert that dw does delete newline if it should go to the next line, and // that repeat works properly. cm.setCursor(0, 1); helpers.doKeys('d', '2', 'w'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1\nword2', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 0); }, { value: ' word1\nword2' }); testVim('de_word_start_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'e'); eq('\n\n', cm.getValue()); }, { value: 'word\n\n' }); testVim('de_word_end_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(0, 3); helpers.doKeys('d', 'e'); eq('wor', cm.getValue()); }, { value: 'word\n\n\n' }); testVim('de_whitespace_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'e'); eq('', cm.getValue()); }, { value: ' \n\n\n' }); testVim('de_end_of_document', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('d', 'e'); eq('\nab', cm.getValue()); }, { value: '\nabc' }); testVim('db_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'b'); eq('\n\n', cm.getValue()); }, { value: '\n\n\n' }); testVim('db_word_start_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'b'); eq('\nword', cm.getValue()); }, { value: '\n\nword' }); testVim('db_word_end_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 3); helpers.doKeys('d', 'b'); eq('\n\nd', cm.getValue()); }, { value: '\n\nword' }); testVim('db_whitespace_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'b'); eq('', cm.getValue()); }, { value: '\n \n' }); testVim('db_start_of_document', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'b'); eq('abc\n', cm.getValue()); }, { value: 'abc\n' }); testVim('dge_empty_lines', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doKeys('d', 'g', 'e'); // Note: In real VIM the result should be '', but it's not quite consistent, // since 2 newlines are deleted. But in the similar case of word\n\n, only // 1 newline is deleted. We'll diverge from VIM's behavior since it's much // easier this way. eq('\n', cm.getValue()); }, { value: '\n\n' }); testVim('dge_word_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doKeys('d', 'g', 'e'); eq('wor\n', cm.getValue()); }, { value: 'word\n\n'}); testVim('dge_whitespace_and_empty_lines', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('d', 'g', 'e'); eq('', cm.getValue()); }, { value: '\n \n' }); testVim('dge_start_of_document', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('d', 'g', 'e'); eq('bc\n', cm.getValue()); }, { value: 'abc\n' }); testVim('d_inclusive', function(cm, vim, helpers) { // Assert that when inclusive is set, the character the cursor is on gets // deleted too. var curStart = makeCursor(0, 1); cm.setCursor(curStart); helpers.doKeys('d', 'e'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1 ' }); testVim('d_reverse', function(cm, vim, helpers) { // Test that deleting in reverse works. cm.setCursor(1, 0); helpers.doKeys('d', 'b'); eq(' word2 ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1\n', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 1); }, { value: ' word1\nword2 ' }); testVim('dd', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedBuffer = cm.getRange(new Pos(0, 0), new Pos(1, 0)); var expectedLineCount = cm.lineCount() - 1; helpers.doKeys('d', 'd'); eq(expectedLineCount, cm.lineCount()); var register = helpers.getRegisterController().getRegister(); eq(expectedBuffer, register.toString()); is(register.linewise); helpers.assertCursorAt(0, lines[1].textStart); }); testVim('dd_prefix_repeat', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedBuffer = cm.getRange(new Pos(0, 0), new Pos(2, 0)); var expectedLineCount = cm.lineCount() - 2; helpers.doKeys('2', 'd', 'd'); eq(expectedLineCount, cm.lineCount()); var register = helpers.getRegisterController().getRegister(); eq(expectedBuffer, register.toString()); is(register.linewise); helpers.assertCursorAt(0, lines[2].textStart); }); testVim('dd_motion_repeat', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedBuffer = cm.getRange(new Pos(0, 0), new Pos(2, 0)); var expectedLineCount = cm.lineCount() - 2; helpers.doKeys('d', '2', 'd'); eq(expectedLineCount, cm.lineCount()); var register = helpers.getRegisterController().getRegister(); eq(expectedBuffer, register.toString()); is(register.linewise); helpers.assertCursorAt(0, lines[2].textStart); }); testVim('dd_multiply_repeat', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedBuffer = cm.getRange(new Pos(0, 0), new Pos(6, 0)); var expectedLineCount = cm.lineCount() - 6; helpers.doKeys('2', 'd', '3', 'd'); eq(expectedLineCount, cm.lineCount()); var register = helpers.getRegisterController().getRegister(); eq(expectedBuffer, register.toString()); is(register.linewise); helpers.assertCursorAt(0, lines[6].textStart); }); testVim('dd_lastline', function(cm, vim, helpers) { cm.setCursor(cm.lineCount(), 0); var expectedLineCount = cm.lineCount() - 1; helpers.doKeys('d', 'd'); eq(expectedLineCount, cm.lineCount()); helpers.assertCursorAt(cm.lineCount() - 1, 0); }); testVim('dd_only_line', function(cm, vim, helpers) { cm.setCursor(0, 0); var expectedRegister = cm.getValue() + "\n"; helpers.doKeys('d','d'); eq(1, cm.lineCount()); eq('', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(expectedRegister, register.toString()); }, { value: "thisistheonlyline" }); // Yank commands should behave the exact same as d commands, expect that nothing // gets deleted. testVim('yw_repeat', function(cm, vim, helpers) { // Assert that yw does yank newline if it should go to the next line, and // that repeat works properly. var curStart = makeCursor(0, 1); cm.setCursor(curStart); helpers.doKeys('y', '2', 'w'); eq(' word1\nword2', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1\nword2', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1\nword2' }); testVim('yy_multiply_repeat', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); var expectedBuffer = cm.getRange(new Pos(0, 0), new Pos(6, 0)); var expectedLineCount = cm.lineCount(); helpers.doKeys('2', 'y', '3', 'y'); eq(expectedLineCount, cm.lineCount()); var register = helpers.getRegisterController().getRegister(); eq(expectedBuffer, register.toString()); is(register.linewise); eqCursorPos(curStart, cm.getCursor()); }); testVim('2dd_blank_P', function(cm, vim, helpers) { helpers.doKeys('2', 'd', 'd', 'P'); eq('\na\n\n', cm.getValue()); }, { value: '\na\n\n' }); // Change commands behave like d commands except that it also enters insert // mode. In addition, when the change is linewise, an additional newline is // inserted so that insert mode starts on that line. testVim('cw', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('c', '2', 'w'); eq(' word3', cm.getValue()); helpers.assertCursorAt(0, 0); }, { value: 'word1 word2 word3'}); testVim('cw_repeat', function(cm, vim, helpers) { // Assert that cw does delete newline if it should go to the next line, and // that repeat works properly. var curStart = makeCursor(0, 1); cm.setCursor(curStart); helpers.doKeys('c', '2', 'w'); eq(' ', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word1\nword2', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); eq('vim-insert', cm.getOption('keyMap')); }, { value: ' word1\nword2' }); testVim('cc_multiply_repeat', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedBuffer = cm.getRange(new Pos(0, 0), new Pos(6, 0)); var expectedLineCount = cm.lineCount() - 5; helpers.doKeys('2', 'c', '3', 'c'); eq(expectedLineCount, cm.lineCount()); var register = helpers.getRegisterController().getRegister(); eq(expectedBuffer, register.toString()); is(register.linewise); eq('vim-insert', cm.getOption('keyMap')); }); testVim('ct', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('c', 't', 'w'); eq(' word1 word3', cm.getValue()); helpers.doKeys('', 'c', '|'); eq(' word3', cm.getValue()); helpers.assertCursorAt(0, 0); helpers.doKeys('', '2', 'u', 'w', 'h'); helpers.doKeys('c', '2', 'g', 'e'); eq(' wordword3', cm.getValue()); }, { value: ' word1 word2 word3'}); testVim('cc_should_not_append_to_document', function(cm, vim, helpers) { var expectedLineCount = cm.lineCount(); cm.setCursor(cm.lastLine(), 0); helpers.doKeys('c', 'c'); eq(expectedLineCount, cm.lineCount()); }); function fillArray(val, times) { var arr = []; for (var i = 0; i < times; i++) { arr.push(val); } return arr; } testVim('c_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('', '2', 'j', 'l', 'l', 'l', 'c'); var replacement = fillArray('hello', 3); cm.replaceSelections(replacement); eq('1hello\n5hello\nahellofg', cm.getValue()); helpers.doKeys(''); cm.setCursor(2, 3); helpers.doKeys('', '2', 'k', 'h', 'C'); replacement = fillArray('world', 3); cm.replaceSelections(replacement); eq('1hworld\n5hworld\nahworld', cm.getValue()); }, {value: '1234\n5678\nabcdefg'}); testVim('c_visual_block_replay', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('', '2', 'j', 'l', 'c'); var replacement = fillArray('fo', 3); cm.replaceSelections(replacement); eq('1fo4\n5fo8\nafodefg', cm.getValue()); helpers.doKeys(''); cm.setCursor(0, 0); helpers.doKeys('.'); eq('foo4\nfoo8\nfoodefg', cm.getValue()); }, {value: '1234\n5678\nabcdefg'}); testVim('d_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('', '2', 'j', 'l', 'l', 'l', 'd'); eq('1\n5\nafg', cm.getValue()); }, {value: '1234\n5678\nabcdefg'}); testVim('D_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('', '2', 'j', 'l', 'D'); eq('1\n5\na', cm.getValue()); }, {value: '1234\n5678\nabcdefg'}); testVim('s_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('', '2', 'j', 'l', 'l', 'l', 's'); var replacement = fillArray('hello{', 3); cm.replaceSelections(replacement); eq('1hello{\n5hello{\nahello{fg\n', cm.getValue()); helpers.doKeys(''); cm.setCursor(2, 3); helpers.doKeys('', '1', 'k', 'h', 'S'); replacement = fillArray('world', 1); cm.replaceSelections(replacement); eq('1hello{\n world\n', cm.getValue()); }, {value: '1234\n5678\nabcdefg\n'}); // Swapcase commands edit in place and do not modify registers. testVim('g~w_repeat', function(cm, vim, helpers) { // Assert that dw does delete newline if it should go to the next line, and // that repeat works properly. var curStart = makeCursor(0, 1); cm.setCursor(curStart); helpers.doKeys('g', '~', '2', 'w'); eq(' WORD1\nWORD2', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1\nword2' }); testVim('g~g~', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); var expectedLineCount = cm.lineCount(); var expectedValue = cm.getValue().toUpperCase(); helpers.doKeys('2', 'g', '~', '3', 'g', '~'); eq(expectedValue, cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); }, { value: ' word1\nword2\nword3\nword4\nword5\nword6' }); testVim('gu_and_gU', function(cm, vim, helpers) { var curStart = makeCursor(0, 7); var value = cm.getValue(); cm.setCursor(curStart); helpers.doKeys('2', 'g', 'U', 'w'); eq(cm.getValue(), 'wa wb xX WC wd'); eqCursorPos(curStart, cm.getCursor()); helpers.doKeys('2', 'g', 'u', 'w'); eq(cm.getValue(), value); helpers.doKeys('2', 'g', 'U', 'B'); eq(cm.getValue(), 'wa WB Xx wc wd'); eqCursorPos(makeCursor(0, 3), cm.getCursor()); cm.setCursor(makeCursor(0, 4)); helpers.doKeys('g', 'u', 'i', 'w'); eq(cm.getValue(), 'wa wb Xx wc wd'); eqCursorPos(makeCursor(0, 3), cm.getCursor()); // TODO: support gUgU guu // eqCursorPos(makeCursor(0, 0), cm.getCursor()); var register = helpers.getRegisterController().getRegister(); eq('', register.toString()); is(!register.linewise); }, { value: 'wa wb xx wc wd' }); testVim('visual_block_~', function(cm, vim, helpers) { cm.setCursor(1, 1); helpers.doKeys('', 'l', 'l', 'j', '~'); helpers.assertCursorAt(1, 1); eq('hello\nwoRLd\naBCDe', cm.getValue()); cm.setCursor(2, 0); helpers.doKeys('v', 'l', 'l', '~'); helpers.assertCursorAt(2, 0); eq('hello\nwoRLd\nAbcDe', cm.getValue()); },{value: 'hello\nwOrld\nabcde' }); testVim('._swapCase_visualBlock', function(cm, vim, helpers) { helpers.doKeys('', 'j', 'j', 'l', '~'); cm.setCursor(0, 3); helpers.doKeys('.'); eq('HelLO\nWorLd\nAbcdE', cm.getValue()); },{value: 'hEllo\nwOrlD\naBcDe' }); testVim('._delete_visualBlock', function(cm, vim, helpers) { helpers.doKeys('', 'j', 'x'); eq('ive\ne\nsome\nsugar', cm.getValue()); helpers.doKeys('.'); eq('ve\n\nsome\nsugar', cm.getValue()); helpers.doKeys('j', 'j', '.'); eq('ve\n\nome\nugar', cm.getValue()); helpers.doKeys('u', '', '.'); eq('ve\n\nme\ngar', cm.getValue()); },{value: 'give\nme\nsome\nsugar' }); testVim('>{motion}', function(cm, vim, helpers) { cm.setCursor(1, 3); var expectedLineCount = cm.lineCount(); var expectedValue = ' word1\n word2\nword3 '; helpers.doKeys('>', 'k'); eq(expectedValue, cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 3); }, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); testVim('>>', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedLineCount = cm.lineCount(); var expectedValue = ' word1\n word2\nword3 '; helpers.doKeys('2', '>', '>'); eq(expectedValue, cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 3); }, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); testVim('<{motion}', function(cm, vim, helpers) { cm.setCursor(1, 3); var expectedLineCount = cm.lineCount(); var expectedValue = ' word1\nword2\nword3 '; helpers.doKeys('<', 'k'); eq(expectedValue, cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 1); }, { value: ' word1\n word2\nword3 ', indentUnit: 2 }); testVim('<<', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedLineCount = cm.lineCount(); var expectedValue = ' word1\nword2\nword3 '; helpers.doKeys('2', '<', '<'); eq(expectedValue, cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 1); }, { value: ' word1\n word2\nword3 ', indentUnit: 2 }); testVim('=', function(cm, vim, helpers) { cm.setCursor(0, 3); helpers.doKeys('', 'j', 'j'); var expectedValue = 'word1\nword2\nword3'; helpers.doKeys('='); eq(expectedValue, cm.getValue()); }, { value: ' word1\n word2\n word3', indentUnit: 2 }); // Edit tests function testEdit(name, before, pos, edit, after) { return testVim(name, function(cm, vim, helpers) { var ch = before.search(pos) var line = before.substring(0, ch).split('\n').length - 1; if (line) { ch = before.substring(0, ch).split('\n').pop().length; } cm.setCursor(line, ch); helpers.doKeys.apply(this, edit.split('')); eq(after, cm.getValue()); }, {value: before}); } // These Delete tests effectively cover word-wise Change, Visual & Yank. // Tabs are used as differentiated whitespace to catch edge cases. // Normal word: testEdit('diw_mid_spc', 'foo \tbAr\t baz', /A/, 'diw', 'foo \t\t baz'); testEdit('daw_mid_spc', 'foo \tbAr\t baz', /A/, 'daw', 'foo \tbaz'); testEdit('diw_mid_punct', 'foo \tbAr.\t baz', /A/, 'diw', 'foo \t.\t baz'); testEdit('daw_mid_punct', 'foo \tbAr.\t baz', /A/, 'daw', 'foo.\t baz'); testEdit('diw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diw', 'foo \t,.\t baz'); testEdit('daw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daw', 'foo \t,.\t baz'); testEdit('diw_start_spc', 'bAr \tbaz', /A/, 'diw', ' \tbaz'); testEdit('daw_start_spc', 'bAr \tbaz', /A/, 'daw', 'baz'); testEdit('diw_start_punct', 'bAr. \tbaz', /A/, 'diw', '. \tbaz'); testEdit('daw_start_punct', 'bAr. \tbaz', /A/, 'daw', '. \tbaz'); testEdit('diw_end_spc', 'foo \tbAr', /A/, 'diw', 'foo \t'); testEdit('daw_end_spc', 'foo \tbAr', /A/, 'daw', 'foo'); testEdit('diw_end_punct', 'foo \tbAr.', /A/, 'diw', 'foo \t.'); testEdit('daw_end_punct', 'foo \tbAr.', /A/, 'daw', 'foo.'); // Big word: testEdit('diW_mid_spc', 'foo \tbAr\t baz', /A/, 'diW', 'foo \t\t baz'); testEdit('daW_mid_spc', 'foo \tbAr\t baz', /A/, 'daW', 'foo \tbaz'); testEdit('diW_mid_punct', 'foo \tbAr.\t baz', /A/, 'diW', 'foo \t\t baz'); testEdit('daW_mid_punct', 'foo \tbAr.\t baz', /A/, 'daW', 'foo \tbaz'); testEdit('diW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diW', 'foo \t\t baz'); testEdit('daW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daW', 'foo \tbaz'); testEdit('diW_start_spc', 'bAr\t baz', /A/, 'diW', '\t baz'); testEdit('daW_start_spc', 'bAr\t baz', /A/, 'daW', 'baz'); testEdit('diW_start_punct', 'bAr.\t baz', /A/, 'diW', '\t baz'); testEdit('daW_start_punct', 'bAr.\t baz', /A/, 'daW', 'baz'); testEdit('diW_end_spc', 'foo \tbAr', /A/, 'diW', 'foo \t'); testEdit('daW_end_spc', 'foo \tbAr', /A/, 'daW', 'foo'); testEdit('diW_end_punct', 'foo \tbAr.', /A/, 'diW', 'foo \t'); testEdit('daW_end_punct', 'foo \tbAr.', /A/, 'daW', 'foo'); // Deleting text objects // Open and close on same line testEdit('di(_open_spc', 'foo (bAr) baz', /\(/, 'di(', 'foo () baz'); testEdit('di)_open_spc', 'foo (bAr) baz', /\(/, 'di)', 'foo () baz'); testEdit('dib_open_spc', 'foo (bAr) baz', /\(/, 'dib', 'foo () baz'); testEdit('da(_open_spc', 'foo (bAr) baz', /\(/, 'da(', 'foo baz'); testEdit('da)_open_spc', 'foo (bAr) baz', /\(/, 'da)', 'foo baz'); testEdit('di(_middle_spc', 'foo (bAr) baz', /A/, 'di(', 'foo () baz'); testEdit('di)_middle_spc', 'foo (bAr) baz', /A/, 'di)', 'foo () baz'); testEdit('da(_middle_spc', 'foo (bAr) baz', /A/, 'da(', 'foo baz'); testEdit('da)_middle_spc', 'foo (bAr) baz', /A/, 'da)', 'foo baz'); testEdit('di(_close_spc', 'foo (bAr) baz', /\)/, 'di(', 'foo () baz'); testEdit('di)_close_spc', 'foo (bAr) baz', /\)/, 'di)', 'foo () baz'); testEdit('da(_close_spc', 'foo (bAr) baz', /\)/, 'da(', 'foo baz'); testEdit('da)_close_spc', 'foo (bAr) baz', /\)/, 'da)', 'foo baz'); // delete around and inner b. testEdit('dab_on_(_should_delete_around_()block', 'o( in(abc) )', /\(a/, 'dab', 'o( in )'); // delete around and inner B. testEdit('daB_on_{_should_delete_around_{}block', 'o{ in{abc} }', /{a/, 'daB', 'o{ in }'); testEdit('diB_on_{_should_delete_inner_{}block', 'o{ in{abc} }', /{a/, 'diB', 'o{ in{} }'); testEdit('da{_on_{_should_delete_inner_block', 'o{ in{abc} }', /{a/, 'da{', 'o{ in }'); testEdit('di[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'di[', 'foo (bAr) baz'); testEdit('di[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'di[', 'foo (bAr) baz'); testEdit('da[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'da[', 'foo (bAr) baz'); testEdit('da[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'da[', 'foo (bAr) baz'); testMotion('di(_outside_should_stay', ['d', 'i', '('], new Pos(0, 0), new Pos(0, 0)); // Open and close on different lines, equally indented testEdit('di{_middle_spc', 'a{\n\tbar\n}b', /r/, 'di{', 'a{}b'); testEdit('di}_middle_spc', 'a{\n\tbar\n}b', /r/, 'di}', 'a{}b'); testEdit('da{_middle_spc', 'a{\n\tbar\n}b', /r/, 'da{', 'ab'); testEdit('da}_middle_spc', 'a{\n\tbar\n}b', /r/, 'da}', 'ab'); testEdit('daB_middle_spc', 'a{\n\tbar\n}b', /r/, 'daB', 'ab'); // open and close on diff lines, open indented less than close testEdit('di{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di{', 'a{}b'); testEdit('di}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di}', 'a{}b'); testEdit('da{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da{', 'ab'); testEdit('da}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da}', 'ab'); // open and close on diff lines, open indented more than close testEdit('di[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di[', 'a\t[]b'); testEdit('di]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di]', 'a\t[]b'); testEdit('da[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da[', 'a\tb'); testEdit('da]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da]', 'a\tb'); // open and close on diff lines, open indented more than close testEdit('di<_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'di<', 'a\t<>b'); testEdit('di>_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'di>', 'a\t<>b'); testEdit('da<_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'da<', 'a\tb'); testEdit('da>_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'da>', 'a\tb'); function testSelection(name, before, pos, keys, sel) { return testVim(name, function(cm, vim, helpers) { var ch = before.search(pos) var line = before.substring(0, ch).split('\n').length - 1; if (line) { ch = before.substring(0, ch).split('\n').pop().length; } cm.setCursor(line, ch); helpers.doKeys.apply(this, keys.split('')); eq(sel, cm.getSelection()); }, {value: before}); } testSelection('viw_middle_spc', 'foo \tbAr\t baz', /A/, 'viw', 'bAr'); testSelection('vaw_middle_spc', 'foo \tbAr\t baz', /A/, 'vaw', 'bAr\t '); testSelection('viw_middle_punct', 'foo \tbAr,\t baz', /A/, 'viw', 'bAr'); testSelection('vaW_middle_punct', 'foo \tbAr,\t baz', /A/, 'vaW', 'bAr,\t '); testSelection('viw_start_spc', 'foo \tbAr\t baz', /b/, 'viw', 'bAr'); testSelection('viw_end_spc', 'foo \tbAr\t baz', /r/, 'viw', 'bAr'); testSelection('viw_eol', 'foo \tbAr', /r/, 'viw', 'bAr'); testSelection('vi{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'vi{', '\n\tbar\n\t'); testSelection('va{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'va{', '{\n\tbar\n\t}'); testVim('mouse_select', function(cm, vim, helpers) { cm.setSelection(Pos(0, 2), Pos(0, 4), {origin: '*mouse'}); is(cm.state.vim.visualMode); is(!cm.state.vim.visualLine); is(!cm.state.vim.visualBlock); helpers.doKeys(''); is(!cm.somethingSelected()); helpers.doKeys('g', 'v'); eq('cd', cm.getSelection()); }, {value: 'abcdef'}); // Operator-motion tests testVim('D', function(cm, vim, helpers) { cm.setCursor(0, 3); helpers.doKeys('D'); eq(' wo\nword2\n word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('rd1', register.toString()); is(!register.linewise); helpers.assertCursorAt(0, 2); }, { value: ' word1\nword2\n word3' }); testVim('C', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('C'); eq(' wo\nword2\n word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('rd1', register.toString()); is(!register.linewise); eqCursorPos(curStart, cm.getCursor()); eq('vim-insert', cm.getOption('keyMap')); }, { value: ' word1\nword2\n word3' }); testVim('Y', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys('Y'); eq(' word1\nword2\n word3', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq(' word1\n', register.toString()); is(register.linewise); helpers.assertCursorAt(0, 3); }, { value: ' word1\nword2\n word3' }); testVim('~', function(cm, vim, helpers) { helpers.doKeys('3', '~'); eq('ABCdefg', cm.getValue()); helpers.assertCursorAt(0, 3); }, { value: 'abcdefg' }); // Action tests testVim('ctrl-a', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(''); eq('-9', cm.getValue()); helpers.assertCursorAt(0, 1); helpers.doKeys('2',''); eq('-7', cm.getValue()); }, {value: '-10'}); testVim('ctrl-x', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(''); eq('-1', cm.getValue()); helpers.assertCursorAt(0, 1); helpers.doKeys('2',''); eq('-3', cm.getValue()); }, {value: '0'}); testVim('/ search forward', function(cm, vim, helpers) { forEach(['', ''], function(key) { cm.setCursor(0, 0); helpers.doKeys(key); helpers.assertCursorAt(0, 5); helpers.doKeys('l'); helpers.doKeys(key); helpers.assertCursorAt(0, 10); cm.setCursor(0, 11); helpers.doKeys(key); helpers.assertCursorAt(0, 11); }); }, {value: '__jmp1 jmp2 jmp'}); testVim('insert_ctrl_w', function(cm, vim, helpers) { var curStart = makeCursor(0, 10); cm.setCursor(curStart); helpers.doKeys('a'); helpers.doKeys(''); eq('word1/', cm.getValue()); var register = helpers.getRegisterController().getRegister(); eq('word2', register.toString()); is(!register.linewise); var curEnd = makeCursor(0, 6); eqCursorPos(curEnd, cm.getCursor()); eq('vim-insert', cm.getOption('keyMap')); }, { value: 'word1/word2' }); testVim('normal_ctrl_w', function(cm, vim, helpers) { var curStart = makeCursor(0, 3); cm.setCursor(curStart); helpers.doKeys(''); eq('word', cm.getValue()); var curEnd = makeCursor(0, 3); helpers.assertCursorAt(0,3); eqCursorPos(curEnd, cm.getCursor()); eq('vim', cm.getOption('keyMap')); }, {value: 'word'}); testVim('a', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('a'); helpers.assertCursorAt(0, 2); eq('vim-insert', cm.getOption('keyMap')); }); testVim('a_eol', function(cm, vim, helpers) { cm.setCursor(0, lines[0].length - 1); helpers.doKeys('a'); helpers.assertCursorAt(0, lines[0].length); eq('vim-insert', cm.getOption('keyMap')); }); testVim('A_endOfSelectedArea', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('v', 'j', 'l'); helpers.doKeys('A'); helpers.assertCursorAt(1, 2); eq('vim-insert', cm.getOption('keyMap')); }, {value: 'foo\nbar'}); testVim('i', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('i'); helpers.assertCursorAt(0, 1); eq('vim-insert', cm.getOption('keyMap')); }); testVim('i_repeat', function(cm, vim, helpers) { helpers.doKeys('3', 'i'); cm.replaceRange('test', cm.getCursor()); helpers.doKeys(''); eq('testtesttest', cm.getValue()); helpers.assertCursorAt(0, 11); }, { value: '' }); testVim('i_repeat_delete', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('2', 'i'); cm.replaceRange('z', cm.getCursor()); helpers.doInsertModeKeys('Backspace', 'Backspace'); helpers.doKeys(''); eq('abe', cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: 'abcde' }); testVim('insert', function(cm, vim, helpers) { helpers.doKeys('i'); eq('vim-insert', cm.getOption('keyMap')); eq(false, cm.state.overwrite); helpers.doKeys(''); eq('vim-replace', cm.getOption('keyMap')); eq(true, cm.state.overwrite); helpers.doKeys(''); eq('vim-insert', cm.getOption('keyMap')); eq(false, cm.state.overwrite); }); testVim('i_backspace', function(cm, vim, helpers) { cm.setCursor(0, 10); helpers.doKeys('i'); helpers.doInsertModeKeys('Backspace'); helpers.assertCursorAt(0, 9); eq('012345678', cm.getValue()); }, { value: '0123456789'}); testVim('i_overwrite_backspace', function(cm, vim, helpers) { cm.setCursor(0, 10); helpers.doKeys('i'); helpers.doKeys(''); helpers.doInsertModeKeys('Backspace'); helpers.assertCursorAt(Pos(0, 9, "after")); eq('0123456789', cm.getValue()); }, { value: '0123456789'}); testVim('A', function(cm, vim, helpers) { helpers.doKeys('A'); helpers.assertCursorAt(0, lines[0].length); eq('vim-insert', cm.getOption('keyMap')); }); testVim('A_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('', '2', 'j', 'l', 'l', 'A'); var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' '); replacement.pop(); cm.replaceSelections(replacement); eq('testhello\nmehello\npleahellose', cm.getValue()); helpers.doKeys(''); cm.setCursor(0, 0); helpers.doKeys('.'); // TODO this doesn't work yet // eq('teshellothello\nme hello hello\nplehelloahellose', cm.getValue()); }, {value: 'test\nme\nplease'}); testVim('I', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('I'); helpers.assertCursorAt(0, lines[0].textStart); eq('vim-insert', cm.getOption('keyMap')); }); testVim('I_repeat', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('3', 'I'); cm.replaceRange('test', cm.getCursor()); helpers.doKeys(''); eq('testtesttestblah', cm.getValue()); helpers.assertCursorAt(0, 11); }, { value: 'blah' }); testVim('I_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('', '2', 'j', 'l', 'l', 'I'); var replacement = new Array(cm.listSelections().length+1).join('hello ').split(' '); replacement.pop(); cm.replaceSelections(replacement); eq('hellotest\nhellome\nhelloplease', cm.getValue()); }, {value: 'test\nme\nplease'}); testVim('o', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('o'); eq('word1\n\nword2', cm.getValue()); helpers.assertCursorAt(1, 0); eq('vim-insert', cm.getOption('keyMap')); }, { value: 'word1\nword2' }); testVim('o_repeat', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('3', 'o'); cm.replaceRange('test', cm.getCursor()); helpers.doKeys(''); eq('\ntest\ntest\ntest', cm.getValue()); helpers.assertCursorAt(3, 3); }, { value: '' }); testVim('O', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('O'); eq('\nword1\nword2', cm.getValue()); helpers.assertCursorAt(0, 0); eq('vim-insert', cm.getOption('keyMap')); }, { value: 'word1\nword2' }); testVim('J', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('J'); var expectedValue = 'word1 word2\nword3\n word4'; eq(expectedValue, cm.getValue()); helpers.assertCursorAt(0, expectedValue.indexOf('word2') - 1); }, { value: 'word1 \n word2\nword3\n word4' }); testVim('J_repeat', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('3', 'J'); var expectedValue = 'word1 word2 word3\n word4'; eq(expectedValue, cm.getValue()); helpers.assertCursorAt(0, expectedValue.indexOf('word3') - 1); }, { value: 'word1 \n word2\nword3\n word4' }); testVim('p', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false); helpers.doKeys('p'); eq('__abc\ndef_', cm.getValue()); helpers.assertCursorAt(1, 2); }, { value: '___' }); testVim('p_register', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().getRegister('a').setText('abc\ndef', false); helpers.doKeys('"', 'a', 'p'); eq('__abc\ndef_', cm.getValue()); helpers.assertCursorAt(1, 2); }, { value: '___' }); testVim('p_wrong_register', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().getRegister('a').setText('abc\ndef', false); helpers.doKeys('p'); eq('___', cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: '___' }); testVim('p_line', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true); helpers.doKeys('2', 'p'); eq('___\n a\nd\n a\nd', cm.getValue()); helpers.assertCursorAt(1, 2); }, { value: '___' }); testVim('p_lastline', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', ' a\nd', true); helpers.doKeys('2', 'p'); eq('___\n a\nd\n a\nd', cm.getValue()); helpers.assertCursorAt(1, 2); }, { value: '___' }); testVim(']p_first_indent_is_smaller', function(cm, vim, helpers) { helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); helpers.doKeys(']', 'p'); eq(' ___\n abc\n def', cm.getValue()); }, { value: ' ___' }); testVim(']p_first_indent_is_larger', function(cm, vim, helpers) { helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); helpers.doKeys(']', 'p'); eq(' ___\n abc\ndef', cm.getValue()); }, { value: ' ___' }); testVim(']p_with_tab_indents', function(cm, vim, helpers) { helpers.getRegisterController().pushText('"', 'yank', '\t\tabc\n\t\t\tdef\n', true); helpers.doKeys(']', 'p'); eq('\t___\n\tabc\n\t\tdef', cm.getValue()); }, { value: '\t___', indentWithTabs: true}); testVim(']p_with_spaces_translated_to_tabs', function(cm, vim, helpers) { helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); helpers.doKeys(']', 'p'); eq('\t___\n\tabc\n\t\tdef', cm.getValue()); }, { value: '\t___', indentWithTabs: true, tabSize: 2 }); testVim('[p', function(cm, vim, helpers) { helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true); helpers.doKeys('[', 'p'); eq(' abc\n def\n ___', cm.getValue()); }, { value: ' ___' }); testVim('P', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false); helpers.doKeys('P'); eq('_abc\ndef__', cm.getValue()); helpers.assertCursorAt(1, 3); }, { value: '___' }); testVim('P_line', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true); helpers.doKeys('2', 'P'); eq(' a\nd\n a\nd\n___', cm.getValue()); helpers.assertCursorAt(0, 2); }, { value: '___' }); testVim('r', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('3', 'r', 'u'); eq('wuuuet\nanother', cm.getValue(),'3r failed'); helpers.assertCursorAt(0, 3); cm.setCursor(0, 4); helpers.doKeys('v', 'j', 'h', 'r', ''); eq('wuuu \n her', cm.getValue(),'Replacing selection by space-characters failed'); cm.setValue("ox"); helpers.doKeys('r', ''); eq('ox', cm.getValue()); helpers.doKeys('r', ''); eq('ox', cm.getValue()); helpers.doKeys('r', ''); eq('\nx', cm.getValue()); }, { value: 'wordet\nanother' }); testVim('r_visual_block', function(cm, vim, helpers) { cm.setCursor(2, 3); helpers.doKeys('', 'k', 'k', 'h', 'h', 'r', 'l'); eq('1lll\n5lll\nalllefg', cm.getValue()); helpers.doKeys('', 'l', 'j', 'r', ''); eq('1 l\n5 l\nalllefg', cm.getValue()); cm.setCursor(2, 0); helpers.doKeys('o'); helpers.doKeys(''); cm.replaceRange('\t\t', cm.getCursor()); helpers.doKeys('', 'h', 'h', 'r', 'r'); eq('1 l\n5 l\nalllefg\nrrrrrrrr', cm.getValue()); }, {value: '1234\n5678\nabcdefg'}); testVim('R', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('R'); helpers.assertCursorAt(0, 1); eq('vim-replace', cm.getOption('keyMap')); is(cm.state.overwrite, 'Setting overwrite state failed'); }); testVim('mark', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys('`', 't'); helpers.assertCursorAt(2, 2); cm.setCursor(2, 0); cm.replaceRange(' h', cm.getCursor()); cm.setCursor(0, 0); helpers.doKeys('\'', 't'); helpers.assertCursorAt(2, 3); }); testVim('mark\'', function(cm, vim, helpers) { cm.setCursor(2, 2); cm.setCursor(0, 0); helpers.doKeys('`', '\''); helpers.assertCursorAt(2, 2); cm.setCursor(2, 0); cm.replaceRange(' h', cm.getCursor()); cm.setCursor(0, 0); helpers.doKeys('\'', '\''); helpers.assertCursorAt(2, 3); }); testVim('mark.', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('O', 'testing', ''); cm.setCursor(3, 3); helpers.doKeys('\'', '.'); helpers.assertCursorAt(0, 0); cm.setCursor(4, 4); helpers.doKeys('`', '.'); helpers.assertCursorAt(0, 6); }); testVim('jumpToMark_next', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys(']', '`'); helpers.assertCursorAt(2, 2); cm.setCursor(0, 0); helpers.doKeys(']', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_next_repeat', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 2); helpers.doKeys('m', 'b'); cm.setCursor(4, 2); helpers.doKeys('m', 'c'); cm.setCursor(0, 0); helpers.doKeys('2', ']', '`'); helpers.assertCursorAt(3, 2); cm.setCursor(0, 0); helpers.doKeys('2', ']', '\''); helpers.assertCursorAt(3, 1); }); testVim('jumpToMark_next_sameline', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('m', 'a'); cm.setCursor(2, 4); helpers.doKeys('m', 'b'); cm.setCursor(2, 2); helpers.doKeys(']', '`'); helpers.assertCursorAt(2, 4); }); testVim('jumpToMark_next_onlyprev', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('m', 'a'); cm.setCursor(4, 0); helpers.doKeys(']', '`'); helpers.assertCursorAt(4, 0); }); testVim('jumpToMark_next_nomark', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys(']', '`'); helpers.assertCursorAt(2, 2); helpers.doKeys(']', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_next_linewise_over', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 4); helpers.doKeys('m', 'b'); cm.setCursor(2, 1); helpers.doKeys(']', '\''); helpers.assertCursorAt(3, 1); }); testVim('jumpToMark_next_action', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys('d', ']', '`'); helpers.assertCursorAt(0, 0); var actual = cm.getLine(0); var expected = 'pop pop 0 1 2 3 4'; eq(actual, expected, "Deleting while jumping to the next mark failed."); }); testVim('jumpToMark_next_line_action', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(0, 0); helpers.doKeys('d', ']', '\''); helpers.assertCursorAt(0, 1); var actual = cm.getLine(0); var expected = ' (a) [b] {c} ' eq(actual, expected, "Deleting while jumping to the next mark line failed."); }); testVim('jumpToMark_prev', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 't'); cm.setCursor(4, 0); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 2); cm.setCursor(4, 0); helpers.doKeys('[', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_repeat', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 2); helpers.doKeys('m', 'b'); cm.setCursor(4, 2); helpers.doKeys('m', 'c'); cm.setCursor(5, 0); helpers.doKeys('2', '[', '`'); helpers.assertCursorAt(3, 2); cm.setCursor(5, 0); helpers.doKeys('2', '[', '\''); helpers.assertCursorAt(3, 1); }); testVim('jumpToMark_prev_sameline', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('m', 'a'); cm.setCursor(2, 4); helpers.doKeys('m', 'b'); cm.setCursor(2, 2); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_onlynext', function(cm, vim, helpers) { cm.setCursor(4, 4); helpers.doKeys('m', 'a'); cm.setCursor(2, 0); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_nomark', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('[', '`'); helpers.assertCursorAt(2, 2); helpers.doKeys('[', '\''); helpers.assertCursorAt(2, 0); }); testVim('jumpToMark_prev_linewise_over', function(cm, vim, helpers) { cm.setCursor(2, 2); helpers.doKeys('m', 'a'); cm.setCursor(3, 4); helpers.doKeys('m', 'b'); cm.setCursor(3, 6); helpers.doKeys('[', '\''); helpers.assertCursorAt(2, 0); }); testVim('delmark_single', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 't'); helpers.doEx('delmarks t'); cm.setCursor(0, 0); helpers.doKeys('`', 't'); helpers.assertCursorAt(0, 0); }); testVim('delmark_range', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks b-d'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'b'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'c'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'd'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'e'); helpers.assertCursorAt(5, 2); }); testVim('delmark_multi', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks bcd'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'b'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'c'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'd'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'e'); helpers.assertCursorAt(5, 2); }); testVim('delmark_multi_space', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks b c d'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'b'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'c'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'd'); helpers.assertCursorAt(1, 2); helpers.doKeys('`', 'e'); helpers.assertCursorAt(5, 2); }); testVim('delmark_all', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('m', 'a'); cm.setCursor(2, 2); helpers.doKeys('m', 'b'); cm.setCursor(3, 2); helpers.doKeys('m', 'c'); cm.setCursor(4, 2); helpers.doKeys('m', 'd'); cm.setCursor(5, 2); helpers.doKeys('m', 'e'); helpers.doEx('delmarks a b-de'); cm.setCursor(0, 0); helpers.doKeys('`', 'a'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'b'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'c'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'd'); helpers.assertCursorAt(0, 0); helpers.doKeys('`', 'e'); helpers.assertCursorAt(0, 0); }); testVim('visual', function(cm, vim, helpers) { helpers.doKeys('l', 'v', 'l', 'l'); helpers.assertCursorAt(0, 4); eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor')); helpers.doKeys('d'); eq('15', cm.getValue()); }, { value: '12345' }); testVim('visual_yank', function(cm, vim, helpers) { helpers.doKeys('v', '3', 'l', 'y'); helpers.assertCursorAt(0, 0); helpers.doKeys('p'); eq('aa te test for yank', cm.getValue()); }, { value: 'a test for yank' }) testVim('visual_w', function(cm, vim, helpers) { helpers.doKeys('v', 'w'); eq(cm.getSelection(), 'motion t'); }, { value: 'motion test'}); testVim('visual_initial_selection', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('v'); cm.getSelection('n'); }, { value: 'init'}); testVim('visual_crossover_left', function(cm, vim, helpers) { cm.setCursor(0, 2); helpers.doKeys('v', 'l', 'h', 'h'); cm.getSelection('ro'); }, { value: 'cross'}); testVim('visual_crossover_left', function(cm, vim, helpers) { cm.setCursor(0, 2); helpers.doKeys('v', 'h', 'l', 'l'); cm.getSelection('os'); }, { value: 'cross'}); testVim('visual_crossover_up', function(cm, vim, helpers) { cm.setCursor(3, 2); helpers.doKeys('v', 'j', 'k', 'k'); eqCursorPos(Pos(2, 2), cm.getCursor('head')); eqCursorPos(Pos(3, 3), cm.getCursor('anchor')); helpers.doKeys('k'); eqCursorPos(Pos(1, 2), cm.getCursor('head')); eqCursorPos(Pos(3, 3), cm.getCursor('anchor')); }, { value: 'cross\ncross\ncross\ncross\ncross\n'}); testVim('visual_crossover_down', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('v', 'k', 'j', 'j'); eqCursorPos(Pos(2, 3), cm.getCursor('head')); eqCursorPos(Pos(1, 2), cm.getCursor('anchor')); helpers.doKeys('j'); eqCursorPos(Pos(3, 3), cm.getCursor('head')); eqCursorPos(Pos(1, 2), cm.getCursor('anchor')); }, { value: 'cross\ncross\ncross\ncross\ncross\n'}); testVim('visual_exit', function(cm, vim, helpers) { helpers.doKeys('', 'l', 'j', 'j', ''); eqCursorPos(cm.getCursor('anchor'), cm.getCursor('head')); eq(vim.visualMode, false); }, { value: 'hello\nworld\nfoo' }); testVim('visual_line', function(cm, vim, helpers) { helpers.doKeys('l', 'V', 'l', 'j', 'j', 'd'); eq(' 4\n 5', cm.getValue()); }, { value: ' 1\n 2\n 3\n 4\n 5' }); testVim('visual_block_move_to_eol', function(cm, vim, helpers) { // moveToEol should move all block cursors to end of line cm.setCursor(0, 0); helpers.doKeys('', 'G', '$'); var selections = cm.getSelections().join(); eq('123,45,6', selections); // Checks that with cursor at Infinity, finding words backwards still works. helpers.doKeys('2', 'k', 'b'); selections = cm.getSelections().join(); eq('1', selections); }, {value: '123\n45\n6'}); testVim('visual_block_different_line_lengths', function(cm, vim, helpers) { // test the block selection with lines of different length // i.e. extending the selection // till the end of the longest line. helpers.doKeys('', 'l', 'j', 'j', '6', 'l', 'd'); helpers.doKeys('d', 'd', 'd', 'd'); eq('', cm.getValue()); }, {value: '1234\n5678\nabcdefg'}); testVim('visual_block_truncate_on_short_line', function(cm, vim, helpers) { // check for left side selection in case // of moving up to a shorter line. cm.replaceRange('', cm.getCursor()); cm.setCursor(3, 4); helpers.doKeys('', 'l', 'k', 'k', 'd'); eq('hello world\n{\ntis\nsa!', cm.getValue()); }, {value: 'hello world\n{\nthis is\nsparta!'}); testVim('visual_block_corners', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('', '2', 'l', 'k'); // circle around the anchor // and check the selections var selections = cm.getSelections(); eq('345891', selections.join('')); helpers.doKeys('4', 'h'); selections = cm.getSelections(); eq('123678', selections.join('')); helpers.doKeys('j', 'j'); selections = cm.getSelections(); eq('678abc', selections.join('')); helpers.doKeys('4', 'l'); selections = cm.getSelections(); eq('891cde', selections.join('')); }, {value: '12345\n67891\nabcde'}); testVim('visual_block_mode_switch', function(cm, vim, helpers) { // switch between visual modes cm.setCursor(1, 1); // blockwise to characterwise visual helpers.doKeys('', 'j', 'l', 'v'); var selections = cm.getSelections(); eq('7891\nabc', selections.join('')); // characterwise to blockwise helpers.doKeys(''); selections = cm.getSelections(); eq('78bc', selections.join('')); // blockwise to linewise visual helpers.doKeys('V'); selections = cm.getSelections(); eq('67891\nabcde', selections.join('')); }, {value: '12345\n67891\nabcde'}); testVim('visual_block_crossing_short_line', function(cm, vim, helpers) { // visual block with long and short lines cm.setCursor(0, 3); helpers.doKeys('', 'j', 'j', 'j'); var selections = cm.getSelections().join(); eq('4,,d,b', selections); helpers.doKeys('3', 'k'); selections = cm.getSelections().join(); eq('4', selections); helpers.doKeys('5', 'j', 'k'); selections = cm.getSelections().join(""); eq(10, selections.length); }, {value: '123456\n78\nabcdefg\nfoobar\n}\n'}); testVim('visual_block_curPos_on_exit', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('', '3' , 'l', ''); eqCursorPos(makeCursor(0, 3), cm.getCursor()); helpers.doKeys('h', '', '2' , 'j' ,'3' , 'l'); eq(cm.getSelections().join(), "3456,,cdef"); helpers.doKeys('4' , 'h'); eq(cm.getSelections().join(), "23,8,bc"); helpers.doKeys('2' , 'l'); eq(cm.getSelections().join(), "34,,cd"); }, {value: '123456\n78\nabcdefg\nfoobar'}); testVim('visual_marks', function(cm, vim, helpers) { helpers.doKeys('l', 'v', 'l', 'l', 'j', 'j', 'v'); // Test visual mode marks cm.setCursor(2, 1); helpers.doKeys('\'', '<'); helpers.assertCursorAt(0, 1); helpers.doKeys('\'', '>'); helpers.assertCursorAt(2, 0); }); testVim('visual_join', function(cm, vim, helpers) { helpers.doKeys('l', 'V', 'l', 'j', 'j', 'J'); eq(' 1 2 3\n 4\n 5', cm.getValue()); is(!vim.visualMode); }, { value: ' 1\n 2\n 3\n 4\n 5' }); testVim('visual_join_2', function(cm, vim, helpers) { helpers.doKeys('G', 'V', 'g', 'g', 'J'); eq('1 2 3 4 5 6 ', cm.getValue()); is(!vim.visualMode); }, { value: '1\n2\n3\n4\n5\n6\n'}); testVim('visual_blank', function(cm, vim, helpers) { helpers.doKeys('v', 'k'); eq(vim.visualMode, true); }, { value: '\n' }); testVim('reselect_visual', function(cm, vim, helpers) { helpers.doKeys('l', 'v', 'l', 'l', 'l', 'y', 'g', 'v'); helpers.assertCursorAt(0, 5); eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor')); helpers.doKeys('v'); cm.setCursor(1, 0); helpers.doKeys('v', 'l', 'l', 'p'); eq('123456\n2345\nbar', cm.getValue()); cm.setCursor(0, 0); helpers.doKeys('g', 'v'); // here the fake cursor is at (1, 3) helpers.assertCursorAt(1, 4); eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor')); helpers.doKeys('v'); cm.setCursor(2, 0); helpers.doKeys('v', 'l', 'l', 'g', 'v'); helpers.assertCursorAt(1, 4); eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor')); helpers.doKeys('g', 'v'); helpers.assertCursorAt(2, 3); eqCursorPos(makeCursor(2, 0), cm.getCursor('anchor')); eq('123456\n2345\nbar', cm.getValue()); }, { value: '123456\nfoo\nbar' }); testVim('reselect_visual_line', function(cm, vim, helpers) { helpers.doKeys('l', 'V', 'j', 'j', 'V', 'g', 'v', 'd'); eq('foo\nand\nbar', cm.getValue()); cm.setCursor(1, 0); helpers.doKeys('V', 'y', 'j'); helpers.doKeys('V', 'p' , 'g', 'v', 'd'); eq('foo\nand', cm.getValue()); }, { value: 'hello\nthis\nis\nfoo\nand\nbar' }); testVim('reselect_visual_block', function(cm, vim, helpers) { cm.setCursor(1, 2); helpers.doKeys('', 'k', 'h', ''); cm.setCursor(2, 1); helpers.doKeys('v', 'l', 'g', 'v'); eqCursorPos(Pos(1, 2), vim.sel.anchor); eqCursorPos(Pos(0, 1), vim.sel.head); // Ensure selection is done with visual block mode rather than one // continuous range. eq(cm.getSelections().join(''), '23oo') helpers.doKeys('g', 'v'); eqCursorPos(Pos(2, 1), vim.sel.anchor); eqCursorPos(Pos(2, 2), vim.sel.head); helpers.doKeys(''); // Ensure selection of deleted range cm.setCursor(1, 1); helpers.doKeys('v', '', 'j', 'd', 'g', 'v'); eq(cm.getSelections().join(''), 'or'); }, { value: '123456\nfoo\nbar' }); testVim('s_normal', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('s'); helpers.doKeys(''); eq('ac', cm.getValue()); }, { value: 'abc'}); testVim('s_visual', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('v', 's'); helpers.doKeys(''); helpers.assertCursorAt(0, 0); eq('ac', cm.getValue()); }, { value: 'abc'}); testVim('o_visual', function(cm, vim, helpers) { cm.setCursor(0,0); helpers.doKeys('v','l','l','l','o'); helpers.assertCursorAt(0,0); helpers.doKeys('v','v','j','j','j','o'); helpers.assertCursorAt(0,0); helpers.doKeys('O'); helpers.doKeys('l','l') helpers.assertCursorAt(3, 3); helpers.doKeys('d'); eq('p',cm.getValue()); }, { value: 'abcd\nefgh\nijkl\nmnop'}); testVim('o_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('','3','j','l','l', 'o'); eqCursorPos(Pos(3, 3), vim.sel.anchor); eqCursorPos(Pos(0, 1), vim.sel.head); helpers.doKeys('O'); eqCursorPos(Pos(3, 1), vim.sel.anchor); eqCursorPos(Pos(0, 3), vim.sel.head); helpers.doKeys('o'); eqCursorPos(Pos(0, 3), vim.sel.anchor); eqCursorPos(Pos(3, 1), vim.sel.head); }, { value: 'abcd\nefgh\nijkl\nmnop'}); testVim('changeCase_visual', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('v', 'l', 'l'); helpers.doKeys('U'); helpers.assertCursorAt(0, 0); helpers.doKeys('v', 'l', 'l'); helpers.doKeys('u'); helpers.assertCursorAt(0, 0); helpers.doKeys('l', 'l', 'l', '.'); helpers.assertCursorAt(0, 3); cm.setCursor(0, 0); helpers.doKeys('q', 'a', 'v', 'j', 'U', 'q'); helpers.assertCursorAt(0, 0); helpers.doKeys('j', '@', 'a'); helpers.assertCursorAt(1, 0); cm.setCursor(3, 0); helpers.doKeys('V', 'U', 'j', '.'); eq('ABCDEF\nGHIJKL\nMnopq\nSHORT LINE\nLONG LINE OF TEXT', cm.getValue()); }, { value: 'abcdef\nghijkl\nmnopq\nshort line\nlong line of text'}); testVim('changeCase_visual_block', function(cm, vim, helpers) { cm.setCursor(2, 1); helpers.doKeys('', 'k', 'k', 'h', 'U'); eq('ABcdef\nGHijkl\nMNopq\nfoo', cm.getValue()); cm.setCursor(0, 2); helpers.doKeys('.'); eq('ABCDef\nGHIJkl\nMNOPq\nfoo', cm.getValue()); // check when last line is shorter. cm.setCursor(2, 2); helpers.doKeys('.'); eq('ABCDef\nGHIJkl\nMNOPq\nfoO', cm.getValue()); }, { value: 'abcdef\nghijkl\nmnopq\nfoo'}); testVim('visual_paste', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('v', 'l', 'l', 'y'); helpers.assertCursorAt(0, 0); helpers.doKeys('3', 'l', 'j', 'v', 'l', 'p'); helpers.assertCursorAt(1, 5); eq('this is a\nunithitest for visual paste', cm.getValue()); cm.setCursor(0, 0); // in case of pasting whole line helpers.doKeys('y', 'y'); cm.setCursor(1, 6); helpers.doKeys('v', 'l', 'l', 'l', 'p'); helpers.assertCursorAt(2, 0); eq('this is a\nunithi\nthis is a\n for visual paste', cm.getValue()); }, { value: 'this is a\nunit test for visual paste'}); // This checks the contents of the register used to paste the text testVim('v_paste_from_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('"', 'a', 'y', 'w'); cm.setCursor(1, 0); helpers.doKeys('v', 'p'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+register/.test(text)); }); }, { value: 'register contents\nare not erased'}); testVim('S_normal', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('j', 'S'); helpers.doKeys(''); helpers.assertCursorAt(1, 1); eq('aa{\n \ncc', cm.getValue()); helpers.doKeys('j', 'S'); eq('aa{\n \n ', cm.getValue()); helpers.assertCursorAt(2, 2); helpers.doKeys(''); helpers.doKeys('d', 'd', 'd', 'd'); helpers.assertCursorAt(0, 0); helpers.doKeys('S'); is(vim.insertMode); eq('', cm.getValue()); }, { value: 'aa{\nbb\ncc'}); testVim('blockwise_paste', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('', '3', 'j', 'l', 'y'); cm.setCursor(0, 2); // paste one char after the current cursor position helpers.doKeys('p'); eq('helhelo\nworwold\nfoofo\nbarba', cm.getValue()); cm.setCursor(0, 0); helpers.doKeys('v', '4', 'l', 'y'); cm.setCursor(0, 0); helpers.doKeys('', '3', 'j', 'p'); eq('helheelhelo\norwold\noofo\narba', cm.getValue()); }, { value: 'hello\nworld\nfoo\nbar'}); testVim('blockwise_paste_long/short_line', function(cm, vim, helpers) { // extend short lines in case of different line lengths. cm.setCursor(0, 0); helpers.doKeys('', 'j', 'j', 'y'); cm.setCursor(0, 3); helpers.doKeys('p'); eq('hellho\nfoo f\nbar b', cm.getValue()); }, { value: 'hello\nfoo\nbar'}); testVim('blockwise_paste_cut_paste', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('', '2', 'j', 'x'); cm.setCursor(0, 0); helpers.doKeys('P'); eq('cut\nand\npaste\nme', cm.getValue()); }, { value: 'cut\nand\npaste\nme'}); testVim('blockwise_paste_from_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('', '2', 'j', '"', 'a', 'y'); cm.setCursor(0, 3); helpers.doKeys('"', 'a', 'p'); eq('foobfar\nhellho\nworlwd', cm.getValue()); }, { value: 'foobar\nhello\nworld'}); testVim('blockwise_paste_last_line', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('', '2', 'j', 'l', 'y'); cm.setCursor(3, 0); helpers.doKeys('p'); eq('cut\nand\npaste\nmcue\n an\n pa', cm.getValue()); }, { value: 'cut\nand\npaste\nme'}); testVim('S_visual', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('v', 'j', 'S'); helpers.doKeys(''); helpers.assertCursorAt(0, 0); eq('\ncc', cm.getValue()); }, { value: 'aa\nbb\ncc'}); testVim('d_/', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('match'); helpers.doKeys('2', 'd', '/'); helpers.assertCursorAt(0, 0); eq('match \n next', cm.getValue()); cm.openDialog = helpers.fakeOpenDialog('2'); helpers.doKeys('d', ':'); // TODO eq(' next', cm.getValue()); }, { value: 'text match match \n next' }); testVim('/ and n/N', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('match'); helpers.doKeys('/'); helpers.assertCursorAt(0, 11); helpers.doKeys('n'); helpers.assertCursorAt(1, 6); helpers.doKeys('N'); helpers.assertCursorAt(0, 11); cm.setCursor(0, 0); helpers.doKeys('2', '/'); helpers.assertCursorAt(1, 6); }, { value: 'match nope match \n nope Match' }); testVim('/_case', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('Match'); helpers.doKeys('/'); helpers.assertCursorAt(1, 6); }, { value: 'match nope match \n nope Match' }); testVim('/_2_pcre', function(cm, vim, helpers) { CodeMirror.Vim.setOption('pcre', true); cm.openDialog = helpers.fakeOpenDialog('(word){2}'); helpers.doKeys('/'); helpers.assertCursorAt(1, 9); helpers.doKeys('n'); helpers.assertCursorAt(2, 1); }, { value: 'word\n another wordword\n wordwordword\n' }); testVim('/_2_nopcre', function(cm, vim, helpers) { CodeMirror.Vim.setOption('pcre', false); cm.openDialog = helpers.fakeOpenDialog('\\(word\\)\\{2}'); helpers.doKeys('/'); helpers.assertCursorAt(1, 9); helpers.doKeys('n'); helpers.assertCursorAt(2, 1); }, { value: 'word\n another wordword\n wordwordword\n' }); testVim('/_nongreedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('aa'); helpers.doKeys('/'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('?_nongreedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('aa'); helpers.doKeys('?'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('/_greedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a+'); helpers.doKeys('/'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('?_greedy', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a+'); helpers.doKeys('?'); helpers.assertCursorAt(1, 3); helpers.doKeys('n'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa \n a aa'}); testVim('/_greedy_0_or_more', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a*'); helpers.doKeys('/'); helpers.assertCursorAt(0, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 4); helpers.doKeys('n'); helpers.assertCursorAt(0, 5); helpers.doKeys('n'); helpers.assertCursorAt(1, 0); helpers.doKeys('n'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa\n aa'}); testVim('?_greedy_0_or_more', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('a*'); helpers.doKeys('?'); helpers.assertCursorAt(1, 1); helpers.doKeys('n'); helpers.assertCursorAt(0, 5); helpers.doKeys('n'); helpers.assertCursorAt(0, 3); helpers.doKeys('n'); helpers.assertCursorAt(0, 0); }, { value: 'aaa aa\n aa'}); testVim('? and n/N', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('match'); helpers.doKeys('?'); helpers.assertCursorAt(1, 6); helpers.doKeys('n'); helpers.assertCursorAt(0, 11); helpers.doKeys('N'); helpers.assertCursorAt(1, 6); cm.setCursor(0, 0); helpers.doKeys('2', '?'); helpers.assertCursorAt(0, 11); }, { value: 'match nope match \n nope Match' }); testVim('*', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('*'); helpers.assertCursorAt(0, 22); cm.setCursor(0, 9); helpers.doKeys('2', '*'); helpers.assertCursorAt(1, 8); }, { value: 'nomatch match nomatch match \nnomatch Match' }); testVim('*_no_word', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('*'); helpers.assertCursorAt(0, 0); }, { value: ' \n match \n' }); testVim('*_symbol', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('*'); helpers.assertCursorAt(1, 0); }, { value: ' /}\n/} match \n' }); testVim('#', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('#'); helpers.assertCursorAt(1, 8); cm.setCursor(0, 9); helpers.doKeys('2', '#'); helpers.assertCursorAt(0, 22); }, { value: 'nomatch match nomatch match \nnomatch Match' }); testVim('*_seek', function(cm, vim, helpers) { // Should skip over space and symbols. cm.setCursor(0, 3); helpers.doKeys('*'); helpers.assertCursorAt(0, 22); }, { value: ' := match nomatch match \nnomatch Match' }); testVim('#', function(cm, vim, helpers) { // Should skip over space and symbols. cm.setCursor(0, 3); helpers.doKeys('#'); helpers.assertCursorAt(1, 8); }, { value: ' := match nomatch match \nnomatch Match' }); testVim('g*', function(cm, vim, helpers) { cm.setCursor(0, 8); helpers.doKeys('g', '*'); helpers.assertCursorAt(0, 18); cm.setCursor(0, 8); helpers.doKeys('3', 'g', '*'); helpers.assertCursorAt(1, 8); }, { value: 'matches match alsoMatch\nmatchme matching' }); testVim('g#', function(cm, vim, helpers) { cm.setCursor(0, 8); helpers.doKeys('g', '#'); helpers.assertCursorAt(0, 0); cm.setCursor(0, 8); helpers.doKeys('3', 'g', '#'); helpers.assertCursorAt(1, 0); }, { value: 'matches match alsoMatch\nmatchme matching' }); testVim('macro_insert', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'a', '0', 'i'); cm.replaceRange('foo', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('q', '@', 'a'); eq('foofoo', cm.getValue()); }, { value: ''}); testVim('macro_insert_repeat', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'a', '$', 'a'); cm.replaceRange('larry.', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('a'); cm.replaceRange('curly.', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('q'); helpers.doKeys('a'); cm.replaceRange('moe.', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('@', 'a'); // At this point, the most recent edit should be the 2nd insert change // inside the macro, i.e. "curly.". helpers.doKeys('.'); eq('larry.curly.moe.larry.curly.curly.', cm.getValue()); }, { value: ''}); testVim('macro_space', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('', ''); helpers.assertCursorAt(0, 2); helpers.doKeys('q', 'a', '', '', 'q'); helpers.assertCursorAt(0, 4); helpers.doKeys('@', 'a'); helpers.assertCursorAt(0, 6); helpers.doKeys('@', 'a'); helpers.assertCursorAt(0, 8); }, { value: 'one line of text.'}); testVim('macro_t_search', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'a', 't', 'e', 'q'); helpers.assertCursorAt(0, 1); helpers.doKeys('l', '@', 'a'); helpers.assertCursorAt(0, 6); helpers.doKeys('l', ';'); helpers.assertCursorAt(0, 12); }, { value: 'one line of text.'}); testVim('macro_f_search', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'b', 'f', 'e', 'q'); helpers.assertCursorAt(0, 2); helpers.doKeys('@', 'b'); helpers.assertCursorAt(0, 7); helpers.doKeys(';'); helpers.assertCursorAt(0, 13); }, { value: 'one line of text.'}); testVim('macro_slash_search', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'c'); cm.openDialog = helpers.fakeOpenDialog('e'); helpers.doKeys('/', 'q'); helpers.assertCursorAt(0, 2); helpers.doKeys('@', 'c'); helpers.assertCursorAt(0, 7); helpers.doKeys('n'); helpers.assertCursorAt(0, 13); }, { value: 'one line of text.'}); testVim('macro_multislash_search', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'd'); cm.openDialog = helpers.fakeOpenDialog('e'); helpers.doKeys('/'); cm.openDialog = helpers.fakeOpenDialog('t'); helpers.doKeys('/', 'q'); helpers.assertCursorAt(0, 12); helpers.doKeys('@', 'd'); helpers.assertCursorAt(0, 15); }, { value: 'one line of text to rule them all.'}); testVim('macro_last_ex_command_register', function (cm, vim, helpers) { cm.setCursor(0, 0); helpers.doEx('s/a/b'); helpers.doKeys('2', '@', ':'); eq('bbbaa', cm.getValue()); helpers.assertCursorAt(0, 2); }, { value: 'aaaaa'}); testVim('macro_parens', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'z', 'i'); cm.replaceRange('(', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('e', 'a'); cm.replaceRange(')', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('q'); helpers.doKeys('w', '@', 'z'); helpers.doKeys('w', '@', 'z'); eq('(see) (spot) (run)', cm.getValue()); }, { value: 'see spot run'}); testVim('macro_overwrite', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'z', '0', 'i'); cm.replaceRange('I ', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('q'); helpers.doKeys('e'); // Now replace the macro with something else. helpers.doKeys('q', 'z', 'a'); cm.replaceRange('.', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('q'); helpers.doKeys('e', '@', 'z'); helpers.doKeys('e', '@', 'z'); eq('I see. spot. run.', cm.getValue()); }, { value: 'see spot run'}); testVim('macro_search_f', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'a', 'f', ' '); helpers.assertCursorAt(0,3); helpers.doKeys('q', '0'); helpers.assertCursorAt(0,0); helpers.doKeys('@', 'a'); helpers.assertCursorAt(0,3); }, { value: 'The quick brown fox jumped over the lazy dog.'}); testVim('macro_search_2f', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'a', '2', 'f', ' '); helpers.assertCursorAt(0,9); helpers.doKeys('q', '0'); helpers.assertCursorAt(0,0); helpers.doKeys('@', 'a'); helpers.assertCursorAt(0,9); }, { value: 'The quick brown fox jumped over the lazy dog.'}); testVim('macro_yank_tick', function(cm, vim, helpers) { cm.setCursor(0, 0); // Start recording a macro into the \' register. helpers.doKeys('q', '\''); helpers.doKeys('y', '', '', '', '', 'p'); helpers.assertCursorAt(0,4); eq('the tex parrot', cm.getValue()); }, { value: 'the ex parrot'}); testVim('yank_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('"', 'a', 'y', 'y'); helpers.doKeys('j', '"', 'b', 'y', 'y'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+foo/.test(text)); is(/b\s+bar/.test(text)); }); helpers.doKeys(':'); }, { value: 'foo\nbar'}); testVim('yank_visual_block', function(cm, vim, helpers) { cm.setCursor(0, 1); helpers.doKeys('', 'l', 'j', '"', 'a', 'y'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+oo\nar/.test(text)); }); helpers.doKeys(':'); }, { value: 'foo\nbar'}); testVim('yank_append_line_to_line_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('"', 'a', 'y', 'y'); helpers.doKeys('j', '"', 'A', 'y', 'y'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+foo\nbar/.test(text)); is(/"\s+foo\nbar/.test(text)); }); helpers.doKeys(':'); }, { value: 'foo\nbar'}); testVim('yank_append_word_to_word_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('"', 'a', 'y', 'w'); helpers.doKeys('j', '"', 'A', 'y', 'w'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+foobar/.test(text)); is(/"\s+foobar/.test(text)); }); helpers.doKeys(':'); }, { value: 'foo\nbar'}); testVim('yank_append_line_to_word_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('"', 'a', 'y', 'w'); helpers.doKeys('j', '"', 'A', 'y', 'y'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+foo\nbar/.test(text)); is(/"\s+foo\nbar/.test(text)); }); helpers.doKeys(':'); }, { value: 'foo\nbar'}); testVim('yank_append_word_to_line_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('"', 'a', 'y', 'y'); helpers.doKeys('j', '"', 'A', 'y', 'w'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+foo\nbar/.test(text)); is(/"\s+foo\nbar/.test(text)); }); helpers.doKeys(':'); }, { value: 'foo\nbar'}); testVim('macro_register', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('q', 'a', 'i'); cm.replaceRange('gangnam', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('q'); helpers.doKeys('q', 'b', 'o'); cm.replaceRange('style', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('q'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/a\s+i/.test(text)); is(/b\s+o/.test(text)); }); helpers.doKeys(':'); }, { value: ''}); testVim('._register', function(cm,vim,helpers) { cm.setCursor(0,0); helpers.doKeys('i'); cm.replaceRange('foo',cm.getCursor()); helpers.doKeys(''); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/\.\s+foo/.test(text)); }); helpers.doKeys(':'); }, {value: ''}); testVim(':_register', function(cm,vim,helpers) { helpers.doEx('bar'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/:\s+bar/.test(text)); }); helpers.doKeys(':'); }, {value: ''}); testVim('search_register_escape', function(cm, vim, helpers) { // Check that the register is restored if the user escapes rather than confirms. cm.openDialog = helpers.fakeOpenDialog('waldo'); helpers.doKeys('/'); var onKeyDown; var onKeyUp; var KEYCODES = { f: 70, o: 79, Esc: 27 }; cm.openDialog = function(template, callback, options) { onKeyDown = options.onKeyDown; onKeyUp = options.onKeyUp; }; var close = function() {}; helpers.doKeys('/'); // Fake some keyboard events coming in. onKeyDown({keyCode: KEYCODES.f}, '', close); onKeyUp({keyCode: KEYCODES.f}, '', close); onKeyDown({keyCode: KEYCODES.o}, 'f', close); onKeyUp({keyCode: KEYCODES.o}, 'f', close); onKeyDown({keyCode: KEYCODES.o}, 'fo', close); onKeyUp({keyCode: KEYCODES.o}, 'fo', close); onKeyDown({keyCode: KEYCODES.Esc}, 'foo', close); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/waldo/.test(text)); is(!/foo/.test(text)); }); helpers.doKeys(':'); }, {value: ''}); testVim('search_register', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('foo'); helpers.doKeys('/'); cm.openDialog = helpers.fakeOpenDialog('registers'); cm.openNotification = helpers.fakeOpenNotification(function(text) { is(/\/\s+foo/.test(text)); }); helpers.doKeys(':'); }, {value: ''}); testVim('search_history', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('this'); helpers.doKeys('/'); cm.openDialog = helpers.fakeOpenDialog('checks'); helpers.doKeys('/'); cm.openDialog = helpers.fakeOpenDialog('search'); helpers.doKeys('/'); cm.openDialog = helpers.fakeOpenDialog('history'); helpers.doKeys('/'); cm.openDialog = helpers.fakeOpenDialog('checks'); helpers.doKeys('/'); var onKeyDown; var onKeyUp; var query = ''; var keyCodes = { Up: 38, Down: 40 }; cm.openDialog = function(template, callback, options) { onKeyUp = options.onKeyUp; onKeyDown = options.onKeyDown; }; var close = function(newVal) { if (typeof newVal == 'string') query = newVal; } helpers.doKeys('/'); onKeyDown({keyCode: keyCodes.Up}, query, close); onKeyUp({keyCode: keyCodes.Up}, query, close); eq(query, 'checks'); onKeyDown({keyCode: keyCodes.Up}, query, close); onKeyUp({keyCode: keyCodes.Up}, query, close); eq(query, 'history'); onKeyDown({keyCode: keyCodes.Up}, query, close); onKeyUp({keyCode: keyCodes.Up}, query, close); eq(query, 'search'); onKeyDown({keyCode: keyCodes.Up}, query, close); onKeyUp({keyCode: keyCodes.Up}, query, close); eq(query, 'this'); onKeyDown({keyCode: keyCodes.Down}, query, close); onKeyUp({keyCode: keyCodes.Down}, query, close); eq(query, 'search'); }, {value: ''}); testVim('exCommand_history', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('registers'); helpers.doKeys(':'); cm.openDialog = helpers.fakeOpenDialog('sort'); helpers.doKeys(':'); cm.openDialog = helpers.fakeOpenDialog('map'); helpers.doKeys(':'); cm.openDialog = helpers.fakeOpenDialog('invalid'); helpers.doKeys(':'); var onKeyDown; var onKeyUp; var input = ''; var keyCodes = { Up: 38, Down: 40, s: 115 }; cm.openDialog = function(template, callback, options) { onKeyUp = options.onKeyUp; onKeyDown = options.onKeyDown; }; var close = function(newVal) { if (typeof newVal == 'string') input = newVal; } helpers.doKeys(':'); onKeyDown({keyCode: keyCodes.Up}, input, close); eq(input, 'invalid'); onKeyDown({keyCode: keyCodes.Up}, input, close); eq(input, 'map'); onKeyDown({keyCode: keyCodes.Up}, input, close); eq(input, 'sort'); onKeyDown({keyCode: keyCodes.Up}, input, close); eq(input, 'registers'); onKeyDown({keyCode: keyCodes.s}, '', close); input = 's'; onKeyDown({keyCode: keyCodes.Up}, input, close); eq(input, 'sort'); }, {value: ''}); testVim('search_clear', function(cm, vim, helpers) { var onKeyDown; var input = ''; var keyCodes = { Ctrl: 17, u: 85 }; cm.openDialog = function(template, callback, options) { onKeyDown = options.onKeyDown; }; var close = function(newVal) { if (typeof newVal == 'string') input = newVal; } helpers.doKeys('/'); input = 'foo'; onKeyDown({keyCode: keyCodes.Ctrl}, input, close); onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close); eq(input, ''); }); testVim('exCommand_clear', function(cm, vim, helpers) { var onKeyDown; var input = ''; var keyCodes = { Ctrl: 17, u: 85 }; cm.openDialog = function(template, callback, options) { onKeyDown = options.onKeyDown; }; var close = function(newVal) { if (typeof newVal == 'string') input = newVal; } helpers.doKeys(':'); input = 'foo'; onKeyDown({keyCode: keyCodes.Ctrl}, input, close); onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close); eq(input, ''); }); testVim('.', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('2', 'd', 'w'); helpers.doKeys('.'); eq('5 6', cm.getValue()); }, { value: '1 2 3 4 5 6'}); testVim('._repeat', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('2', 'd', 'w'); helpers.doKeys('3', '.'); eq('6', cm.getValue()); }, { value: '1 2 3 4 5 6'}); testVim('._insert', function(cm, vim, helpers) { helpers.doKeys('i'); cm.replaceRange('test', cm.getCursor()); helpers.doKeys(''); helpers.doKeys('.'); eq('testestt', cm.getValue()); helpers.assertCursorAt(0, 6); helpers.doKeys('O'); cm.replaceRange('xyz', cm.getCursor()); helpers.doInsertModeKeys('Backspace'); helpers.doInsertModeKeys('Down'); helpers.doKeys(''); helpers.doKeys('.'); eq('xy\nxy\ntestestt', cm.getValue()); helpers.assertCursorAt(1, 1); }, { value: ''}); testVim('._insert_repeat', function(cm, vim, helpers) { helpers.doKeys('i'); cm.replaceRange('test', cm.getCursor()); cm.setCursor(0, 4); helpers.doKeys(''); helpers.doKeys('2', '.'); eq('testesttestt', cm.getValue()); helpers.assertCursorAt(0, 10); }, { value: ''}); testVim('._repeat_insert', function(cm, vim, helpers) { helpers.doKeys('3', 'i'); cm.replaceRange('te', cm.getCursor()); cm.setCursor(0, 2); helpers.doKeys(''); helpers.doKeys('.'); eq('tetettetetee', cm.getValue()); helpers.assertCursorAt(0, 10); }, { value: ''}); testVim('._insert_o', function(cm, vim, helpers) { helpers.doKeys('o'); cm.replaceRange('z', cm.getCursor()); cm.setCursor(1, 1); helpers.doKeys(''); helpers.doKeys('.'); eq('\nz\nz', cm.getValue()); helpers.assertCursorAt(2, 0); }, { value: ''}); testVim('._insert_o_repeat', function(cm, vim, helpers) { helpers.doKeys('o'); cm.replaceRange('z', cm.getCursor()); helpers.doKeys(''); cm.setCursor(1, 0); helpers.doKeys('2', '.'); eq('\nz\nz\nz', cm.getValue()); helpers.assertCursorAt(3, 0); }, { value: ''}); testVim('._insert_o_indent', function(cm, vim, helpers) { helpers.doKeys('o'); cm.replaceRange('z', cm.getCursor()); helpers.doKeys(''); cm.setCursor(1, 2); helpers.doKeys('.'); eq('{\n z\n z', cm.getValue()); helpers.assertCursorAt(2, 2); }, { value: '{'}); testVim('._insert_cw', function(cm, vim, helpers) { helpers.doKeys('c', 'w'); cm.replaceRange('test', cm.getCursor()); helpers.doKeys(''); cm.setCursor(0, 3); helpers.doKeys('2', 'l'); helpers.doKeys('.'); eq('test test word3', cm.getValue()); helpers.assertCursorAt(0, 8); }, { value: 'word1 word2 word3' }); testVim('._insert_cw_repeat', function(cm, vim, helpers) { // For some reason, repeat cw in desktop VIM will does not repeat insert mode // changes. Will conform to that behavior. helpers.doKeys('c', 'w'); cm.replaceRange('test', cm.getCursor()); helpers.doKeys(''); cm.setCursor(0, 4); helpers.doKeys('l'); helpers.doKeys('2', '.'); eq('test test', cm.getValue()); helpers.assertCursorAt(0, 8); }, { value: 'word1 word2 word3' }); testVim('._delete', function(cm, vim, helpers) { cm.setCursor(0, 5); helpers.doKeys('i'); helpers.doInsertModeKeys('Backspace'); helpers.doKeys(''); helpers.doKeys('.'); eq('zace', cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: 'zabcde'}); testVim('._delete_repeat', function(cm, vim, helpers) { cm.setCursor(0, 6); helpers.doKeys('i'); helpers.doInsertModeKeys('Backspace'); helpers.doKeys(''); helpers.doKeys('2', '.'); eq('zzce', cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: 'zzabcde'}); testVim('._visual_>', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('V', 'j', '>'); cm.setCursor(2, 0) helpers.doKeys('.'); eq(' 1\n 2\n 3\n 4', cm.getValue()); helpers.assertCursorAt(2, 2); }, { value: '1\n2\n3\n4'}); testVim('._replace_repeat', function(cm, vim, helpers) { helpers.doKeys('R'); cm.replaceRange('123', cm.getCursor(), offsetCursor(cm.getCursor(), 0, 3)); cm.setCursor(0, 3); helpers.doKeys(''); helpers.doKeys('2', '.'); eq('12123123\nabcdefg', cm.getValue()); helpers.assertCursorAt(0, 7); cm.setCursor(1, 0); helpers.doKeys('.'); eq('12123123\n123123g', cm.getValue()); helpers.doKeys('l', '"', '.', 'p'); eq('12123123\n123123g123', cm.getValue()); }, { value: 'abcdef\nabcdefg'}); testVim('f;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(9, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('F;', function(cm, vim, helpers) { cm.setCursor(0, 8); helpers.doKeys('F', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(2, cm.getCursor().ch); }, { value: '01x3xx6x8x'}); testVim('t;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(8, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('T;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', 'x'); helpers.doKeys(';'); helpers.doKeys('2', ';'); eq(2, cm.getCursor().ch); }, { value: '0xx3xx678x'}); testVim('f,', function(cm, vim, helpers) { cm.setCursor(0, 6); helpers.doKeys('f', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(2, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('F,', function(cm, vim, helpers) { cm.setCursor(0, 3); helpers.doKeys('F', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(9, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('t,', function(cm, vim, helpers) { cm.setCursor(0, 6); helpers.doKeys('t', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(3, cm.getCursor().ch); }, { value: '01x3xx678x'}); testVim('T,', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys('T', 'x'); helpers.doKeys(','); helpers.doKeys('2', ','); eq(8, cm.getCursor().ch); }, { value: '01x3xx67xx'}); testVim('fd,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', '4'); cm.setCursor(0, 0); helpers.doKeys('d', ';'); eq('56789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('d', ','); eq('01239', cm.getValue()); }, { value: '0123456789'}); testVim('Fd,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('F', '4'); cm.setCursor(0, 9); helpers.doKeys('d', ';'); eq('01239', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('d', ','); eq('56789', cm.getValue()); }, { value: '0123456789'}); testVim('td,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', '4'); cm.setCursor(0, 0); helpers.doKeys('d', ';'); eq('456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('d', ','); eq('012349', cm.getValue()); }, { value: '0123456789'}); testVim('Td,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', '4'); cm.setCursor(0, 9); helpers.doKeys('d', ';'); eq('012349', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('d', ','); eq('456789', cm.getValue()); }, { value: '0123456789'}); testVim('fc,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', '4'); cm.setCursor(0, 0); helpers.doKeys('c', ';', ''); eq('56789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('c', ','); eq('01239', cm.getValue()); }, { value: '0123456789'}); testVim('Fc,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('F', '4'); cm.setCursor(0, 9); helpers.doKeys('c', ';', ''); eq('01239', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('c', ','); eq('56789', cm.getValue()); }, { value: '0123456789'}); testVim('tc,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', '4'); cm.setCursor(0, 0); helpers.doKeys('c', ';', ''); eq('456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('c', ','); eq('012349', cm.getValue()); }, { value: '0123456789'}); testVim('Tc,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', '4'); cm.setCursor(0, 9); helpers.doKeys('c', ';', ''); eq('012349', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('c', ','); eq('456789', cm.getValue()); }, { value: '0123456789'}); testVim('fy,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('f', '4'); cm.setCursor(0, 0); helpers.doKeys('y', ';', 'P'); eq('012340123456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('y', ',', 'P'); eq('012345678456789', cm.getValue()); }, { value: '0123456789'}); testVim('Fy,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('F', '4'); cm.setCursor(0, 9); helpers.doKeys('y', ';', 'p'); eq('012345678945678', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('y', ',', 'P'); eq('012340123456789', cm.getValue()); }, { value: '0123456789'}); testVim('ty,;', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys('t', '4'); cm.setCursor(0, 0); helpers.doKeys('y', ';', 'P'); eq('01230123456789', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 9); helpers.doKeys('y', ',', 'p'); eq('01234567895678', cm.getValue()); }, { value: '0123456789'}); testVim('Ty,;', function(cm, vim, helpers) { cm.setCursor(0, 9); helpers.doKeys('T', '4'); cm.setCursor(0, 9); helpers.doKeys('y', ';', 'p'); eq('01234567895678', cm.getValue()); helpers.doKeys('u'); cm.setCursor(0, 0); helpers.doKeys('y', ',', 'P'); eq('01230123456789', cm.getValue()); }, { value: '0123456789'}); testVim('HML', function(cm, vim, helpers) { var lines = 35; var textHeight = cm.defaultTextHeight(); cm.setSize(600, lines*textHeight); cm.setCursor(120, 0); helpers.doKeys('H'); helpers.assertCursorAt(86, 2); helpers.doKeys('L'); helpers.assertCursorAt(120, 4); helpers.doKeys('M'); helpers.assertCursorAt(103,4); }, { value: (function(){ var lines = new Array(100); var upper = ' xx\n'; var lower = ' xx\n'; upper = lines.join(upper); lower = lines.join(lower); return upper + lower; })()}); var zVals = []; forEach(['zb','zz','zt','z-','z.','z'], function(e, idx){ var lineNum = 250; var lines = 35; testVim(e, function(cm, vim, helpers) { var k1 = e[0]; var k2 = e.substring(1); var textHeight = cm.defaultTextHeight(); cm.setSize(600, lines*textHeight); cm.setCursor(lineNum, 0); helpers.doKeys(k1, k2); zVals[idx] = cm.getScrollInfo().top; }, { value: (function(){ return new Array(500).join('\n'); })()}); }); testVim('zb_to_bottom', function(cm, vim, helpers){ var lineNum = 250; cm.setSize(600, 35*cm.defaultTextHeight()); cm.setCursor(lineNum, 0); helpers.doKeys('z', 'b'); var scrollInfo = cm.getScrollInfo(); eq(scrollInfo.top + scrollInfo.clientHeight, cm.charCoords(Pos(lineNum, 0), 'local').bottom); }, { value: (function(){ return new Array(500).join('\n'); })()}); testVim('zt_to_top', function(cm, vim, helpers){ var lineNum = 250; cm.setSize(600, 35*cm.defaultTextHeight()); cm.setCursor(lineNum, 0); helpers.doKeys('z', 't'); eq(cm.getScrollInfo().top, cm.charCoords(Pos(lineNum, 0), 'local').top); }, { value: (function(){ return new Array(500).join('\n'); })()}); testVim('zb', function(cm, vim, helpers){ eq(zVals[2], zVals[5]); }); var moveTillCharacterSandbox = 'The quick brown fox \n'; testVim('moveTillCharacter', function(cm, vim, helpers){ cm.setCursor(0, 0); // Search for the 'q'. cm.openDialog = helpers.fakeOpenDialog('q'); helpers.doKeys('/'); eq(4, cm.getCursor().ch); // Jump to just before the first o in the list. helpers.doKeys('t'); helpers.doKeys('o'); eq('The quick brown fox \n', cm.getValue()); // Delete that one character. helpers.doKeys('d'); helpers.doKeys('t'); helpers.doKeys('o'); eq('The quick bown fox \n', cm.getValue()); // Delete everything until the next 'o'. helpers.doKeys('.'); eq('The quick box \n', cm.getValue()); // An unmatched character should have no effect. helpers.doKeys('d'); helpers.doKeys('t'); helpers.doKeys('q'); eq('The quick box \n', cm.getValue()); // Matches should only be possible on single lines. helpers.doKeys('d'); helpers.doKeys('t'); helpers.doKeys('z'); eq('The quick box \n', cm.getValue()); // After all that, the search for 'q' should still be active, so the 'N' command // can run it again in reverse. Use that to delete everything back to the 'q'. helpers.doKeys('d'); helpers.doKeys('N'); eq('The ox \n', cm.getValue()); eq(4, cm.getCursor().ch); }, { value: moveTillCharacterSandbox}); testVim('searchForPipe', function(cm, vim, helpers){ CodeMirror.Vim.setOption('pcre', false); cm.setCursor(0, 0); // Search for the '|'. cm.openDialog = helpers.fakeOpenDialog('|'); helpers.doKeys('/'); eq(4, cm.getCursor().ch); }, { value: 'this|that'}); var 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'; testVim('scrollMotion', function(cm, vim, helpers){ var prevCursor, prevScrollInfo; cm.setCursor(0, 0); // ctrl-y at the top of the file should have no effect. helpers.doKeys(''); eq(0, cm.getCursor().line); prevScrollInfo = cm.getScrollInfo(); helpers.doKeys(''); eq(1, cm.getCursor().line); is(prevScrollInfo.top < cm.getScrollInfo().top); // Jump to the end of the sandbox. cm.setCursor(1000, 0); prevCursor = cm.getCursor(); // ctrl-e at the bottom of the file should have no effect. helpers.doKeys(''); eq(prevCursor.line, cm.getCursor().line); prevScrollInfo = cm.getScrollInfo(); helpers.doKeys(''); eq(prevCursor.line - 1, cm.getCursor().line, "Y"); is(prevScrollInfo.top > cm.getScrollInfo().top); }, { value: scrollMotionSandbox}); var squareBracketMotionSandbox = ''+ '({\n'+//0 ' ({\n'+//11 ' /*comment {\n'+//2 ' */(\n'+//3 '#else \n'+//4 ' /* )\n'+//5 '#if }\n'+//6 ' )}*/\n'+//7 ')}\n'+//8 '{}\n'+//9 '#else {{\n'+//10 '{}\n'+//11 '}\n'+//12 '{\n'+//13 '#endif\n'+//14 '}\n'+//15 '}\n'+//16 '#else';//17 testVim('[[, ]]', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(']', ']'); helpers.assertCursorAt(9,0); helpers.doKeys('2', ']', ']'); helpers.assertCursorAt(13,0); helpers.doKeys(']', ']'); helpers.assertCursorAt(17,0); helpers.doKeys('[', '['); helpers.assertCursorAt(13,0); helpers.doKeys('2', '[', '['); helpers.assertCursorAt(9,0); helpers.doKeys('[', '['); helpers.assertCursorAt(0,0); }, { value: squareBracketMotionSandbox}); testVim('[], ][', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doKeys(']', '['); helpers.assertCursorAt(12,0); helpers.doKeys('2', ']', '['); helpers.assertCursorAt(16,0); helpers.doKeys(']', '['); helpers.assertCursorAt(17,0); helpers.doKeys('[', ']'); helpers.assertCursorAt(16,0); helpers.doKeys('2', '[', ']'); helpers.assertCursorAt(12,0); helpers.doKeys('[', ']'); helpers.assertCursorAt(0,0); }, { value: squareBracketMotionSandbox}); testVim('[{, ]}', function(cm, vim, helpers) { cm.setCursor(4, 10); helpers.doKeys('[', '{'); helpers.assertCursorAt(2,12); helpers.doKeys('2', '[', '{'); helpers.assertCursorAt(0,1); cm.setCursor(4, 10); helpers.doKeys(']', '}'); helpers.assertCursorAt(6,11); helpers.doKeys('2', ']', '}'); helpers.assertCursorAt(8,1); cm.setCursor(0,1); helpers.doKeys(']', '}'); helpers.assertCursorAt(8,1); helpers.doKeys('[', '{'); helpers.assertCursorAt(0,1); }, { value: squareBracketMotionSandbox}); testVim('[(, ])', function(cm, vim, helpers) { cm.setCursor(4, 10); helpers.doKeys('[', '('); helpers.assertCursorAt(3,14); helpers.doKeys('2', '[', '('); helpers.assertCursorAt(0,0); cm.setCursor(4, 10); helpers.doKeys(']', ')'); helpers.assertCursorAt(5,11); helpers.doKeys('2', ']', ')'); helpers.assertCursorAt(8,0); helpers.doKeys('[', '('); helpers.assertCursorAt(0,0); helpers.doKeys(']', ')'); helpers.assertCursorAt(8,0); }, { value: squareBracketMotionSandbox}); testVim('[*, ]*, [/, ]/', function(cm, vim, helpers) { forEach(['*', '/'], function(key){ cm.setCursor(7, 0); helpers.doKeys('2', '[', key); helpers.assertCursorAt(2,2); helpers.doKeys('2', ']', key); helpers.assertCursorAt(7,5); }); }, { value: squareBracketMotionSandbox}); testVim('[#, ]#', function(cm, vim, helpers) { cm.setCursor(10, 3); helpers.doKeys('2', '[', '#'); helpers.assertCursorAt(4,0); helpers.doKeys('5', ']', '#'); helpers.assertCursorAt(17,0); cm.setCursor(10, 3); helpers.doKeys(']', '#'); helpers.assertCursorAt(14,0); }, { value: squareBracketMotionSandbox}); testVim('[m, ]m, [M, ]M', function(cm, vim, helpers) { cm.setCursor(11, 0); helpers.doKeys('[', 'm'); helpers.assertCursorAt(10,7); helpers.doKeys('4', '[', 'm'); helpers.assertCursorAt(1,3); helpers.doKeys('5', ']', 'm'); helpers.assertCursorAt(11,0); helpers.doKeys('[', 'M'); helpers.assertCursorAt(9,1); helpers.doKeys('3', ']', 'M'); helpers.assertCursorAt(15,0); helpers.doKeys('5', '[', 'M'); helpers.assertCursorAt(7,3); }, { value: squareBracketMotionSandbox}); testVim('i_indent_right', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedValue = ' word1\nword2\nword3 '; helpers.doKeys('i', ''); eq(expectedValue, cm.getValue()); helpers.assertCursorAt(0, 5); }, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); testVim('i_indent_left', function(cm, vim, helpers) { cm.setCursor(0, 3); var expectedValue = ' word1\nword2\nword3 '; helpers.doKeys('i', ''); eq(expectedValue, cm.getValue()); helpers.assertCursorAt(0, 1); }, { value: ' word1\nword2\nword3 ', indentUnit: 2 }); // Ex mode tests testVim('ex_go_to_line', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doEx('4'); helpers.assertCursorAt(3, 0); }, { value: 'a\nb\nc\nd\ne\n'}); testVim('ex_go_to_mark', function(cm, vim, helpers) { cm.setCursor(3, 0); helpers.doKeys('m', 'a'); cm.setCursor(0, 0); helpers.doEx('\'a'); helpers.assertCursorAt(3, 0); }, { value: 'a\nb\nc\nd\ne\n'}); testVim('ex_go_to_line_offset', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doEx('+3'); helpers.assertCursorAt(3, 0); helpers.doEx('-1'); helpers.assertCursorAt(2, 0); helpers.doEx('.2'); helpers.assertCursorAt(4, 0); helpers.doEx('.-3'); helpers.assertCursorAt(1, 0); }, { value: 'a\nb\nc\nd\ne\n'}); testVim('ex_go_to_mark_offset', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('m', 'a'); cm.setCursor(0, 0); helpers.doEx('\'a1'); helpers.assertCursorAt(3, 0); helpers.doEx('\'a-1'); helpers.assertCursorAt(1, 0); helpers.doEx('\'a+2'); helpers.assertCursorAt(4, 0); }, { value: 'a\nb\nc\nd\ne\n'}); testVim('ex_write', function(cm, vim, helpers) { var tmp = CodeMirror.commands.save; var written; var actualCm; CodeMirror.commands.save = function(cm) { written = true; actualCm = cm; }; // Test that w, wr, wri ... write all trigger :write. var command = 'write'; for (var i = 1; i < command.length; i++) { written = false; actualCm = null; helpers.doEx(command.substring(0, i)); eq(written, true); eq(actualCm, cm); } CodeMirror.commands.save = tmp; }); testVim('ex_sort', function(cm, vim, helpers) { helpers.doEx('sort'); eq('Z\na\nb\nc\nd', cm.getValue()); }, { value: 'b\nZ\nd\nc\na'}); testVim('ex_sort_reverse', function(cm, vim, helpers) { helpers.doEx('sort!'); eq('d\nc\nb\na', cm.getValue()); }, { value: 'b\nd\nc\na'}); testVim('ex_sort_range', function(cm, vim, helpers) { helpers.doEx('2,3sort'); eq('b\nc\nd\na', cm.getValue()); }, { value: 'b\nd\nc\na'}); testVim('ex_sort_oneline', function(cm, vim, helpers) { helpers.doEx('2sort'); // Expect no change. eq('b\nd\nc\na', cm.getValue()); }, { value: 'b\nd\nc\na'}); testVim('ex_sort_ignoreCase', function(cm, vim, helpers) { helpers.doEx('sort i'); eq('a\nb\nc\nd\nZ', cm.getValue()); }, { value: 'b\nZ\nd\nc\na'}); testVim('ex_sort_unique', function(cm, vim, helpers) { helpers.doEx('sort u'); eq('Z\na\nb\nc\nd', cm.getValue()); }, { value: 'b\nZ\na\na\nd\na\nc\na'}); testVim('ex_sort_decimal', function(cm, vim, helpers) { helpers.doEx('sort d'); eq('d3\n s5\n6\n.9', cm.getValue()); }, { value: '6\nd3\n s5\n.9'}); testVim('ex_sort_decimal_negative', function(cm, vim, helpers) { helpers.doEx('sort d'); eq('z-9\nd3\n s5\n6\n.9', cm.getValue()); }, { value: '6\nd3\n s5\n.9\nz-9'}); testVim('ex_sort_decimal_reverse', function(cm, vim, helpers) { helpers.doEx('sort! d'); eq('.9\n6\n s5\nd3', cm.getValue()); }, { value: '6\nd3\n s5\n.9'}); testVim('ex_sort_hex', function(cm, vim, helpers) { helpers.doEx('sort x'); eq(' s5\n6\n.9\n&0xB\nd3', cm.getValue()); }, { value: '6\nd3\n s5\n&0xB\n.9'}); testVim('ex_sort_octal', function(cm, vim, helpers) { helpers.doEx('sort o'); eq('.9\n.8\nd3\n s5\n6', cm.getValue()); }, { value: '6\nd3\n s5\n.9\n.8'}); testVim('ex_sort_decimal_mixed', function(cm, vim, helpers) { helpers.doEx('sort d'); eq('z\ny\nc1\nb2\na3', cm.getValue()); }, { value: 'a3\nz\nc1\ny\nb2'}); testVim('ex_sort_decimal_mixed_reverse', function(cm, vim, helpers) { helpers.doEx('sort! d'); eq('a3\nb2\nc1\nz\ny', cm.getValue()); }, { value: 'a3\nz\nc1\ny\nb2'}); testVim('ex_sort_pattern_alpha', function(cm, vim, helpers) { helpers.doEx('sort /[a-z]/'); eq('a3\nb2\nc1\ny\nz', cm.getValue()); }, { value: 'z\ny\nc1\nb2\na3'}); testVim('ex_sort_pattern_alpha_reverse', function(cm, vim, helpers) { helpers.doEx('sort! /[a-z]/'); eq('z\ny\nc1\nb2\na3', cm.getValue()); }, { value: 'z\ny\nc1\nb2\na3'}); testVim('ex_sort_pattern_alpha_ignoreCase', function(cm, vim, helpers) { helpers.doEx('sort i/[a-z]/'); eq('a3\nb2\nC1\nY\nz', cm.getValue()); }, { value: 'z\nY\nC1\nb2\na3'}); testVim('ex_sort_pattern_alpha_longer', function(cm, vim, helpers) { helpers.doEx('sort /[a-z]+/'); eq('a\naa\nab\nade\nadele\nadelle\nadriana\nalex\nalexandra\nb\nc\ny\nz', cm.getValue()); }, { value: 'z\nab\naa\nade\nadelle\nalexandra\nalex\nadriana\nadele\ny\nc\nb\na'}); testVim('ex_sort_pattern_alpha_only', function(cm, vim, helpers) { helpers.doEx('sort /^[a-z]$/'); eq('z1\ny2\na3\nb\nc', cm.getValue()); }, { value: 'z1\ny2\na3\nc\nb'}); testVim('ex_sort_pattern_alpha_only_reverse', function(cm, vim, helpers) { helpers.doEx('sort! /^[a-z]$/'); eq('c\nb\nz1\ny2\na3', cm.getValue()); }, { value: 'z1\ny2\na3\nc\nb'}); testVim('ex_sort_pattern_alpha_num', function(cm, vim, helpers) { helpers.doEx('sort /[a-z][0-9]/'); eq('c\nb\na3\ny2\nz1', cm.getValue()); }, { value: 'z1\ny2\na3\nc\nb'}); // test for :global command testVim('ex_global', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doEx('g/one/s//two'); eq('two two\n two two\n two two', cm.getValue()); helpers.doEx('1,2g/two/s//one'); eq('one one\n one one\n two two', cm.getValue()); }, {value: 'one one\n one one\n one one'}); testVim('ex_global_confirm', function(cm, vim, helpers) { cm.setCursor(0, 0); var onKeyDown; var openDialogSave = cm.openDialog; var KEYCODES = { a: 65, n: 78, q: 81, y: 89 }; // Intercept the ex command, 'global' cm.openDialog = function(template, callback, options) { // Intercept the prompt for the embedded ex command, 'substitute' cm.openDialog = function(template, callback, options) { onKeyDown = options.onKeyDown; }; callback('g/one/s//two/gc'); }; helpers.doKeys(':'); var close = function() {}; onKeyDown({keyCode: KEYCODES.n}, '', close); onKeyDown({keyCode: KEYCODES.y}, '', close); onKeyDown({keyCode: KEYCODES.a}, '', close); onKeyDown({keyCode: KEYCODES.q}, '', close); onKeyDown({keyCode: KEYCODES.y}, '', close); eq('one two\n two two\n one one\n two one\n one one', cm.getValue()); }, {value: 'one one\n one one\n one one\n one one\n one one'}); // Basic substitute tests. testVim('ex_substitute_same_line', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doEx('s/one/two/g'); eq('one one\n two two', cm.getValue()); }, { value: 'one one\n one one'}); testVim('ex_substitute_alternate_separator', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doEx('s#o/e#two#g'); eq('o/e o/e\n two two', cm.getValue()); }, { value: 'o/e o/e\n o/e o/e'}); testVim('ex_substitute_full_file', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doEx('%s/one/two/g'); eq('two two\n two two', cm.getValue()); }, { value: 'one one\n one one'}); testVim('ex_substitute_input_range', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doEx('1,3s/\\d/0/g'); eq('0\n0\n0\n4', cm.getValue()); }, { value: '1\n2\n3\n4' }); testVim('ex_substitute_range_current_to_input', function(cm, vim, helpers) { cm.setCursor(1, 0); helpers.doEx('.,3s/\\d/0/g'); eq('1\n0\n0\n4', cm.getValue()); }, { value: '1\n2\n3\n4' }); testVim('ex_substitute_range_input_to_current', function(cm, vim, helpers) { cm.setCursor(3, 0); helpers.doEx('2,.s/\\d/0/g'); eq('1\n0\n0\n0\n5', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_range_offset', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doEx('-1,+1s/\\d/0/g'); eq('1\n0\n0\n0\n5', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_range_implicit_offset', function(cm, vim, helpers) { cm.setCursor(0, 0); helpers.doEx('.1,.3s/\\d/0/g'); eq('1\n0\n0\n0\n5', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_to_eof', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doEx('.,$s/\\d/0/g'); eq('1\n2\n0\n0\n0', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_to_relative_eof', function(cm, vim, helpers) { cm.setCursor(4, 0); helpers.doEx('2,$-2s/\\d/0/g'); eq('1\n0\n0\n4\n5', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_range_mark', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('ma'); cm.setCursor(0, 0); helpers.doEx('.,\'as/\\d/0/g'); eq('0\n0\n0\n4\n5', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_range_mark_offset', function(cm, vim, helpers) { cm.setCursor(2, 0); helpers.doKeys('ma'); cm.setCursor(0, 0); helpers.doEx('\'a-1,\'a+1s/\\d/0/g'); eq('1\n0\n0\n0\n5', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_visual_range', function(cm, vim, helpers) { cm.setCursor(1, 0); // Set last visual mode selection marks '< and '> at lines 2 and 4 helpers.doKeys('V', '2', 'j', 'v'); helpers.doEx('\'<,\'>s/\\d/0/g'); eq('1\n0\n0\n0\n5', cm.getValue()); }, { value: '1\n2\n3\n4\n5' }); testVim('ex_substitute_empty_query', function(cm, vim, helpers) { // If the query is empty, use last query. cm.setCursor(1, 0); cm.openDialog = helpers.fakeOpenDialog('1'); helpers.doKeys('/'); helpers.doEx('s//b/g'); eq('abb ab2 ab3', cm.getValue()); }, { value: 'a11 a12 a13' }); testVim('ex_substitute_javascript', function(cm, vim, helpers) { CodeMirror.Vim.setOption('pcre', false); cm.setCursor(1, 0); // Throw all the things that javascript likes to treat as special values // into the replace part. All should be literal (this is VIM). helpers.doEx('s/\\(\\d+\\)/$$ $\' $` $& \\1/g') eq('a $$ $\' $` $& 0 b', cm.getValue()); }, { value: 'a 0 b' }); testVim('ex_substitute_empty_arguments', function(cm,vim,helpers) { cm.setCursor(0, 0); helpers.doEx('s/a/b/g'); cm.setCursor(1, 0); helpers.doEx('s'); eq('b b\nb a', cm.getValue()); }, {value: 'a a\na a'}); // More complex substitute tests that test both pcre and nopcre options. function testSubstitute(name, options) { testVim(name + '_pcre', function(cm, vim, helpers) { cm.setCursor(1, 0); CodeMirror.Vim.setOption('pcre', true); helpers.doEx(options.expr); eq(options.expectedValue, cm.getValue()); }, options); // If no noPcreExpr is defined, assume that it's the same as the expr. var noPcreExpr = options.noPcreExpr ? options.noPcreExpr : options.expr; testVim(name + '_nopcre', function(cm, vim, helpers) { cm.setCursor(1, 0); CodeMirror.Vim.setOption('pcre', false); helpers.doEx(noPcreExpr); eq(options.expectedValue, cm.getValue()); }, options); } testSubstitute('ex_substitute_capture', { value: 'a11 a12 a13', expectedValue: 'a1111 a1212 a1313', // $n is a backreference expr: 's/(\\d+)/$1$1/g', // \n is a backreference. noPcreExpr: 's/\\(\\d+\\)/\\1\\1/g'}); testSubstitute('ex_substitute_capture2', { value: 'a 0 b', expectedValue: 'a $00 b', expr: 's/(\\d+)/$$$1$1/g', noPcreExpr: 's/\\(\\d+\\)/$\\1\\1/g'}); testSubstitute('ex_substitute_nocapture', { value: 'a11 a12 a13', expectedValue: 'a$1$1 a$1$1 a$1$1', expr: 's/(\\d+)/$$1$$1/g', noPcreExpr: 's/\\(\\d+\\)/$1$1/g'}); testSubstitute('ex_substitute_nocapture2', { value: 'a 0 b', expectedValue: 'a $10 b', expr: 's/(\\d+)/$$1$1/g', noPcreExpr: 's/\\(\\d+\\)/\\$1\\1/g'}); testSubstitute('ex_substitute_nocapture', { value: 'a b c', expectedValue: 'a $ c', expr: 's/b/$$/', noPcreExpr: 's/b/$/'}); testSubstitute('ex_substitute_slash_regex', { value: 'one/two \n three/four', expectedValue: 'one|two \n three|four', expr: '%s/\\//|'}); testSubstitute('ex_substitute_pipe_regex', { value: 'one|two \n three|four', expectedValue: 'one,two \n three,four', expr: '%s/\\|/,/', noPcreExpr: '%s/|/,/'}); testSubstitute('ex_substitute_or_regex', { value: 'one|two \n three|four', expectedValue: 'ana|twa \n thraa|faar', expr: '%s/o|e|u/a/g', noPcreExpr: '%s/o\\|e\\|u/a/g'}); testSubstitute('ex_substitute_or_word_regex', { value: 'one|two \n three|four', expectedValue: 'five|five \n three|four', expr: '%s/(one|two)/five/g', noPcreExpr: '%s/\\(one\\|two\\)/five/g'}); testSubstitute('ex_substitute_backslashslash_regex', { value: 'one\\two \n three\\four', expectedValue: 'one,two \n three,four', expr: '%s/\\\\/,'}); testSubstitute('ex_substitute_slash_replacement', { value: 'one,two \n three,four', expectedValue: 'one/two \n three/four', expr: '%s/,/\\/'}); testSubstitute('ex_substitute_backslash_replacement', { value: 'one,two \n three,four', expectedValue: 'one\\two \n three\\four', expr: '%s/,/\\\\/g'}); testSubstitute('ex_substitute_multibackslash_replacement', { value: 'one,two \n three,four', expectedValue: 'one\\\\\\\\two \n three\\\\\\\\four', // 2*8 backslashes. expr: '%s/,/\\\\\\\\\\\\\\\\/g'}); // 16 backslashes. testSubstitute('ex_substitute_dollar_match', { value: 'one,two \n three,four', expectedValue: 'one,two ,\n three,four', expr: '%s/$/,/g'}); testSubstitute('ex_substitute_newline_match', { value: 'one,two \n three,four', expectedValue: 'one,two , three,four', expr: '%s/\\n/,/g'}); testSubstitute('ex_substitute_newline_replacement', { value: 'one,two \n three,four', expectedValue: 'one\ntwo \n three\nfour', expr: '%s/,/\\n/g'}); testSubstitute('ex_substitute_braces_word', { value: 'ababab abb ab{2}', expectedValue: 'ab abb ab{2}', expr: '%s/(ab){2}//g', noPcreExpr: '%s/\\(ab\\)\\{2\\}//g'}); testSubstitute('ex_substitute_braces_range', { value: 'a aa aaa aaaa', expectedValue: 'a a', expr: '%s/a{2,3}//g', noPcreExpr: '%s/a\\{2,3\\}//g'}); testSubstitute('ex_substitute_braces_literal', { value: 'ababab abb ab{2}', expectedValue: 'ababab abb ', expr: '%s/ab\\{2\\}//g', noPcreExpr: '%s/ab{2}//g'}); testSubstitute('ex_substitute_braces_char', { value: 'ababab abb ab{2}', expectedValue: 'ababab ab{2}', expr: '%s/ab{2}//g', noPcreExpr: '%s/ab\\{2\\}//g'}); testSubstitute('ex_substitute_braces_no_escape', { value: 'ababab abb ab{2}', expectedValue: 'ababab ab{2}', expr: '%s/ab{2}//g', noPcreExpr: '%s/ab\\{2}//g'}); testSubstitute('ex_substitute_count', { value: '1\n2\n3\n4', expectedValue: '1\n0\n0\n4', expr: 's/\\d/0/i 2'}); testSubstitute('ex_substitute_count_with_range', { value: '1\n2\n3\n4', expectedValue: '1\n2\n0\n0', expr: '1,3s/\\d/0/ 3'}); testSubstitute('ex_substitute_not_global', { value: 'aaa\nbaa\ncaa', expectedValue: 'xaa\nbxa\ncxa', expr: '%s/a/x/'}); function testSubstituteConfirm(name, command, initialValue, expectedValue, keys, finalPos) { testVim(name, function(cm, vim, helpers) { var savedOpenDialog = cm.openDialog; var savedKeyName = CodeMirror.keyName; var onKeyDown; var recordedCallback; var closed = true; // Start out closed, set false on second openDialog. function close() { closed = true; } // First openDialog should save callback. cm.openDialog = function(template, callback, options) { recordedCallback = callback; } // Do first openDialog. helpers.doKeys(':'); // Second openDialog should save keyDown handler. cm.openDialog = function(template, callback, options) { onKeyDown = options.onKeyDown; closed = false; }; // Return the command to Vim and trigger second openDialog. recordedCallback(command); // The event should really use keyCode, but here just mock it out and use // key and replace keyName to just return key. CodeMirror.keyName = function (e) { return e.key; } keys = keys.toUpperCase(); for (var i = 0; i < keys.length; i++) { is(!closed); onKeyDown({ key: keys.charAt(i) }, '', close); } try { eq(expectedValue, cm.getValue()); helpers.assertCursorAt(finalPos); is(closed); } catch(e) { throw e } finally { // Restore overridden functions. CodeMirror.keyName = savedKeyName; cm.openDialog = savedOpenDialog; } }, { value: initialValue }); } testSubstituteConfirm('ex_substitute_confirm_emptydoc', '%s/x/b/c', '', '', '', makeCursor(0, 0)); testSubstituteConfirm('ex_substitute_confirm_nomatch', '%s/x/b/c', 'ba a\nbab', 'ba a\nbab', '', makeCursor(0, 0)); testSubstituteConfirm('ex_substitute_confirm_accept', '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'yyy', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_random_keys', '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ysdkywerty', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_some', '%s/a/b/cg', 'ba a\nbab', 'bb a\nbbb', 'yny', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_all', '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'a', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_accept_then_all', '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ya', makeCursor(1, 1)); testSubstituteConfirm('ex_substitute_confirm_quit', '%s/a/b/cg', 'ba a\nbab', 'bb a\nbab', 'yq', makeCursor(0, 3)); testSubstituteConfirm('ex_substitute_confirm_last', '%s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3)); testSubstituteConfirm('ex_substitute_confirm_oneline', '1s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3)); testSubstituteConfirm('ex_substitute_confirm_range_accept', '1,2s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyy', makeCursor(1, 0)); testSubstituteConfirm('ex_substitute_confirm_range_some', '1,3s/a/b/cg', 'aa\na \na\na', 'ba\nb \nb\na', 'ynyy', makeCursor(2, 0)); testSubstituteConfirm('ex_substitute_confirm_range_all', '1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \nb\na', 'a', makeCursor(2, 0)); testSubstituteConfirm('ex_substitute_confirm_range_last', '1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyl', makeCursor(1, 0)); //:noh should clear highlighting of search-results but allow to resume search through n testVim('ex_noh_clearSearchHighlight', function(cm, vim, helpers) { cm.openDialog = helpers.fakeOpenDialog('match'); helpers.doKeys('?'); helpers.doEx('noh'); eq(vim.searchState_.getOverlay(),null,'match-highlighting wasn\'t cleared'); helpers.doKeys('n'); helpers.assertCursorAt(0, 11,'can\'t resume search after clearing highlighting'); }, { value: 'match nope match \n nope Match' }); testVim('ex_yank', function (cm, vim, helpers) { var curStart = makeCursor(3, 0); cm.setCursor(curStart); helpers.doEx('y'); var register = helpers.getRegisterController().getRegister(); var line = cm.getLine(3); eq(line + '\n', register.toString()); }); testVim('set_boolean', function(cm, vim, helpers) { CodeMirror.Vim.defineOption('testoption', true, 'boolean'); // Test default value is set. is(CodeMirror.Vim.getOption('testoption')); try { // Test fail to set to non-boolean CodeMirror.Vim.setOption('testoption', '5'); fail(); } catch (expected) {} // Test setOption CodeMirror.Vim.setOption('testoption', false); is(!CodeMirror.Vim.getOption('testoption')); }); testVim('ex_set_boolean', function(cm, vim, helpers) { CodeMirror.Vim.defineOption('testoption', true, 'boolean'); // Test default value is set. is(CodeMirror.Vim.getOption('testoption')); try { // Test fail to set to non-boolean helpers.doEx('set testoption=22'); fail(); } catch (expected) {} // Test setOption helpers.doEx('set notestoption'); is(!CodeMirror.Vim.getOption('testoption')); }); testVim('set_string', function(cm, vim, helpers) { CodeMirror.Vim.defineOption('testoption', 'a', 'string'); // Test default value is set. eq('a', CodeMirror.Vim.getOption('testoption')); try { // Test fail to set non-string. CodeMirror.Vim.setOption('testoption', true); fail(); } catch (expected) {} try { // Test fail to set 'notestoption' CodeMirror.Vim.setOption('notestoption', 'b'); fail(); } catch (expected) {} // Test setOption CodeMirror.Vim.setOption('testoption', 'c'); eq('c', CodeMirror.Vim.getOption('testoption')); }); testVim('ex_set_string', function(cm, vim, helpers) { CodeMirror.Vim.defineOption('testopt', 'a', 'string'); // Test default value is set. eq('a', CodeMirror.Vim.getOption('testopt')); try { // Test fail to set 'notestopt' helpers.doEx('set notestopt=b'); fail(); } catch (expected) {} // Test setOption helpers.doEx('set testopt=c') eq('c', CodeMirror.Vim.getOption('testopt')); helpers.doEx('set testopt=c') eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global eq('c', CodeMirror.Vim.getOption('testopt')); // global // Test setOption global helpers.doEx('setg testopt=d') eq('c', CodeMirror.Vim.getOption('testopt', cm)); eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); eq('d', CodeMirror.Vim.getOption('testopt')); // Test setOption local helpers.doEx('setl testopt=e') eq('e', CodeMirror.Vim.getOption('testopt', cm)); eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); eq('d', CodeMirror.Vim.getOption('testopt')); }); testVim('ex_set_callback', function(cm, vim, helpers) { var global; function cb(val, cm, cfg) { if (val === undefined) { // Getter if (cm) { return cm._local; } else { return global; } } else { // Setter if (cm) { cm._local = val; } else { global = val; } } } CodeMirror.Vim.defineOption('testopt', 'a', 'string', cb); // Test default value is set. eq('a', CodeMirror.Vim.getOption('testopt')); try { // Test fail to set 'notestopt' helpers.doEx('set notestopt=b'); fail(); } catch (expected) {} // Test setOption (Identical to the string tests, but via callback instead) helpers.doEx('set testopt=c') eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global eq('c', CodeMirror.Vim.getOption('testopt')); // global // Test setOption global helpers.doEx('setg testopt=d') eq('c', CodeMirror.Vim.getOption('testopt', cm)); eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); eq('d', CodeMirror.Vim.getOption('testopt')); // Test setOption local helpers.doEx('setl testopt=e') eq('e', CodeMirror.Vim.getOption('testopt', cm)); eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); eq('d', CodeMirror.Vim.getOption('testopt')); }) testVim('ex_set_filetype', function(cm, vim, helpers) { CodeMirror.defineMode('test_mode', function() { return {token: function(stream) { stream.match(/^\s+|^\S+/); }}; }); CodeMirror.defineMode('test_mode_2', function() { return {token: function(stream) { stream.match(/^\s+|^\S+/); }}; }); // Test mode is set. helpers.doEx('set filetype=test_mode'); eq('test_mode', cm.getMode().name); // Test 'ft' alias also sets mode. helpers.doEx('set ft=test_mode_2'); eq('test_mode_2', cm.getMode().name); }); testVim('ex_set_filetype_null', function(cm, vim, helpers) { CodeMirror.defineMode('test_mode', function() { return {token: function(stream) { stream.match(/^\s+|^\S+/); }}; }); cm.setOption('mode', 'test_mode'); // Test mode is set to null. helpers.doEx('set filetype='); eq('null', cm.getMode().name); }); testVim('mapclear', function(cm, vim, helpers) { CodeMirror.Vim.map('w', 'l'); cm.setCursor(0, 0); helpers.assertCursorAt(0, 0); helpers.doKeys('w'); helpers.assertCursorAt(0, 1); CodeMirror.Vim.mapclear('visual'); helpers.doKeys('v', 'w', 'v'); helpers.assertCursorAt(0, 4); helpers.doKeys('w'); helpers.assertCursorAt(0, 5); CodeMirror.Vim.mapclear(); }, { value: 'abc abc' }); testVim('mapclear_context', function(cm, vim, helpers) { CodeMirror.Vim.map('w', 'l', 'normal'); cm.setCursor(0, 0); helpers.assertCursorAt(0, 0); helpers.doKeys('w'); helpers.assertCursorAt(0, 1); CodeMirror.Vim.mapclear('normal'); helpers.doKeys('w'); helpers.assertCursorAt(0, 4); CodeMirror.Vim.mapclear(); }, { value: 'abc abc' }); testVim('ex_map_key2key', function(cm, vim, helpers) { helpers.doEx('map a x'); helpers.doKeys('a'); helpers.assertCursorAt(0, 0); eq('bc', cm.getValue()); CodeMirror.Vim.mapclear(); }, { value: 'abc' }); testVim('ex_unmap_key2key', function(cm, vim, helpers) { helpers.doEx('map a x'); helpers.doEx('unmap a'); helpers.doKeys('a'); eq('vim-insert', cm.getOption('keyMap')); CodeMirror.Vim.mapclear(); }, { value: 'abc' }); testVim('ex_unmap_key2key_does_not_remove_default', function(cm, vim, helpers) { try { helpers.doEx('unmap a'); fail(); } catch (expected) {} helpers.doKeys('a'); eq('vim-insert', cm.getOption('keyMap')); CodeMirror.Vim.mapclear(); }, { value: 'abc' }); testVim('ex_map_key2key_to_colon', function(cm, vim, helpers) { helpers.doEx('map ; :'); var dialogOpened = false; cm.openDialog = function() { dialogOpened = true; } helpers.doKeys(';'); eq(dialogOpened, true); CodeMirror.Vim.mapclear(); }); testVim('ex_map_ex2key:', function(cm, vim, helpers) { helpers.doEx('map :del x'); helpers.doEx('del'); helpers.assertCursorAt(0, 0); eq('bc', cm.getValue()); CodeMirror.Vim.mapclear(); }, { value: 'abc' }); testVim('ex_map_ex2ex', function(cm, vim, helpers) { helpers.doEx('map :del :w'); var tmp = CodeMirror.commands.save; var written = false; var actualCm; CodeMirror.commands.save = function(cm) { written = true; actualCm = cm; }; helpers.doEx('del'); CodeMirror.commands.save = tmp; eq(written, true); eq(actualCm, cm); CodeMirror.Vim.mapclear(); }); testVim('ex_map_key2ex', function(cm, vim, helpers) { helpers.doEx('map a :w'); var tmp = CodeMirror.commands.save; var written = false; var actualCm; CodeMirror.commands.save = function(cm) { written = true; actualCm = cm; }; helpers.doKeys('a'); CodeMirror.commands.save = tmp; eq(written, true); eq(actualCm, cm); CodeMirror.Vim.mapclear(); }); testVim('ex_map_key2key_visual_api', function(cm, vim, helpers) { CodeMirror.Vim.map('b', ':w', 'visual'); var tmp = CodeMirror.commands.save; var written = false; var actualCm; CodeMirror.commands.save = function(cm) { written = true; actualCm = cm; }; // Mapping should not work in normal mode. helpers.doKeys('b'); eq(written, false); // Mapping should work in visual mode. helpers.doKeys('v', 'b'); eq(written, true); eq(actualCm, cm); CodeMirror.commands.save = tmp; CodeMirror.Vim.mapclear(); }); testVim('ex_imap', function(cm, vim, helpers) { CodeMirror.Vim.map('jk', '', 'insert'); helpers.doKeys('i'); is(vim.insertMode); helpers.doKeys('j', 'k'); is(!vim.insertMode); cm.setCursor(0, 1); CodeMirror.Vim.map('jj', '', 'insert'); helpers.doKeys('', '2', 'j', 'l', 'c'); var replacement = fillArray('f', 3); cm.replaceSelections(replacement); var replacement = fillArray('o', 3); cm.replaceSelections(replacement); eq('1fo4\n5fo8\nafodefg', cm.getValue()); helpers.doKeys('j', 'j'); cm.setCursor(0, 0); helpers.doKeys('.'); eq('foo4\nfoo8\nfoodefg', cm.getValue()); CodeMirror.Vim.mapclear(); }, { value: '1234\n5678\nabcdefg' }); testVim('ex_unmap_api', function(cm, vim, helpers) { CodeMirror.Vim.map('', 'gg', 'normal'); is(CodeMirror.Vim.handleKey(cm, "", "normal"), "Alt-X key is mapped"); CodeMirror.Vim.unmap("", "normal"); is(!CodeMirror.Vim.handleKey(cm, "", "normal"), "Alt-X key is unmapped"); CodeMirror.Vim.mapclear(); }); // Testing registration of functions as ex-commands and mapping to -keys testVim('ex_api_test', function(cm, vim, helpers) { var res=false; var val='from'; CodeMirror.Vim.defineEx('extest','ext',function(cm,params){ if(params.args)val=params.args[0]; else res=true; }); helpers.doEx(':ext to'); eq(val,'to','Defining ex-command failed'); CodeMirror.Vim.map('',':ext'); helpers.doKeys('',''); is(res,'Mapping to key failed'); CodeMirror.Vim.mapclear(); }); // For now, this test needs to be last because it messes up : for future tests. testVim('ex_map_key2key_from_colon', function(cm, vim, helpers) { helpers.doEx('map : x'); helpers.doKeys(':'); helpers.assertCursorAt(0, 0); eq('bc', cm.getValue()); CodeMirror.Vim.mapclear(); }, { value: 'abc' }); testVim('noremap', function(cm, vim, helpers) { CodeMirror.Vim.noremap(';', 'l'); cm.setCursor(0, 0); eq('wOrd1', cm.getValue()); // Mapping should work in normal mode. helpers.doKeys(';', 'r', '1'); eq('w1rd1', cm.getValue()); // Mapping will not work in insert mode because of no current fallback // keyToKey mapping support. helpers.doKeys('i', ';', ''); eq('w;1rd1', cm.getValue()); // unmap all mappings CodeMirror.Vim.mapclear(); }, { value: 'wOrd1' }); testVim('noremap_swap', function(cm, vim, helpers) { CodeMirror.Vim.noremap('i', 'a', 'normal'); CodeMirror.Vim.noremap('a', 'i', 'normal'); cm.setCursor(0, 0); // 'a' should act like 'i'. helpers.doKeys('a'); eqCursorPos(Pos(0, 0), cm.getCursor()); // ...and 'i' should act like 'a'. helpers.doKeys('', 'i'); eqCursorPos(Pos(0, 1), cm.getCursor()); // unmap all mappings CodeMirror.Vim.mapclear(); }, { value: 'foo' }); testVim('noremap_map_interaction', function(cm, vim, helpers) { // noremap should clobber map CodeMirror.Vim.map(';', 'l'); CodeMirror.Vim.noremap(';', 'l'); CodeMirror.Vim.map('l', 'j'); cm.setCursor(0, 0); helpers.doKeys(';'); eqCursorPos(Pos(0, 1), cm.getCursor()); helpers.doKeys('l'); eqCursorPos(Pos(1, 1), cm.getCursor()); // map should be able to point to a noremap CodeMirror.Vim.map('m', ';'); helpers.doKeys('m'); eqCursorPos(Pos(1, 2), cm.getCursor()); // unmap all mappings CodeMirror.Vim.mapclear(); }, { value: 'wOrd1\nwOrd2' }); testVim('noremap_map_interaction2', function(cm, vim, helpers) { // map should point to the most recent noremap CodeMirror.Vim.noremap(';', 'l'); CodeMirror.Vim.map('m', ';'); CodeMirror.Vim.noremap(';', 'h'); cm.setCursor(0, 0); helpers.doKeys('l'); eqCursorPos(Pos(0, 1), cm.getCursor()); helpers.doKeys('m'); eqCursorPos(Pos(0, 0), cm.getCursor()); // unmap all mappings CodeMirror.Vim.mapclear(); }, { value: 'wOrd1\nwOrd2' }); // Test event handlers testVim('beforeSelectionChange', function(cm, vim, helpers) { cm.setCursor(0, 100); eqCursorPos(cm.getCursor('head'), cm.getCursor('anchor')); }, { value: 'abc' }); testVim('increment_binary', function(cm, vim, helpers) { cm.setCursor(0, 4); helpers.doKeys(''); eq('0b001', cm.getValue()); helpers.doKeys(''); eq('0b010', cm.getValue()); helpers.doKeys(''); eq('0b001', cm.getValue()); helpers.doKeys(''); eq('0b000', cm.getValue()); cm.setCursor(0, 0); helpers.doKeys(''); eq('0b001', cm.getValue()); helpers.doKeys(''); eq('0b010', cm.getValue()); helpers.doKeys(''); eq('0b001', cm.getValue()); helpers.doKeys(''); eq('0b000', cm.getValue()); }, { value: '0b000' }); testVim('increment_octal', function(cm, vim, helpers) { cm.setCursor(0, 2); helpers.doKeys(''); eq('001', cm.getValue()); helpers.doKeys(''); eq('002', cm.getValue()); helpers.doKeys(''); eq('003', cm.getValue()); helpers.doKeys(''); eq('004', cm.getValue()); helpers.doKeys(''); eq('005', cm.getValue()); helpers.doKeys(''); eq('006', cm.getValue()); helpers.doKeys(''); eq('007', cm.getValue()); helpers.doKeys(''); eq('010', cm.getValue()); helpers.doKeys(''); eq('007', cm.getValue()); helpers.doKeys(''); eq('006', cm.getValue()); helpers.doKeys(''); eq('005', cm.getValue()); helpers.doKeys(''); eq('004', cm.getValue()); helpers.doKeys(''); eq('003', cm.getValue()); helpers.doKeys(''); eq('002', cm.getValue()); helpers.doKeys(''); eq('001', cm.getValue()); helpers.doKeys(''); eq('000', cm.getValue()); cm.setCursor(0, 0); helpers.doKeys(''); eq('001', cm.getValue()); helpers.doKeys(''); eq('002', cm.getValue()); helpers.doKeys(''); eq('001', cm.getValue()); helpers.doKeys(''); eq('000', cm.getValue()); }, { value: '000' }); testVim('increment_decimal', function(cm, vim, helpers) { cm.setCursor(0, 2); helpers.doKeys(''); eq('101', cm.getValue()); helpers.doKeys(''); eq('102', cm.getValue()); helpers.doKeys(''); eq('103', cm.getValue()); helpers.doKeys(''); eq('104', cm.getValue()); helpers.doKeys(''); eq('105', cm.getValue()); helpers.doKeys(''); eq('106', cm.getValue()); helpers.doKeys(''); eq('107', cm.getValue()); helpers.doKeys(''); eq('108', cm.getValue()); helpers.doKeys(''); eq('109', cm.getValue()); helpers.doKeys(''); eq('110', cm.getValue()); helpers.doKeys(''); eq('109', cm.getValue()); helpers.doKeys(''); eq('108', cm.getValue()); helpers.doKeys(''); eq('107', cm.getValue()); helpers.doKeys(''); eq('106', cm.getValue()); helpers.doKeys(''); eq('105', cm.getValue()); helpers.doKeys(''); eq('104', cm.getValue()); helpers.doKeys(''); eq('103', cm.getValue()); helpers.doKeys(''); eq('102', cm.getValue()); helpers.doKeys(''); eq('101', cm.getValue()); helpers.doKeys(''); eq('100', cm.getValue()); cm.setCursor(0, 0); helpers.doKeys(''); eq('101', cm.getValue()); helpers.doKeys(''); eq('102', cm.getValue()); helpers.doKeys(''); eq('101', cm.getValue()); helpers.doKeys(''); eq('100', cm.getValue()); }, { value: '100' }); testVim('increment_decimal_single_zero', function(cm, vim, helpers) { helpers.doKeys(''); eq('1', cm.getValue()); helpers.doKeys(''); eq('2', cm.getValue()); helpers.doKeys(''); eq('3', cm.getValue()); helpers.doKeys(''); eq('4', cm.getValue()); helpers.doKeys(''); eq('5', cm.getValue()); helpers.doKeys(''); eq('6', cm.getValue()); helpers.doKeys(''); eq('7', cm.getValue()); helpers.doKeys(''); eq('8', cm.getValue()); helpers.doKeys(''); eq('9', cm.getValue()); helpers.doKeys(''); eq('10', cm.getValue()); helpers.doKeys(''); eq('9', cm.getValue()); helpers.doKeys(''); eq('8', cm.getValue()); helpers.doKeys(''); eq('7', cm.getValue()); helpers.doKeys(''); eq('6', cm.getValue()); helpers.doKeys(''); eq('5', cm.getValue()); helpers.doKeys(''); eq('4', cm.getValue()); helpers.doKeys(''); eq('3', cm.getValue()); helpers.doKeys(''); eq('2', cm.getValue()); helpers.doKeys(''); eq('1', cm.getValue()); helpers.doKeys(''); eq('0', cm.getValue()); cm.setCursor(0, 0); helpers.doKeys(''); eq('1', cm.getValue()); helpers.doKeys(''); eq('2', cm.getValue()); helpers.doKeys(''); eq('1', cm.getValue()); helpers.doKeys(''); eq('0', cm.getValue()); }, { value: '0' }); testVim('increment_hexadecimal', function(cm, vim, helpers) { cm.setCursor(0, 2); helpers.doKeys(''); eq('0x1', cm.getValue()); helpers.doKeys(''); eq('0x2', cm.getValue()); helpers.doKeys(''); eq('0x3', cm.getValue()); helpers.doKeys(''); eq('0x4', cm.getValue()); helpers.doKeys(''); eq('0x5', cm.getValue()); helpers.doKeys(''); eq('0x6', cm.getValue()); helpers.doKeys(''); eq('0x7', cm.getValue()); helpers.doKeys(''); eq('0x8', cm.getValue()); helpers.doKeys(''); eq('0x9', cm.getValue()); helpers.doKeys(''); eq('0xa', cm.getValue()); helpers.doKeys(''); eq('0xb', cm.getValue()); helpers.doKeys(''); eq('0xc', cm.getValue()); helpers.doKeys(''); eq('0xd', cm.getValue()); helpers.doKeys(''); eq('0xe', cm.getValue()); helpers.doKeys(''); eq('0xf', cm.getValue()); helpers.doKeys(''); eq('0x10', cm.getValue()); helpers.doKeys(''); eq('0x0f', cm.getValue()); helpers.doKeys(''); eq('0x0e', cm.getValue()); helpers.doKeys(''); eq('0x0d', cm.getValue()); helpers.doKeys(''); eq('0x0c', cm.getValue()); helpers.doKeys(''); eq('0x0b', cm.getValue()); helpers.doKeys(''); eq('0x0a', cm.getValue()); helpers.doKeys(''); eq('0x09', cm.getValue()); helpers.doKeys(''); eq('0x08', cm.getValue()); helpers.doKeys(''); eq('0x07', cm.getValue()); helpers.doKeys(''); eq('0x06', cm.getValue()); helpers.doKeys(''); eq('0x05', cm.getValue()); helpers.doKeys(''); eq('0x04', cm.getValue()); helpers.doKeys(''); eq('0x03', cm.getValue()); helpers.doKeys(''); eq('0x02', cm.getValue()); helpers.doKeys(''); eq('0x01', cm.getValue()); helpers.doKeys(''); eq('0x00', cm.getValue()); cm.setCursor(0, 0); helpers.doKeys(''); eq('0x01', cm.getValue()); helpers.doKeys(''); eq('0x02', cm.getValue()); helpers.doKeys(''); eq('0x01', cm.getValue()); helpers.doKeys(''); eq('0x00', cm.getValue()); }, { value: '0x0' }); ================================================ FILE: third_party/CodeMirror/theme/3024-day.css ================================================ /* Name: 3024 day Author: Jan T. Sott (http://github.com/idleberg) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-3024-day.CodeMirror { background: #f7f7f7; color: #3a3432; } .cm-s-3024-day div.CodeMirror-selected { background: #d6d5d4; } .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; } .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; } .cm-s-3024-day .CodeMirror-gutters { background: #f7f7f7; border-right: 0px; } .cm-s-3024-day .CodeMirror-guttermarker { color: #db2d20; } .cm-s-3024-day .CodeMirror-guttermarker-subtle { color: #807d7c; } .cm-s-3024-day .CodeMirror-linenumber { color: #807d7c; } .cm-s-3024-day .CodeMirror-cursor { border-left: 1px solid #5c5855; } .cm-s-3024-day span.cm-comment { color: #cdab53; } .cm-s-3024-day span.cm-atom { color: #a16a94; } .cm-s-3024-day span.cm-number { color: #a16a94; } .cm-s-3024-day span.cm-property, .cm-s-3024-day span.cm-attribute { color: #01a252; } .cm-s-3024-day span.cm-keyword { color: #db2d20; } .cm-s-3024-day span.cm-string { color: #fded02; } .cm-s-3024-day span.cm-variable { color: #01a252; } .cm-s-3024-day span.cm-variable-2 { color: #01a0e4; } .cm-s-3024-day span.cm-def { color: #e8bbd0; } .cm-s-3024-day span.cm-bracket { color: #3a3432; } .cm-s-3024-day span.cm-tag { color: #db2d20; } .cm-s-3024-day span.cm-link { color: #a16a94; } .cm-s-3024-day span.cm-error { background: #db2d20; color: #5c5855; } .cm-s-3024-day .CodeMirror-activeline-background { background: #e8f2ff; } .cm-s-3024-day .CodeMirror-matchingbracket { text-decoration: underline; color: #a16a94 !important; } ================================================ FILE: third_party/CodeMirror/theme/3024-night.css ================================================ /* Name: 3024 night Author: Jan T. Sott (http://github.com/idleberg) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-3024-night.CodeMirror { background: #090300; color: #d6d5d4; } .cm-s-3024-night div.CodeMirror-selected { background: #3a3432; } .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); } .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); } .cm-s-3024-night .CodeMirror-gutters { background: #090300; border-right: 0px; } .cm-s-3024-night .CodeMirror-guttermarker { color: #db2d20; } .cm-s-3024-night .CodeMirror-guttermarker-subtle { color: #5c5855; } .cm-s-3024-night .CodeMirror-linenumber { color: #5c5855; } .cm-s-3024-night .CodeMirror-cursor { border-left: 1px solid #807d7c; } .cm-s-3024-night span.cm-comment { color: #cdab53; } .cm-s-3024-night span.cm-atom { color: #a16a94; } .cm-s-3024-night span.cm-number { color: #a16a94; } .cm-s-3024-night span.cm-property, .cm-s-3024-night span.cm-attribute { color: #01a252; } .cm-s-3024-night span.cm-keyword { color: #db2d20; } .cm-s-3024-night span.cm-string { color: #fded02; } .cm-s-3024-night span.cm-variable { color: #01a252; } .cm-s-3024-night span.cm-variable-2 { color: #01a0e4; } .cm-s-3024-night span.cm-def { color: #e8bbd0; } .cm-s-3024-night span.cm-bracket { color: #d6d5d4; } .cm-s-3024-night span.cm-tag { color: #db2d20; } .cm-s-3024-night span.cm-link { color: #a16a94; } .cm-s-3024-night span.cm-error { background: #db2d20; color: #807d7c; } .cm-s-3024-night .CodeMirror-activeline-background { background: #2F2F2F; } .cm-s-3024-night .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/abcdef.css ================================================ .cm-s-abcdef.CodeMirror { background: #0f0f0f; color: #defdef; } .cm-s-abcdef div.CodeMirror-selected { background: #515151; } .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); } .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); } .cm-s-abcdef .CodeMirror-gutters { background: #555; border-right: 2px solid #314151; } .cm-s-abcdef .CodeMirror-guttermarker { color: #222; } .cm-s-abcdef .CodeMirror-guttermarker-subtle { color: azure; } .cm-s-abcdef .CodeMirror-linenumber { color: #FFFFFF; } .cm-s-abcdef .CodeMirror-cursor { border-left: 1px solid #00FF00; } .cm-s-abcdef span.cm-keyword { color: darkgoldenrod; font-weight: bold; } .cm-s-abcdef span.cm-atom { color: #77F; } .cm-s-abcdef span.cm-number { color: violet; } .cm-s-abcdef span.cm-def { color: #fffabc; } .cm-s-abcdef span.cm-variable { color: #abcdef; } .cm-s-abcdef span.cm-variable-2 { color: #cacbcc; } .cm-s-abcdef span.cm-variable-3, .cm-s-abcdef span.cm-type { color: #def; } .cm-s-abcdef span.cm-property { color: #fedcba; } .cm-s-abcdef span.cm-operator { color: #ff0; } .cm-s-abcdef span.cm-comment { color: #7a7b7c; font-style: italic;} .cm-s-abcdef span.cm-string { color: #2b4; } .cm-s-abcdef span.cm-meta { color: #C9F; } .cm-s-abcdef span.cm-qualifier { color: #FFF700; } .cm-s-abcdef span.cm-builtin { color: #30aabc; } .cm-s-abcdef span.cm-bracket { color: #8a8a8a; } .cm-s-abcdef span.cm-tag { color: #FFDD44; } .cm-s-abcdef span.cm-attribute { color: #DDFF00; } .cm-s-abcdef span.cm-error { color: #FF0000; } .cm-s-abcdef span.cm-header { color: aquamarine; font-weight: bold; } .cm-s-abcdef span.cm-link { color: blueviolet; } .cm-s-abcdef .CodeMirror-activeline-background { background: #314151; } ================================================ FILE: third_party/CodeMirror/theme/ambiance-mobile.css ================================================ .cm-s-ambiance.CodeMirror { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } ================================================ FILE: third_party/CodeMirror/theme/ambiance.css ================================================ /* ambiance theme for codemirror */ /* Color scheme */ .cm-s-ambiance .cm-header { color: blue; } .cm-s-ambiance .cm-quote { color: #24C2C7; } .cm-s-ambiance .cm-keyword { color: #cda869; } .cm-s-ambiance .cm-atom { color: #CF7EA9; } .cm-s-ambiance .cm-number { color: #78CF8A; } .cm-s-ambiance .cm-def { color: #aac6e3; } .cm-s-ambiance .cm-variable { color: #ffb795; } .cm-s-ambiance .cm-variable-2 { color: #eed1b3; } .cm-s-ambiance .cm-variable-3, .cm-s-ambiance .cm-type { color: #faded3; } .cm-s-ambiance .cm-property { color: #eed1b3; } .cm-s-ambiance .cm-operator { color: #fa8d6a; } .cm-s-ambiance .cm-comment { color: #555; font-style:italic; } .cm-s-ambiance .cm-string { color: #8f9d6a; } .cm-s-ambiance .cm-string-2 { color: #9d937c; } .cm-s-ambiance .cm-meta { color: #D2A8A1; } .cm-s-ambiance .cm-qualifier { color: yellow; } .cm-s-ambiance .cm-builtin { color: #9999cc; } .cm-s-ambiance .cm-bracket { color: #24C2C7; } .cm-s-ambiance .cm-tag { color: #fee4ff; } .cm-s-ambiance .cm-attribute { color: #9B859D; } .cm-s-ambiance .cm-hr { color: pink; } .cm-s-ambiance .cm-link { color: #F4C20B; } .cm-s-ambiance .cm-special { color: #FF9D00; } .cm-s-ambiance .cm-error { color: #AF2018; } .cm-s-ambiance .CodeMirror-matchingbracket { color: #0f0; } .cm-s-ambiance .CodeMirror-nonmatchingbracket { color: #f22; } .cm-s-ambiance div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); } .cm-s-ambiance.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } .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); } .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); } /* Editor styling */ .cm-s-ambiance.CodeMirror { line-height: 1.40em; color: #E6E1DC; background-color: #202020; -webkit-box-shadow: inset 0 0 10px black; -moz-box-shadow: inset 0 0 10px black; box-shadow: inset 0 0 10px black; } .cm-s-ambiance .CodeMirror-gutters { background: #3D3D3D; border-right: 1px solid #4D4D4D; box-shadow: 0 10px 20px black; } .cm-s-ambiance .CodeMirror-linenumber { text-shadow: 0px 1px 1px #4d4d4d; color: #111; padding: 0 5px; } .cm-s-ambiance .CodeMirror-guttermarker { color: #aaa; } .cm-s-ambiance .CodeMirror-guttermarker-subtle { color: #111; } .cm-s-ambiance .CodeMirror-cursor { border-left: 1px solid #7991E8; } .cm-s-ambiance .CodeMirror-activeline-background { background: none repeat scroll 0% 0% rgba(255, 255, 255, 0.031); } .cm-s-ambiance.CodeMirror, .cm-s-ambiance .CodeMirror-gutters { 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"); } ================================================ FILE: third_party/CodeMirror/theme/base16-dark.css ================================================ /* Name: Base16 Default Dark Author: Chris Kempson (http://chriskempson.com) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-base16-dark.CodeMirror { background: #151515; color: #e0e0e0; } .cm-s-base16-dark div.CodeMirror-selected { background: #303030; } .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); } .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); } .cm-s-base16-dark .CodeMirror-gutters { background: #151515; border-right: 0px; } .cm-s-base16-dark .CodeMirror-guttermarker { color: #ac4142; } .cm-s-base16-dark .CodeMirror-guttermarker-subtle { color: #505050; } .cm-s-base16-dark .CodeMirror-linenumber { color: #505050; } .cm-s-base16-dark .CodeMirror-cursor { border-left: 1px solid #b0b0b0; } .cm-s-base16-dark span.cm-comment { color: #8f5536; } .cm-s-base16-dark span.cm-atom { color: #aa759f; } .cm-s-base16-dark span.cm-number { color: #aa759f; } .cm-s-base16-dark span.cm-property, .cm-s-base16-dark span.cm-attribute { color: #90a959; } .cm-s-base16-dark span.cm-keyword { color: #ac4142; } .cm-s-base16-dark span.cm-string { color: #f4bf75; } .cm-s-base16-dark span.cm-variable { color: #90a959; } .cm-s-base16-dark span.cm-variable-2 { color: #6a9fb5; } .cm-s-base16-dark span.cm-def { color: #d28445; } .cm-s-base16-dark span.cm-bracket { color: #e0e0e0; } .cm-s-base16-dark span.cm-tag { color: #ac4142; } .cm-s-base16-dark span.cm-link { color: #aa759f; } .cm-s-base16-dark span.cm-error { background: #ac4142; color: #b0b0b0; } .cm-s-base16-dark .CodeMirror-activeline-background { background: #202020; } .cm-s-base16-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/base16-light.css ================================================ /* Name: Base16 Default Light Author: Chris Kempson (http://chriskempson.com) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-base16-light.CodeMirror { background: #f5f5f5; color: #202020; } .cm-s-base16-light div.CodeMirror-selected { background: #e0e0e0; } .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; } .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; } .cm-s-base16-light .CodeMirror-gutters { background: #f5f5f5; border-right: 0px; } .cm-s-base16-light .CodeMirror-guttermarker { color: #ac4142; } .cm-s-base16-light .CodeMirror-guttermarker-subtle { color: #b0b0b0; } .cm-s-base16-light .CodeMirror-linenumber { color: #b0b0b0; } .cm-s-base16-light .CodeMirror-cursor { border-left: 1px solid #505050; } .cm-s-base16-light span.cm-comment { color: #8f5536; } .cm-s-base16-light span.cm-atom { color: #aa759f; } .cm-s-base16-light span.cm-number { color: #aa759f; } .cm-s-base16-light span.cm-property, .cm-s-base16-light span.cm-attribute { color: #90a959; } .cm-s-base16-light span.cm-keyword { color: #ac4142; } .cm-s-base16-light span.cm-string { color: #f4bf75; } .cm-s-base16-light span.cm-variable { color: #90a959; } .cm-s-base16-light span.cm-variable-2 { color: #6a9fb5; } .cm-s-base16-light span.cm-def { color: #d28445; } .cm-s-base16-light span.cm-bracket { color: #202020; } .cm-s-base16-light span.cm-tag { color: #ac4142; } .cm-s-base16-light span.cm-link { color: #aa759f; } .cm-s-base16-light span.cm-error { background: #ac4142; color: #505050; } .cm-s-base16-light .CodeMirror-activeline-background { background: #DDDCDC; } .cm-s-base16-light .CodeMirror-matchingbracket { color: #f5f5f5 !important; background-color: #6A9FB5 !important} ================================================ FILE: third_party/CodeMirror/theme/bespin.css ================================================ /* Name: Bespin Author: Mozilla / Jan T. Sott CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-bespin.CodeMirror {background: #28211c; color: #9d9b97;} .cm-s-bespin div.CodeMirror-selected {background: #36312e !important;} .cm-s-bespin .CodeMirror-gutters {background: #28211c; border-right: 0px;} .cm-s-bespin .CodeMirror-linenumber {color: #666666;} .cm-s-bespin .CodeMirror-cursor {border-left: 1px solid #797977 !important;} .cm-s-bespin span.cm-comment {color: #937121;} .cm-s-bespin span.cm-atom {color: #9b859d;} .cm-s-bespin span.cm-number {color: #9b859d;} .cm-s-bespin span.cm-property, .cm-s-bespin span.cm-attribute {color: #54be0d;} .cm-s-bespin span.cm-keyword {color: #cf6a4c;} .cm-s-bespin span.cm-string {color: #f9ee98;} .cm-s-bespin span.cm-variable {color: #54be0d;} .cm-s-bespin span.cm-variable-2 {color: #5ea6ea;} .cm-s-bespin span.cm-def {color: #cf7d34;} .cm-s-bespin span.cm-error {background: #cf6a4c; color: #797977;} .cm-s-bespin span.cm-bracket {color: #9d9b97;} .cm-s-bespin span.cm-tag {color: #cf6a4c;} .cm-s-bespin span.cm-link {color: #9b859d;} .cm-s-bespin .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} .cm-s-bespin .CodeMirror-activeline-background { background: #404040; } ================================================ FILE: third_party/CodeMirror/theme/blackboard.css ================================================ /* Port of TextMate's Blackboard theme */ .cm-s-blackboard.CodeMirror { background: #0C1021; color: #F8F8F8; } .cm-s-blackboard div.CodeMirror-selected { background: #253B76; } .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); } .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); } .cm-s-blackboard .CodeMirror-gutters { background: #0C1021; border-right: 0; } .cm-s-blackboard .CodeMirror-guttermarker { color: #FBDE2D; } .cm-s-blackboard .CodeMirror-guttermarker-subtle { color: #888; } .cm-s-blackboard .CodeMirror-linenumber { color: #888; } .cm-s-blackboard .CodeMirror-cursor { border-left: 1px solid #A7A7A7; } .cm-s-blackboard .cm-keyword { color: #FBDE2D; } .cm-s-blackboard .cm-atom { color: #D8FA3C; } .cm-s-blackboard .cm-number { color: #D8FA3C; } .cm-s-blackboard .cm-def { color: #8DA6CE; } .cm-s-blackboard .cm-variable { color: #FF6400; } .cm-s-blackboard .cm-operator { color: #FBDE2D; } .cm-s-blackboard .cm-comment { color: #AEAEAE; } .cm-s-blackboard .cm-string { color: #61CE3C; } .cm-s-blackboard .cm-string-2 { color: #61CE3C; } .cm-s-blackboard .cm-meta { color: #D8FA3C; } .cm-s-blackboard .cm-builtin { color: #8DA6CE; } .cm-s-blackboard .cm-tag { color: #8DA6CE; } .cm-s-blackboard .cm-attribute { color: #8DA6CE; } .cm-s-blackboard .cm-header { color: #FF6400; } .cm-s-blackboard .cm-hr { color: #AEAEAE; } .cm-s-blackboard .cm-link { color: #8DA6CE; } .cm-s-blackboard .cm-error { background: #9D1E15; color: #F8F8F8; } .cm-s-blackboard .CodeMirror-activeline-background { background: #3C3636; } .cm-s-blackboard .CodeMirror-matchingbracket { outline:1px solid grey;color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/cobalt.css ================================================ .cm-s-cobalt.CodeMirror { background: #002240; color: white; } .cm-s-cobalt div.CodeMirror-selected { background: #b36539; } .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); } .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); } .cm-s-cobalt .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } .cm-s-cobalt .CodeMirror-guttermarker { color: #ffee80; } .cm-s-cobalt .CodeMirror-guttermarker-subtle { color: #d0d0d0; } .cm-s-cobalt .CodeMirror-linenumber { color: #d0d0d0; } .cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-cobalt span.cm-comment { color: #08f; } .cm-s-cobalt span.cm-atom { color: #845dc4; } .cm-s-cobalt span.cm-number, .cm-s-cobalt span.cm-attribute { color: #ff80e1; } .cm-s-cobalt span.cm-keyword { color: #ffee80; } .cm-s-cobalt span.cm-string { color: #3ad900; } .cm-s-cobalt span.cm-meta { color: #ff9d00; } .cm-s-cobalt span.cm-variable-2, .cm-s-cobalt span.cm-tag { color: #9effff; } .cm-s-cobalt span.cm-variable-3, .cm-s-cobalt span.cm-def, .cm-s-cobalt .cm-type { color: white; } .cm-s-cobalt span.cm-bracket { color: #d8d8d8; } .cm-s-cobalt span.cm-builtin, .cm-s-cobalt span.cm-special { color: #ff9e59; } .cm-s-cobalt span.cm-link { color: #845dc4; } .cm-s-cobalt span.cm-error { color: #9d1e15; } .cm-s-cobalt .CodeMirror-activeline-background { background: #002D57; } .cm-s-cobalt .CodeMirror-matchingbracket { outline:1px solid grey;color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/colorforth.css ================================================ .cm-s-colorforth.CodeMirror { background: #000000; color: #f8f8f8; } .cm-s-colorforth .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } .cm-s-colorforth .CodeMirror-guttermarker { color: #FFBD40; } .cm-s-colorforth .CodeMirror-guttermarker-subtle { color: #78846f; } .cm-s-colorforth .CodeMirror-linenumber { color: #bababa; } .cm-s-colorforth .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-colorforth span.cm-comment { color: #ededed; } .cm-s-colorforth span.cm-def { color: #ff1c1c; font-weight:bold; } .cm-s-colorforth span.cm-keyword { color: #ffd900; } .cm-s-colorforth span.cm-builtin { color: #00d95a; } .cm-s-colorforth span.cm-variable { color: #73ff00; } .cm-s-colorforth span.cm-string { color: #007bff; } .cm-s-colorforth span.cm-number { color: #00c4ff; } .cm-s-colorforth span.cm-atom { color: #606060; } .cm-s-colorforth span.cm-variable-2 { color: #EEE; } .cm-s-colorforth span.cm-variable-3, .cm-s-colorforth span.cm-type { color: #DDD; } .cm-s-colorforth span.cm-property {} .cm-s-colorforth span.cm-operator {} .cm-s-colorforth span.cm-meta { color: yellow; } .cm-s-colorforth span.cm-qualifier { color: #FFF700; } .cm-s-colorforth span.cm-bracket { color: #cc7; } .cm-s-colorforth span.cm-tag { color: #FFBD40; } .cm-s-colorforth span.cm-attribute { color: #FFF700; } .cm-s-colorforth span.cm-error { color: #f00; } .cm-s-colorforth div.CodeMirror-selected { background: #333d53; } .cm-s-colorforth span.cm-compilation { background: rgba(255, 255, 255, 0.12); } .cm-s-colorforth .CodeMirror-activeline-background { background: #253540; } ================================================ FILE: third_party/CodeMirror/theme/darcula.css ================================================ /** Name: IntelliJ IDEA darcula theme From IntelliJ IDEA by JetBrains */ .cm-s-darcula { font-family: Consolas, Menlo, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', monospace, serif;} .cm-s-darcula.CodeMirror { background: #2B2B2B; color: #A9B7C6; } .cm-s-darcula span.cm-meta { color: #BBB529; } .cm-s-darcula span.cm-number { color: #6897BB; } .cm-s-darcula span.cm-keyword { color: #CC7832; line-height: 1em; font-weight: bold; } .cm-s-darcula span.cm-def { color: #A9B7C6; font-style: italic; } .cm-s-darcula span.cm-variable { color: #A9B7C6; } .cm-s-darcula span.cm-variable-2 { color: #A9B7C6; } .cm-s-darcula span.cm-variable-3 { color: #9876AA; } .cm-s-darcula span.cm-type { color: #AABBCC; font-weight: bold; } .cm-s-darcula span.cm-property { color: #FFC66D; } .cm-s-darcula span.cm-operator { color: #A9B7C6; } .cm-s-darcula span.cm-string { color: #6A8759; } .cm-s-darcula span.cm-string-2 { color: #6A8759; } .cm-s-darcula span.cm-comment { color: #61A151; font-style: italic; } .cm-s-darcula span.cm-link { color: #CC7832; } .cm-s-darcula span.cm-atom { color: #CC7832; } .cm-s-darcula span.cm-error { color: #BC3F3C; } .cm-s-darcula span.cm-tag { color: #629755; font-weight: bold; font-style: italic; text-decoration: underline; } .cm-s-darcula span.cm-attribute { color: #6897bb; } .cm-s-darcula span.cm-qualifier { color: #6A8759; } .cm-s-darcula span.cm-bracket { color: #A9B7C6; } .cm-s-darcula span.cm-builtin { color: #FF9E59; } .cm-s-darcula span.cm-special { color: #FF9E59; } .cm-s-darcula .CodeMirror-cursor { border-left: 1px solid #A9B7C6; } .cm-s-darcula .CodeMirror-activeline-background { background: #323232; } .cm-s-darcula .CodeMirror-gutters { background: #313335; border-right: 1px solid #313335; } .cm-s-darcula .CodeMirror-guttermarker { color: #FFEE80; } .cm-s-darcula .CodeMirror-guttermarker-subtle { color: #D0D0D0; } .cm-s-darcula .CodeMirrir-linenumber { color: #606366; } .cm-s-darcula .CodeMirror-matchingbracket { background-color: #3B514D; color: #FFEF28 !important; font-weight: bold; } .cm-s-darcula div.CodeMirror-selected { background: #214283; } .CodeMirror-hints.darcula { font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; color: #9C9E9E; background-color: #3B3E3F !important; } .CodeMirror-hints.darcula .CodeMirror-hint-active { background-color: #494D4E !important; color: #9C9E9E !important; } ================================================ FILE: third_party/CodeMirror/theme/dracula.css ================================================ /* Name: dracula Author: Michael Kaminsky (http://github.com/mkaminsky11) Original dracula color scheme by Zeno Rocha (https://github.com/zenorocha/dracula-theme) */ .cm-s-dracula.CodeMirror, .cm-s-dracula .CodeMirror-gutters { background-color: #282a36 !important; color: #f8f8f2 !important; border: none; } .cm-s-dracula .CodeMirror-gutters { color: #282a36; } .cm-s-dracula .CodeMirror-cursor { border-left: solid thin #f8f8f0; } .cm-s-dracula .CodeMirror-linenumber { color: #6D8A88; } .cm-s-dracula .CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } .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); } .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); } .cm-s-dracula span.cm-comment { color: #6272a4; } .cm-s-dracula span.cm-string, .cm-s-dracula span.cm-string-2 { color: #f1fa8c; } .cm-s-dracula span.cm-number { color: #bd93f9; } .cm-s-dracula span.cm-variable { color: #50fa7b; } .cm-s-dracula span.cm-variable-2 { color: white; } .cm-s-dracula span.cm-def { color: #50fa7b; } .cm-s-dracula span.cm-operator { color: #ff79c6; } .cm-s-dracula span.cm-keyword { color: #ff79c6; } .cm-s-dracula span.cm-atom { color: #bd93f9; } .cm-s-dracula span.cm-meta { color: #f8f8f2; } .cm-s-dracula span.cm-tag { color: #ff79c6; } .cm-s-dracula span.cm-attribute { color: #50fa7b; } .cm-s-dracula span.cm-qualifier { color: #50fa7b; } .cm-s-dracula span.cm-property { color: #66d9ef; } .cm-s-dracula span.cm-builtin { color: #50fa7b; } .cm-s-dracula span.cm-variable-3, .cm-s-dracula span.cm-type { color: #ffb86c; } .cm-s-dracula .CodeMirror-activeline-background { background: rgba(255,255,255,0.1); } .cm-s-dracula .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/duotone-dark.css ================================================ /* Name: DuoTone-Dark Author: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes) CodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/) */ .cm-s-duotone-dark.CodeMirror { background: #2a2734; color: #6c6783; } .cm-s-duotone-dark div.CodeMirror-selected { background: #545167!important; } .cm-s-duotone-dark .CodeMirror-gutters { background: #2a2734; border-right: 0px; } .cm-s-duotone-dark .CodeMirror-linenumber { color: #545167; } /* begin cursor */ .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; } .cm-s-duotone-dark .CodeMirror-activeline-background { background: #363342; /* background: #36334280; */ opacity: .5;} .cm-s-duotone-dark .cm-fat-cursor .CodeMirror-cursor { background: #ffad5c; /* background: #ffad5c80; */ opacity: .5;} /* end cursor */ .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; } .cm-s-duotone-dark span.cm-property { color: #9a86fd; } .cm-s-duotone-dark span.cm-punctuation, .cm-s-duotone-dark span.cm-unit, .cm-s-duotone-dark span.cm-negative { color: #e09142; } .cm-s-duotone-dark span.cm-string { color: #ffb870; } .cm-s-duotone-dark span.cm-operator { color: #ffad5c; } .cm-s-duotone-dark span.cm-positive { color: #6a51e6; } .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; } .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; } .cm-s-duotone-dark span.cm-bracket, .cm-s-duotone-dark span.cm-comment { color: #6c6783; } /* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */ .cm-s-duotone-dark span.cm-error, .cm-s-duotone-dark span.cm-invalidchar { color: #f00; } .cm-s-duotone-dark span.cm-header { font-weight: normal; } .cm-s-duotone-dark .CodeMirror-matchingbracket { text-decoration: underline; color: #eeebff !important; } ================================================ FILE: third_party/CodeMirror/theme/duotone-light.css ================================================ /* Name: DuoTone-Light Author: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes) CodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/) */ .cm-s-duotone-light.CodeMirror { background: #faf8f5; color: #b29762; } .cm-s-duotone-light div.CodeMirror-selected { background: #e3dcce !important; } .cm-s-duotone-light .CodeMirror-gutters { background: #faf8f5; border-right: 0px; } .cm-s-duotone-light .CodeMirror-linenumber { color: #cdc4b1; } /* begin cursor */ .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; } .cm-s-duotone-light .CodeMirror-activeline-background { background: #e3dcce; /* background: #e3dcce80; */ opacity: .5; } .cm-s-duotone-light .cm-fat-cursor .CodeMirror-cursor { background: #93abdc; /* #93abdc80; */ opacity: .5; } /* end cursor */ .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; } .cm-s-duotone-light span.cm-property { color: #b29762; } .cm-s-duotone-light span.cm-punctuation, .cm-s-duotone-light span.cm-unit, .cm-s-duotone-light span.cm-negative { color: #063289; } .cm-s-duotone-light span.cm-string, .cm-s-duotone-light span.cm-operator { color: #1659df; } .cm-s-duotone-light span.cm-positive { color: #896724; } .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; } .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; } .cm-s-duotone-light span.cm-bracket, .cm-s-duotone-light span.cm-comment { color: #b6ad9a; } /* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */ /* .cm-s-duotone-light span.cm-error { background: #896724; color: #728fcb; } */ .cm-s-duotone-light span.cm-error, .cm-s-duotone-light span.cm-invalidchar { color: #f00; } .cm-s-duotone-light span.cm-header { font-weight: normal; } .cm-s-duotone-light .CodeMirror-matchingbracket { text-decoration: underline; color: #faf8f5 !important; } ================================================ FILE: third_party/CodeMirror/theme/eclipse.css ================================================ .cm-s-eclipse span.cm-meta { color: #FF1717; } .cm-s-eclipse span.cm-keyword { line-height: 1em; font-weight: bold; color: #7F0055; } .cm-s-eclipse span.cm-atom { color: #219; } .cm-s-eclipse span.cm-number { color: #164; } .cm-s-eclipse span.cm-def { color: #00f; } .cm-s-eclipse span.cm-variable { color: black; } .cm-s-eclipse span.cm-variable-2 { color: #0000C0; } .cm-s-eclipse span.cm-variable-3, .cm-s-eclipse span.cm-type { color: #0000C0; } .cm-s-eclipse span.cm-property { color: black; } .cm-s-eclipse span.cm-operator { color: black; } .cm-s-eclipse span.cm-comment { color: #3F7F5F; } .cm-s-eclipse span.cm-string { color: #2A00FF; } .cm-s-eclipse span.cm-string-2 { color: #f50; } .cm-s-eclipse span.cm-qualifier { color: #555; } .cm-s-eclipse span.cm-builtin { color: #30a; } .cm-s-eclipse span.cm-bracket { color: #cc7; } .cm-s-eclipse span.cm-tag { color: #170; } .cm-s-eclipse span.cm-attribute { color: #00c; } .cm-s-eclipse span.cm-link { color: #219; } .cm-s-eclipse span.cm-error { color: #f00; } .cm-s-eclipse .CodeMirror-activeline-background { background: #e8f2ff; } .cm-s-eclipse .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; } ================================================ FILE: third_party/CodeMirror/theme/elegant.css ================================================ .cm-s-elegant span.cm-number, .cm-s-elegant span.cm-string, .cm-s-elegant span.cm-atom { color: #762; } .cm-s-elegant span.cm-comment { color: #262; font-style: italic; line-height: 1em; } .cm-s-elegant span.cm-meta { color: #555; font-style: italic; line-height: 1em; } .cm-s-elegant span.cm-variable { color: black; } .cm-s-elegant span.cm-variable-2 { color: #b11; } .cm-s-elegant span.cm-qualifier { color: #555; } .cm-s-elegant span.cm-keyword { color: #730; } .cm-s-elegant span.cm-builtin { color: #30a; } .cm-s-elegant span.cm-link { color: #762; } .cm-s-elegant span.cm-error { background-color: #fdd; } .cm-s-elegant .CodeMirror-activeline-background { background: #e8f2ff; } .cm-s-elegant .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; } ================================================ FILE: third_party/CodeMirror/theme/erlang-dark.css ================================================ .cm-s-erlang-dark.CodeMirror { background: #002240; color: white; } .cm-s-erlang-dark div.CodeMirror-selected { background: #b36539; } .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); } .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); } .cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } .cm-s-erlang-dark .CodeMirror-guttermarker { color: white; } .cm-s-erlang-dark .CodeMirror-guttermarker-subtle { color: #d0d0d0; } .cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; } .cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-erlang-dark span.cm-quote { color: #ccc; } .cm-s-erlang-dark span.cm-atom { color: #f133f1; } .cm-s-erlang-dark span.cm-attribute { color: #ff80e1; } .cm-s-erlang-dark span.cm-bracket { color: #ff9d00; } .cm-s-erlang-dark span.cm-builtin { color: #eaa; } .cm-s-erlang-dark span.cm-comment { color: #77f; } .cm-s-erlang-dark span.cm-def { color: #e7a; } .cm-s-erlang-dark span.cm-keyword { color: #ffee80; } .cm-s-erlang-dark span.cm-meta { color: #50fefe; } .cm-s-erlang-dark span.cm-number { color: #ffd0d0; } .cm-s-erlang-dark span.cm-operator { color: #d55; } .cm-s-erlang-dark span.cm-property { color: #ccc; } .cm-s-erlang-dark span.cm-qualifier { color: #ccc; } .cm-s-erlang-dark span.cm-special { color: #ffbbbb; } .cm-s-erlang-dark span.cm-string { color: #3ad900; } .cm-s-erlang-dark span.cm-string-2 { color: #ccc; } .cm-s-erlang-dark span.cm-tag { color: #9effff; } .cm-s-erlang-dark span.cm-variable { color: #50fe50; } .cm-s-erlang-dark span.cm-variable-2 { color: #e0e; } .cm-s-erlang-dark span.cm-variable-3, .cm-s-erlang-dark span.cm-type { color: #ccc; } .cm-s-erlang-dark span.cm-error { color: #9d1e15; } .cm-s-erlang-dark .CodeMirror-activeline-background { background: #013461; } .cm-s-erlang-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/gruvbox-dark.css ================================================ /* Name: gruvbox-dark Author: kRkk (https://github.com/krkk) Original gruvbox color scheme by Pavel Pertsev (https://github.com/morhetz/gruvbox) */ .cm-s-gruvbox-dark.CodeMirror, .cm-s-gruvbox-dark .CodeMirror-gutters { background-color: #282828; color: #bdae93; } .cm-s-gruvbox-dark .CodeMirror-gutters {background: #282828; border-right: 0px;} .cm-s-gruvbox-dark .CodeMirror-linenumber {color: #7c6f64;} .cm-s-gruvbox-dark .CodeMirror-cursor { border-left: 1px solid #ebdbb2; } .cm-s-gruvbox-dark div.CodeMirror-selected { background: #928374; } .cm-s-gruvbox-dark span.cm-meta { color: #83a598; } .cm-s-gruvbox-dark span.cm-comment { color: #928374; } .cm-s-gruvbox-dark span.cm-number, span.cm-atom { color: #d3869b; } .cm-s-gruvbox-dark span.cm-keyword { color: #f84934; } .cm-s-gruvbox-dark span.cm-variable { color: #ebdbb2; } .cm-s-gruvbox-dark span.cm-variable-2 { color: #ebdbb2; } .cm-s-gruvbox-dark span.cm-variable-3, .cm-s-gruvbox-dark span.cm-type { color: #fabd2f; } .cm-s-gruvbox-dark span.cm-operator { color: #ebdbb2; } .cm-s-gruvbox-dark span.cm-callee { color: #ebdbb2; } .cm-s-gruvbox-dark span.cm-def { color: #ebdbb2; } .cm-s-gruvbox-dark span.cm-property { color: #ebdbb2; } .cm-s-gruvbox-dark span.cm-string { color: #b8bb26; } .cm-s-gruvbox-dark span.cm-string-2 { color: #8ec07c; } .cm-s-gruvbox-dark span.cm-qualifier { color: #8ec07c; } .cm-s-gruvbox-dark span.cm-attribute { color: #8ec07c; } .cm-s-gruvbox-dark .CodeMirror-activeline-background { background: #3c3836; } .cm-s-gruvbox-dark .CodeMirror-matchingbracket { background: #928374; color:#282828 !important; } .cm-s-gruvbox-dark span.cm-builtin { color: #fe8019; } .cm-s-gruvbox-dark span.cm-tag { color: #fe8019; } ================================================ FILE: third_party/CodeMirror/theme/hopscotch.css ================================================ /* Name: Hopscotch Author: Jan T. Sott CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-hopscotch.CodeMirror {background: #322931; color: #d5d3d5;} .cm-s-hopscotch div.CodeMirror-selected {background: #433b42 !important;} .cm-s-hopscotch .CodeMirror-gutters {background: #322931; border-right: 0px;} .cm-s-hopscotch .CodeMirror-linenumber {color: #797379;} .cm-s-hopscotch .CodeMirror-cursor {border-left: 1px solid #989498 !important;} .cm-s-hopscotch span.cm-comment {color: #b33508;} .cm-s-hopscotch span.cm-atom {color: #c85e7c;} .cm-s-hopscotch span.cm-number {color: #c85e7c;} .cm-s-hopscotch span.cm-property, .cm-s-hopscotch span.cm-attribute {color: #8fc13e;} .cm-s-hopscotch span.cm-keyword {color: #dd464c;} .cm-s-hopscotch span.cm-string {color: #fdcc59;} .cm-s-hopscotch span.cm-variable {color: #8fc13e;} .cm-s-hopscotch span.cm-variable-2 {color: #1290bf;} .cm-s-hopscotch span.cm-def {color: #fd8b19;} .cm-s-hopscotch span.cm-error {background: #dd464c; color: #989498;} .cm-s-hopscotch span.cm-bracket {color: #d5d3d5;} .cm-s-hopscotch span.cm-tag {color: #dd464c;} .cm-s-hopscotch span.cm-link {color: #c85e7c;} .cm-s-hopscotch .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} .cm-s-hopscotch .CodeMirror-activeline-background { background: #302020; } ================================================ FILE: third_party/CodeMirror/theme/icecoder.css ================================================ /* ICEcoder default theme by Matt Pass, used in code editor available at https://icecoder.net */ .cm-s-icecoder { color: #666; background: #1d1d1b; } .cm-s-icecoder span.cm-keyword { color: #eee; font-weight:bold; } /* off-white 1 */ .cm-s-icecoder span.cm-atom { color: #e1c76e; } /* yellow */ .cm-s-icecoder span.cm-number { color: #6cb5d9; } /* blue */ .cm-s-icecoder span.cm-def { color: #b9ca4a; } /* green */ .cm-s-icecoder span.cm-variable { color: #6cb5d9; } /* blue */ .cm-s-icecoder span.cm-variable-2 { color: #cc1e5c; } /* pink */ .cm-s-icecoder span.cm-variable-3, .cm-s-icecoder span.cm-type { color: #f9602c; } /* orange */ .cm-s-icecoder span.cm-property { color: #eee; } /* off-white 1 */ .cm-s-icecoder span.cm-operator { color: #9179bb; } /* purple */ .cm-s-icecoder span.cm-comment { color: #97a3aa; } /* grey-blue */ .cm-s-icecoder span.cm-string { color: #b9ca4a; } /* green */ .cm-s-icecoder span.cm-string-2 { color: #6cb5d9; } /* blue */ .cm-s-icecoder span.cm-meta { color: #555; } /* grey */ .cm-s-icecoder span.cm-qualifier { color: #555; } /* grey */ .cm-s-icecoder span.cm-builtin { color: #214e7b; } /* bright blue */ .cm-s-icecoder span.cm-bracket { color: #cc7; } /* grey-yellow */ .cm-s-icecoder span.cm-tag { color: #e8e8e8; } /* off-white 2 */ .cm-s-icecoder span.cm-attribute { color: #099; } /* teal */ .cm-s-icecoder span.cm-header { color: #6a0d6a; } /* purple-pink */ .cm-s-icecoder span.cm-quote { color: #186718; } /* dark green */ .cm-s-icecoder span.cm-hr { color: #888; } /* mid-grey */ .cm-s-icecoder span.cm-link { color: #e1c76e; } /* yellow */ .cm-s-icecoder span.cm-error { color: #d00; } /* red */ .cm-s-icecoder .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-icecoder div.CodeMirror-selected { color: #fff; background: #037; } .cm-s-icecoder .CodeMirror-gutters { background: #1d1d1b; min-width: 41px; border-right: 0; } .cm-s-icecoder .CodeMirror-linenumber { color: #555; cursor: default; } .cm-s-icecoder .CodeMirror-matchingbracket { color: #fff !important; background: #555 !important; } .cm-s-icecoder .CodeMirror-activeline-background { background: #000; } ================================================ FILE: third_party/CodeMirror/theme/idea.css ================================================ /** Name: IDEA default theme From IntelliJ IDEA by JetBrains */ .cm-s-idea span.cm-meta { color: #808000; } .cm-s-idea span.cm-number { color: #0000FF; } .cm-s-idea span.cm-keyword { line-height: 1em; font-weight: bold; color: #000080; } .cm-s-idea span.cm-atom { font-weight: bold; color: #000080; } .cm-s-idea span.cm-def { color: #000000; } .cm-s-idea span.cm-variable { color: black; } .cm-s-idea span.cm-variable-2 { color: black; } .cm-s-idea span.cm-variable-3, .cm-s-idea span.cm-type { color: black; } .cm-s-idea span.cm-property { color: black; } .cm-s-idea span.cm-operator { color: black; } .cm-s-idea span.cm-comment { color: #808080; } .cm-s-idea span.cm-string { color: #008000; } .cm-s-idea span.cm-string-2 { color: #008000; } .cm-s-idea span.cm-qualifier { color: #555; } .cm-s-idea span.cm-error { color: #FF0000; } .cm-s-idea span.cm-attribute { color: #0000FF; } .cm-s-idea span.cm-tag { color: #000080; } .cm-s-idea span.cm-link { color: #0000FF; } .cm-s-idea .CodeMirror-activeline-background { background: #FFFAE3; } .cm-s-idea span.cm-builtin { color: #30a; } .cm-s-idea span.cm-bracket { color: #cc7; } .cm-s-idea { font-family: Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif;} .cm-s-idea .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; } .CodeMirror-hints.idea { font-family: Menlo, Monaco, Consolas, 'Courier New', monospace; color: #616569; background-color: #ebf3fd !important; } .CodeMirror-hints.idea .CodeMirror-hint-active { background-color: #a2b8c9 !important; color: #5c6065 !important; } ================================================ FILE: third_party/CodeMirror/theme/isotope.css ================================================ /* Name: Isotope Author: David Desandro / Jan T. Sott CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-isotope.CodeMirror {background: #000000; color: #e0e0e0;} .cm-s-isotope div.CodeMirror-selected {background: #404040 !important;} .cm-s-isotope .CodeMirror-gutters {background: #000000; border-right: 0px;} .cm-s-isotope .CodeMirror-linenumber {color: #808080;} .cm-s-isotope .CodeMirror-cursor {border-left: 1px solid #c0c0c0 !important;} .cm-s-isotope span.cm-comment {color: #3300ff;} .cm-s-isotope span.cm-atom {color: #cc00ff;} .cm-s-isotope span.cm-number {color: #cc00ff;} .cm-s-isotope span.cm-property, .cm-s-isotope span.cm-attribute {color: #33ff00;} .cm-s-isotope span.cm-keyword {color: #ff0000;} .cm-s-isotope span.cm-string {color: #ff0099;} .cm-s-isotope span.cm-variable {color: #33ff00;} .cm-s-isotope span.cm-variable-2 {color: #0066ff;} .cm-s-isotope span.cm-def {color: #ff9900;} .cm-s-isotope span.cm-error {background: #ff0000; color: #c0c0c0;} .cm-s-isotope span.cm-bracket {color: #e0e0e0;} .cm-s-isotope span.cm-tag {color: #ff0000;} .cm-s-isotope span.cm-link {color: #cc00ff;} .cm-s-isotope .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} .cm-s-isotope .CodeMirror-activeline-background { background: #202020; } ================================================ FILE: third_party/CodeMirror/theme/lesser-dark.css ================================================ /* http://lesscss.org/ dark theme Ported to CodeMirror by Peter Kroon */ .cm-s-lesser-dark { line-height: 1.3em; } .cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; } .cm-s-lesser-dark div.CodeMirror-selected { background: #45443B; } /* 33322B*/ .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); } .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); } .cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/ .cm-s-lesser-dark.CodeMirror span.CodeMirror-matchingbracket { color: #7EFC7E; }/*65FC65*/ .cm-s-lesser-dark .CodeMirror-gutters { background: #262626; border-right:1px solid #aaa; } .cm-s-lesser-dark .CodeMirror-guttermarker { color: #599eff; } .cm-s-lesser-dark .CodeMirror-guttermarker-subtle { color: #777; } .cm-s-lesser-dark .CodeMirror-linenumber { color: #777; } .cm-s-lesser-dark span.cm-header { color: #a0a; } .cm-s-lesser-dark span.cm-quote { color: #090; } .cm-s-lesser-dark span.cm-keyword { color: #599eff; } .cm-s-lesser-dark span.cm-atom { color: #C2B470; } .cm-s-lesser-dark span.cm-number { color: #B35E4D; } .cm-s-lesser-dark span.cm-def { color: white; } .cm-s-lesser-dark span.cm-variable { color:#D9BF8C; } .cm-s-lesser-dark span.cm-variable-2 { color: #669199; } .cm-s-lesser-dark span.cm-variable-3, .cm-s-lesser-dark span.cm-type { color: white; } .cm-s-lesser-dark span.cm-property { color: #92A75C; } .cm-s-lesser-dark span.cm-operator { color: #92A75C; } .cm-s-lesser-dark span.cm-comment { color: #666; } .cm-s-lesser-dark span.cm-string { color: #BCD279; } .cm-s-lesser-dark span.cm-string-2 { color: #f50; } .cm-s-lesser-dark span.cm-meta { color: #738C73; } .cm-s-lesser-dark span.cm-qualifier { color: #555; } .cm-s-lesser-dark span.cm-builtin { color: #ff9e59; } .cm-s-lesser-dark span.cm-bracket { color: #EBEFE7; } .cm-s-lesser-dark span.cm-tag { color: #669199; } .cm-s-lesser-dark span.cm-attribute { color: #81a4d5; } .cm-s-lesser-dark span.cm-hr { color: #999; } .cm-s-lesser-dark span.cm-link { color: #00c; } .cm-s-lesser-dark span.cm-error { color: #9d1e15; } .cm-s-lesser-dark .CodeMirror-activeline-background { background: #3C3A3A; } .cm-s-lesser-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/liquibyte.css ================================================ .cm-s-liquibyte.CodeMirror { background-color: #000; color: #fff; line-height: 1.2em; font-size: 1em; } .cm-s-liquibyte .CodeMirror-focused .cm-matchhighlight { text-decoration: underline; text-decoration-color: #0f0; text-decoration-style: wavy; } .cm-s-liquibyte .cm-trailingspace { text-decoration: line-through; text-decoration-color: #f00; text-decoration-style: dotted; } .cm-s-liquibyte .cm-tab { text-decoration: line-through; text-decoration-color: #404040; text-decoration-style: dotted; } .cm-s-liquibyte .CodeMirror-gutters { background-color: #262626; border-right: 1px solid #505050; padding-right: 0.8em; } .cm-s-liquibyte .CodeMirror-gutter-elt div { font-size: 1.2em; } .cm-s-liquibyte .CodeMirror-guttermarker { } .cm-s-liquibyte .CodeMirror-guttermarker-subtle { } .cm-s-liquibyte .CodeMirror-linenumber { color: #606060; padding-left: 0; } .cm-s-liquibyte .CodeMirror-cursor { border-left: 1px solid #eee; } .cm-s-liquibyte span.cm-comment { color: #008000; } .cm-s-liquibyte span.cm-def { color: #ffaf40; font-weight: bold; } .cm-s-liquibyte span.cm-keyword { color: #c080ff; font-weight: bold; } .cm-s-liquibyte span.cm-builtin { color: #ffaf40; font-weight: bold; } .cm-s-liquibyte span.cm-variable { color: #5967ff; font-weight: bold; } .cm-s-liquibyte span.cm-string { color: #ff8000; } .cm-s-liquibyte span.cm-number { color: #0f0; font-weight: bold; } .cm-s-liquibyte span.cm-atom { color: #bf3030; font-weight: bold; } .cm-s-liquibyte span.cm-variable-2 { color: #007f7f; font-weight: bold; } .cm-s-liquibyte span.cm-variable-3, .cm-s-liquibyte span.cm-type { color: #c080ff; font-weight: bold; } .cm-s-liquibyte span.cm-property { color: #999; font-weight: bold; } .cm-s-liquibyte span.cm-operator { color: #fff; } .cm-s-liquibyte span.cm-meta { color: #0f0; } .cm-s-liquibyte span.cm-qualifier { color: #fff700; font-weight: bold; } .cm-s-liquibyte span.cm-bracket { color: #cc7; } .cm-s-liquibyte span.cm-tag { color: #ff0; font-weight: bold; } .cm-s-liquibyte span.cm-attribute { color: #c080ff; font-weight: bold; } .cm-s-liquibyte span.cm-error { color: #f00; } .cm-s-liquibyte div.CodeMirror-selected { background-color: rgba(255, 0, 0, 0.25); } .cm-s-liquibyte span.cm-compilation { background-color: rgba(255, 255, 255, 0.12); } .cm-s-liquibyte .CodeMirror-activeline-background { background-color: rgba(0, 255, 0, 0.15); } /* Default styles for common addons */ .cm-s-liquibyte .CodeMirror span.CodeMirror-matchingbracket { color: #0f0; font-weight: bold; } .cm-s-liquibyte .CodeMirror span.CodeMirror-nonmatchingbracket { color: #f00; font-weight: bold; } .CodeMirror-matchingtag { background-color: rgba(150, 255, 0, .3); } /* Scrollbars */ /* Simple */ .cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div:hover, .cm-s-liquibyte div.CodeMirror-simplescroll-vertical div:hover { background-color: rgba(80, 80, 80, .7); } .cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div, .cm-s-liquibyte div.CodeMirror-simplescroll-vertical div { background-color: rgba(80, 80, 80, .3); border: 1px solid #404040; border-radius: 5px; } .cm-s-liquibyte div.CodeMirror-simplescroll-vertical div { border-top: 1px solid #404040; border-bottom: 1px solid #404040; } .cm-s-liquibyte div.CodeMirror-simplescroll-horizontal div { border-left: 1px solid #404040; border-right: 1px solid #404040; } .cm-s-liquibyte div.CodeMirror-simplescroll-vertical { background-color: #262626; } .cm-s-liquibyte div.CodeMirror-simplescroll-horizontal { background-color: #262626; border-top: 1px solid #404040; } /* Overlay */ .cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div, div.CodeMirror-overlayscroll-vertical div { background-color: #404040; border-radius: 5px; } .cm-s-liquibyte div.CodeMirror-overlayscroll-vertical div { border: 1px solid #404040; } .cm-s-liquibyte div.CodeMirror-overlayscroll-horizontal div { border: 1px solid #404040; } ================================================ FILE: third_party/CodeMirror/theme/lucario.css ================================================ /* Name: lucario Author: Raphael Amorim Original Lucario color scheme (https://github.com/raphamorim/lucario) */ .cm-s-lucario.CodeMirror, .cm-s-lucario .CodeMirror-gutters { background-color: #2b3e50 !important; color: #f8f8f2 !important; border: none; } .cm-s-lucario .CodeMirror-gutters { color: #2b3e50; } .cm-s-lucario .CodeMirror-cursor { border-left: solid thin #E6C845; } .cm-s-lucario .CodeMirror-linenumber { color: #f8f8f2; } .cm-s-lucario .CodeMirror-selected { background: #243443; } .cm-s-lucario .CodeMirror-line::selection, .cm-s-lucario .CodeMirror-line > span::selection, .cm-s-lucario .CodeMirror-line > span > span::selection { background: #243443; } .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; } .cm-s-lucario span.cm-comment { color: #5c98cd; } .cm-s-lucario span.cm-string, .cm-s-lucario span.cm-string-2 { color: #E6DB74; } .cm-s-lucario span.cm-number { color: #ca94ff; } .cm-s-lucario span.cm-variable { color: #f8f8f2; } .cm-s-lucario span.cm-variable-2 { color: #f8f8f2; } .cm-s-lucario span.cm-def { color: #72C05D; } .cm-s-lucario span.cm-operator { color: #66D9EF; } .cm-s-lucario span.cm-keyword { color: #ff6541; } .cm-s-lucario span.cm-atom { color: #bd93f9; } .cm-s-lucario span.cm-meta { color: #f8f8f2; } .cm-s-lucario span.cm-tag { color: #ff6541; } .cm-s-lucario span.cm-attribute { color: #66D9EF; } .cm-s-lucario span.cm-qualifier { color: #72C05D; } .cm-s-lucario span.cm-property { color: #f8f8f2; } .cm-s-lucario span.cm-builtin { color: #72C05D; } .cm-s-lucario span.cm-variable-3, .cm-s-lucario span.cm-type { color: #ffb86c; } .cm-s-lucario .CodeMirror-activeline-background { background: #243443; } .cm-s-lucario .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/material.css ================================================ /* Name: material Author: Michael Kaminsky (http://github.com/mkaminsky11) Original material color scheme by Mattia Astorino (https://github.com/equinusocio/material-theme) */ .cm-s-material.CodeMirror { background-color: #263238; color: rgba(233, 237, 237, 1); } .cm-s-material .CodeMirror-gutters { background: #263238; color: rgb(83,127,126); border: none; } .cm-s-material .CodeMirror-guttermarker, .cm-s-material .CodeMirror-guttermarker-subtle, .cm-s-material .CodeMirror-linenumber { color: rgb(83,127,126); } .cm-s-material .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } .cm-s-material div.CodeMirror-selected { background: rgba(255, 255, 255, 0.15); } .cm-s-material.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } .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); } .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); } .cm-s-material .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0); } .cm-s-material .cm-keyword { color: rgba(199, 146, 234, 1); } .cm-s-material .cm-operator { color: rgba(233, 237, 237, 1); } .cm-s-material .cm-variable-2 { color: #80CBC4; } .cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #82B1FF; } .cm-s-material .cm-builtin { color: #DECB6B; } .cm-s-material .cm-atom { color: #F77669; } .cm-s-material .cm-number { color: #F77669; } .cm-s-material .cm-def { color: rgba(233, 237, 237, 1); } .cm-s-material .cm-string { color: #C3E88D; } .cm-s-material .cm-string-2 { color: #80CBC4; } .cm-s-material .cm-comment { color: #546E7A; } .cm-s-material .cm-variable { color: #82B1FF; } .cm-s-material .cm-tag { color: #80CBC4; } .cm-s-material .cm-meta { color: #80CBC4; } .cm-s-material .cm-attribute { color: #FFCB6B; } .cm-s-material .cm-property { color: #80CBAE; } .cm-s-material .cm-qualifier { color: #DECB6B; } .cm-s-material .cm-variable-3, .cm-s-material .cm-type { color: #DECB6B; } .cm-s-material .cm-tag { color: rgba(255, 83, 112, 1); } .cm-s-material .cm-error { color: rgba(255, 255, 255, 1.0); background-color: #EC5F67; } .cm-s-material .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/mbo.css ================================================ /****************************************************************/ /* Based on mbonaci's Brackets mbo theme */ /* https://github.com/mbonaci/global/blob/master/Mbo.tmTheme */ /* Create your own: http://tmtheme-editor.herokuapp.com */ /****************************************************************/ .cm-s-mbo.CodeMirror { background: #2c2c2c; color: #ffffec; } .cm-s-mbo div.CodeMirror-selected { background: #716C62; } .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); } .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); } .cm-s-mbo .CodeMirror-gutters { background: #4e4e4e; border-right: 0px; } .cm-s-mbo .CodeMirror-guttermarker { color: white; } .cm-s-mbo .CodeMirror-guttermarker-subtle { color: grey; } .cm-s-mbo .CodeMirror-linenumber { color: #dadada; } .cm-s-mbo .CodeMirror-cursor { border-left: 1px solid #ffffec; } .cm-s-mbo span.cm-comment { color: #95958a; } .cm-s-mbo span.cm-atom { color: #00a8c6; } .cm-s-mbo span.cm-number { color: #00a8c6; } .cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute { color: #9ddfe9; } .cm-s-mbo span.cm-keyword { color: #ffb928; } .cm-s-mbo span.cm-string { color: #ffcf6c; } .cm-s-mbo span.cm-string.cm-property { color: #ffffec; } .cm-s-mbo span.cm-variable { color: #ffffec; } .cm-s-mbo span.cm-variable-2 { color: #00a8c6; } .cm-s-mbo span.cm-def { color: #ffffec; } .cm-s-mbo span.cm-bracket { color: #fffffc; font-weight: bold; } .cm-s-mbo span.cm-tag { color: #9ddfe9; } .cm-s-mbo span.cm-link { color: #f54b07; } .cm-s-mbo span.cm-error { border-bottom: #636363; color: #ffffec; } .cm-s-mbo span.cm-qualifier { color: #ffffec; } .cm-s-mbo .CodeMirror-activeline-background { background: #494b41; } .cm-s-mbo .CodeMirror-matchingbracket { color: #ffb928 !important; } .cm-s-mbo .CodeMirror-matchingtag { background: rgba(255, 255, 255, .37); } ================================================ FILE: third_party/CodeMirror/theme/mdn-like.css ================================================ /* MDN-LIKE Theme - Mozilla Ported to CodeMirror by Peter Kroon Report bugs/issues here: https://github.com/codemirror/CodeMirror/issues GitHub: @peterkroon The mdn-like theme is inspired on the displayed code examples at: https://developer.mozilla.org/en-US/docs/Web/CSS/animation */ .cm-s-mdn-like.CodeMirror { color: #999; background-color: #fff; } .cm-s-mdn-like div.CodeMirror-selected { background: #cfc; } .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; } .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; } .cm-s-mdn-like .CodeMirror-gutters { background: #f8f8f8; border-left: 6px solid rgba(0,83,159,0.65); color: #333; } .cm-s-mdn-like .CodeMirror-linenumber { color: #aaa; padding-left: 8px; } .cm-s-mdn-like .CodeMirror-cursor { border-left: 2px solid #222; } .cm-s-mdn-like .cm-keyword { color: #6262FF; } .cm-s-mdn-like .cm-atom { color: #F90; } .cm-s-mdn-like .cm-number { color: #ca7841; } .cm-s-mdn-like .cm-def { color: #8DA6CE; } .cm-s-mdn-like span.cm-variable-2, .cm-s-mdn-like span.cm-tag { color: #690; } .cm-s-mdn-like span.cm-variable-3, .cm-s-mdn-like span.cm-def, .cm-s-mdn-like span.cm-type { color: #07a; } .cm-s-mdn-like .cm-variable { color: #07a; } .cm-s-mdn-like .cm-property { color: #905; } .cm-s-mdn-like .cm-qualifier { color: #690; } .cm-s-mdn-like .cm-operator { color: #cda869; } .cm-s-mdn-like .cm-comment { color:#777; font-weight:normal; } .cm-s-mdn-like .cm-string { color:#07a; font-style:italic; } .cm-s-mdn-like .cm-string-2 { color:#bd6b18; } /*?*/ .cm-s-mdn-like .cm-meta { color: #000; } /*?*/ .cm-s-mdn-like .cm-builtin { color: #9B7536; } /*?*/ .cm-s-mdn-like .cm-tag { color: #997643; } .cm-s-mdn-like .cm-attribute { color: #d6bb6d; } /*?*/ .cm-s-mdn-like .cm-header { color: #FF6400; } .cm-s-mdn-like .cm-hr { color: #AEAEAE; } .cm-s-mdn-like .cm-link { color:#ad9361; font-style:italic; text-decoration:none; } .cm-s-mdn-like .cm-error { border-bottom: 1px solid red; } div.cm-s-mdn-like .CodeMirror-activeline-background { background: #efefff; } div.cm-s-mdn-like span.CodeMirror-matchingbracket { outline:1px solid grey; color: inherit; } .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=); } ================================================ FILE: third_party/CodeMirror/theme/midnight.css ================================================ /* Based on the theme at http://bonsaiden.github.com/JavaScript-Garden */ /**/ .cm-s-midnight span.CodeMirror-matchhighlight { background: #494949; } .cm-s-midnight.CodeMirror-focused span.CodeMirror-matchhighlight { background: #314D67 !important; } /**/ .cm-s-midnight .CodeMirror-activeline-background { background: #253540; } .cm-s-midnight.CodeMirror { background: #0F192A; color: #D1EDFF; } .cm-s-midnight div.CodeMirror-selected { background: #314D67; } .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); } .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); } .cm-s-midnight .CodeMirror-gutters { background: #0F192A; border-right: 1px solid; } .cm-s-midnight .CodeMirror-guttermarker { color: white; } .cm-s-midnight .CodeMirror-guttermarker-subtle { color: #d0d0d0; } .cm-s-midnight .CodeMirror-linenumber { color: #D0D0D0; } .cm-s-midnight .CodeMirror-cursor { border-left: 1px solid #F8F8F0; } .cm-s-midnight span.cm-comment { color: #428BDD; } .cm-s-midnight span.cm-atom { color: #AE81FF; } .cm-s-midnight span.cm-number { color: #D1EDFF; } .cm-s-midnight span.cm-property, .cm-s-midnight span.cm-attribute { color: #A6E22E; } .cm-s-midnight span.cm-keyword { color: #E83737; } .cm-s-midnight span.cm-string { color: #1DC116; } .cm-s-midnight span.cm-variable { color: #FFAA3E; } .cm-s-midnight span.cm-variable-2 { color: #FFAA3E; } .cm-s-midnight span.cm-def { color: #4DD; } .cm-s-midnight span.cm-bracket { color: #D1EDFF; } .cm-s-midnight span.cm-tag { color: #449; } .cm-s-midnight span.cm-link { color: #AE81FF; } .cm-s-midnight span.cm-error { background: #F92672; color: #F8F8F0; } .cm-s-midnight .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/monokai.css ================================================ /* Based on Sublime Text's Monokai theme */ .cm-s-monokai.CodeMirror { background: #272822; color: #f8f8f2; } .cm-s-monokai div.CodeMirror-selected { background: #49483E; } .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); } .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); } .cm-s-monokai .CodeMirror-gutters { background: #272822; border-right: 0px; } .cm-s-monokai .CodeMirror-guttermarker { color: white; } .cm-s-monokai .CodeMirror-guttermarker-subtle { color: #d0d0d0; } .cm-s-monokai .CodeMirror-linenumber { color: #d0d0d0; } .cm-s-monokai .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } .cm-s-monokai span.cm-comment { color: #75715e; } .cm-s-monokai span.cm-atom { color: #ae81ff; } .cm-s-monokai span.cm-number { color: #ae81ff; } .cm-s-monokai span.cm-comment.cm-attribute { color: #97b757; } .cm-s-monokai span.cm-comment.cm-def { color: #bc9262; } .cm-s-monokai span.cm-comment.cm-tag { color: #bc6283; } .cm-s-monokai span.cm-comment.cm-type { color: #5998a6; } .cm-s-monokai span.cm-property, .cm-s-monokai span.cm-attribute { color: #a6e22e; } .cm-s-monokai span.cm-keyword { color: #f92672; } .cm-s-monokai span.cm-builtin { color: #66d9ef; } .cm-s-monokai span.cm-string { color: #e6db74; } .cm-s-monokai span.cm-variable { color: #f8f8f2; } .cm-s-monokai span.cm-variable-2 { color: #9effff; } .cm-s-monokai span.cm-variable-3, .cm-s-monokai span.cm-type { color: #66d9ef; } .cm-s-monokai span.cm-def { color: #fd971f; } .cm-s-monokai span.cm-bracket { color: #f8f8f2; } .cm-s-monokai span.cm-tag { color: #f92672; } .cm-s-monokai span.cm-header { color: #ae81ff; } .cm-s-monokai span.cm-link { color: #ae81ff; } .cm-s-monokai span.cm-error { background: #f92672; color: #f8f8f0; } .cm-s-monokai .CodeMirror-activeline-background { background: #373831; } .cm-s-monokai .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/neat.css ================================================ .cm-s-neat span.cm-comment { color: #a86; } .cm-s-neat span.cm-keyword { line-height: 1em; font-weight: bold; color: blue; } .cm-s-neat span.cm-string { color: #a22; } .cm-s-neat span.cm-builtin { line-height: 1em; font-weight: bold; color: #077; } .cm-s-neat span.cm-special { line-height: 1em; font-weight: bold; color: #0aa; } .cm-s-neat span.cm-variable { color: black; } .cm-s-neat span.cm-number, .cm-s-neat span.cm-atom { color: #3a3; } .cm-s-neat span.cm-meta { color: #555; } .cm-s-neat span.cm-link { color: #3a3; } .cm-s-neat .CodeMirror-activeline-background { background: #e8f2ff; } .cm-s-neat .CodeMirror-matchingbracket { outline:1px solid grey; color:black !important; } ================================================ FILE: third_party/CodeMirror/theme/neo.css ================================================ /* neo theme for codemirror */ /* Color scheme */ .cm-s-neo.CodeMirror { background-color:#ffffff; color:#2e383c; line-height:1.4375; } .cm-s-neo .cm-comment { color:#75787b; } .cm-s-neo .cm-keyword, .cm-s-neo .cm-property { color:#1d75b3; } .cm-s-neo .cm-atom,.cm-s-neo .cm-number { color:#75438a; } .cm-s-neo .cm-node,.cm-s-neo .cm-tag { color:#9c3328; } .cm-s-neo .cm-string { color:#b35e14; } .cm-s-neo .cm-variable,.cm-s-neo .cm-qualifier { color:#047d65; } /* Editor styling */ .cm-s-neo pre { padding:0; } .cm-s-neo .CodeMirror-gutters { border:none; border-right:10px solid transparent; background-color:transparent; } .cm-s-neo .CodeMirror-linenumber { padding:0; color:#e0e2e5; } .cm-s-neo .CodeMirror-guttermarker { color: #1d75b3; } .cm-s-neo .CodeMirror-guttermarker-subtle { color: #e0e2e5; } .cm-s-neo .CodeMirror-cursor { width: auto; border: 0; background: rgba(155,157,162,0.37); z-index: 1; } ================================================ FILE: third_party/CodeMirror/theme/night.css ================================================ /* Loosely based on the Midnight Textmate theme */ .cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; } .cm-s-night div.CodeMirror-selected { background: #447; } .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); } .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); } .cm-s-night .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } .cm-s-night .CodeMirror-guttermarker { color: white; } .cm-s-night .CodeMirror-guttermarker-subtle { color: #bbb; } .cm-s-night .CodeMirror-linenumber { color: #f8f8f8; } .cm-s-night .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-night span.cm-comment { color: #8900d1; } .cm-s-night span.cm-atom { color: #845dc4; } .cm-s-night span.cm-number, .cm-s-night span.cm-attribute { color: #ffd500; } .cm-s-night span.cm-keyword { color: #599eff; } .cm-s-night span.cm-string { color: #37f14a; } .cm-s-night span.cm-meta { color: #7678e2; } .cm-s-night span.cm-variable-2, .cm-s-night span.cm-tag { color: #99b2ff; } .cm-s-night span.cm-variable-3, .cm-s-night span.cm-def, .cm-s-night span.cm-type { color: white; } .cm-s-night span.cm-bracket { color: #8da6ce; } .cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; } .cm-s-night span.cm-link { color: #845dc4; } .cm-s-night span.cm-error { color: #9d1e15; } .cm-s-night .CodeMirror-activeline-background { background: #1C005A; } .cm-s-night .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/oceanic-next.css ================================================ /* Name: oceanic-next Author: Filype Pereira (https://github.com/fpereira1) Original oceanic-next color scheme by Dmitri Voronianski (https://github.com/voronianski/oceanic-next-color-scheme) */ .cm-s-oceanic-next.CodeMirror { background: #304148; color: #f8f8f2; } .cm-s-oceanic-next div.CodeMirror-selected { background: rgba(101, 115, 126, 0.33); } .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); } .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); } .cm-s-oceanic-next .CodeMirror-gutters { background: #304148; border-right: 10px; } .cm-s-oceanic-next .CodeMirror-guttermarker { color: white; } .cm-s-oceanic-next .CodeMirror-guttermarker-subtle { color: #d0d0d0; } .cm-s-oceanic-next .CodeMirror-linenumber { color: #d0d0d0; } .cm-s-oceanic-next .CodeMirror-cursor { border-left: 1px solid #f8f8f0; } .cm-s-oceanic-next span.cm-comment { color: #65737E; } .cm-s-oceanic-next span.cm-atom { color: #C594C5; } .cm-s-oceanic-next span.cm-number { color: #F99157; } .cm-s-oceanic-next span.cm-property { color: #99C794; } .cm-s-oceanic-next span.cm-attribute, .cm-s-oceanic-next span.cm-keyword { color: #C594C5; } .cm-s-oceanic-next span.cm-builtin { color: #66d9ef; } .cm-s-oceanic-next span.cm-string { color: #99C794; } .cm-s-oceanic-next span.cm-variable, .cm-s-oceanic-next span.cm-variable-2, .cm-s-oceanic-next span.cm-variable-3 { color: #f8f8f2; } .cm-s-oceanic-next span.cm-def { color: #6699CC; } .cm-s-oceanic-next span.cm-bracket { color: #5FB3B3; } .cm-s-oceanic-next span.cm-tag { color: #C594C5; } .cm-s-oceanic-next span.cm-header { color: #C594C5; } .cm-s-oceanic-next span.cm-link { color: #C594C5; } .cm-s-oceanic-next span.cm-error { background: #C594C5; color: #f8f8f0; } .cm-s-oceanic-next .CodeMirror-activeline-background { background: rgba(101, 115, 126, 0.33); } .cm-s-oceanic-next .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/panda-syntax.css ================================================ /* Name: Panda Syntax Author: Siamak Mokhtari (http://github.com/siamak/) CodeMirror template by Siamak Mokhtari (https://github.com/siamak/atom-panda-syntax) */ .cm-s-panda-syntax { background: #292A2B; color: #E6E6E6; line-height: 1.5; font-family: 'Operator Mono', 'Source Sans Pro', Menlo, Monaco, Consolas, Courier New, monospace; } .cm-s-panda-syntax .CodeMirror-cursor { border-color: #ff2c6d; } .cm-s-panda-syntax .CodeMirror-activeline-background { background: rgba(99, 123, 156, 0.1); } .cm-s-panda-syntax .CodeMirror-selected { background: #FFF; } .cm-s-panda-syntax .cm-comment { font-style: italic; color: #676B79; } .cm-s-panda-syntax .cm-operator { color: #f3f3f3; } .cm-s-panda-syntax .cm-string { color: #19F9D8; } .cm-s-panda-syntax .cm-string-2 { color: #FFB86C; } .cm-s-panda-syntax .cm-tag { color: #ff2c6d; } .cm-s-panda-syntax .cm-meta { color: #b084eb; } .cm-s-panda-syntax .cm-number { color: #FFB86C; } .cm-s-panda-syntax .cm-atom { color: #ff2c6d; } .cm-s-panda-syntax .cm-keyword { color: #FF75B5; } .cm-s-panda-syntax .cm-variable { color: #ffb86c; } .cm-s-panda-syntax .cm-variable-2 { color: #ff9ac1; } .cm-s-panda-syntax .cm-variable-3, .cm-s-panda-syntax .cm-type { color: #ff9ac1; } .cm-s-panda-syntax .cm-def { color: #e6e6e6; } .cm-s-panda-syntax .cm-property { color: #f3f3f3; } .cm-s-panda-syntax .cm-unit { color: #ffb86c; } .cm-s-panda-syntax .cm-attribute { color: #ffb86c; } .cm-s-panda-syntax .CodeMirror-matchingbracket { border-bottom: 1px dotted #19F9D8; padding-bottom: 2px; color: #e6e6e6; } .cm-s-panda-syntax .CodeMirror-gutters { background: #292a2b; border-right-color: rgba(255, 255, 255, 0.1); } .cm-s-panda-syntax .CodeMirror-linenumber { color: #e6e6e6; opacity: 0.6; } ================================================ FILE: third_party/CodeMirror/theme/paraiso-dark.css ================================================ /* Name: Paraíso (Dark) Author: Jan T. Sott Color scheme by Jan T. Sott (https://github.com/idleberg/Paraiso-CodeMirror) Inspired by the art of Rubens LP (http://www.rubenslp.com.br) */ .cm-s-paraiso-dark.CodeMirror { background: #2f1e2e; color: #b9b6b0; } .cm-s-paraiso-dark div.CodeMirror-selected { background: #41323f; } .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); } .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); } .cm-s-paraiso-dark .CodeMirror-gutters { background: #2f1e2e; border-right: 0px; } .cm-s-paraiso-dark .CodeMirror-guttermarker { color: #ef6155; } .cm-s-paraiso-dark .CodeMirror-guttermarker-subtle { color: #776e71; } .cm-s-paraiso-dark .CodeMirror-linenumber { color: #776e71; } .cm-s-paraiso-dark .CodeMirror-cursor { border-left: 1px solid #8d8687; } .cm-s-paraiso-dark span.cm-comment { color: #e96ba8; } .cm-s-paraiso-dark span.cm-atom { color: #815ba4; } .cm-s-paraiso-dark span.cm-number { color: #815ba4; } .cm-s-paraiso-dark span.cm-property, .cm-s-paraiso-dark span.cm-attribute { color: #48b685; } .cm-s-paraiso-dark span.cm-keyword { color: #ef6155; } .cm-s-paraiso-dark span.cm-string { color: #fec418; } .cm-s-paraiso-dark span.cm-variable { color: #48b685; } .cm-s-paraiso-dark span.cm-variable-2 { color: #06b6ef; } .cm-s-paraiso-dark span.cm-def { color: #f99b15; } .cm-s-paraiso-dark span.cm-bracket { color: #b9b6b0; } .cm-s-paraiso-dark span.cm-tag { color: #ef6155; } .cm-s-paraiso-dark span.cm-link { color: #815ba4; } .cm-s-paraiso-dark span.cm-error { background: #ef6155; color: #8d8687; } .cm-s-paraiso-dark .CodeMirror-activeline-background { background: #4D344A; } .cm-s-paraiso-dark .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/paraiso-light.css ================================================ /* Name: Paraíso (Light) Author: Jan T. Sott Color scheme by Jan T. Sott (https://github.com/idleberg/Paraiso-CodeMirror) Inspired by the art of Rubens LP (http://www.rubenslp.com.br) */ .cm-s-paraiso-light.CodeMirror { background: #e7e9db; color: #41323f; } .cm-s-paraiso-light div.CodeMirror-selected { background: #b9b6b0; } .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; } .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; } .cm-s-paraiso-light .CodeMirror-gutters { background: #e7e9db; border-right: 0px; } .cm-s-paraiso-light .CodeMirror-guttermarker { color: black; } .cm-s-paraiso-light .CodeMirror-guttermarker-subtle { color: #8d8687; } .cm-s-paraiso-light .CodeMirror-linenumber { color: #8d8687; } .cm-s-paraiso-light .CodeMirror-cursor { border-left: 1px solid #776e71; } .cm-s-paraiso-light span.cm-comment { color: #e96ba8; } .cm-s-paraiso-light span.cm-atom { color: #815ba4; } .cm-s-paraiso-light span.cm-number { color: #815ba4; } .cm-s-paraiso-light span.cm-property, .cm-s-paraiso-light span.cm-attribute { color: #48b685; } .cm-s-paraiso-light span.cm-keyword { color: #ef6155; } .cm-s-paraiso-light span.cm-string { color: #fec418; } .cm-s-paraiso-light span.cm-variable { color: #48b685; } .cm-s-paraiso-light span.cm-variable-2 { color: #06b6ef; } .cm-s-paraiso-light span.cm-def { color: #f99b15; } .cm-s-paraiso-light span.cm-bracket { color: #41323f; } .cm-s-paraiso-light span.cm-tag { color: #ef6155; } .cm-s-paraiso-light span.cm-link { color: #815ba4; } .cm-s-paraiso-light span.cm-error { background: #ef6155; color: #776e71; } .cm-s-paraiso-light .CodeMirror-activeline-background { background: #CFD1C4; } .cm-s-paraiso-light .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/pastel-on-dark.css ================================================ /** * Pastel On Dark theme ported from ACE editor * @license MIT * @copyright AtomicPages LLC 2014 * @author Dennis Thompson, AtomicPages LLC * @version 1.1 * @source https://github.com/atomicpages/codemirror-pastel-on-dark-theme */ .cm-s-pastel-on-dark.CodeMirror { background: #2c2827; color: #8F938F; line-height: 1.5; } .cm-s-pastel-on-dark div.CodeMirror-selected { background: rgba(221,240,255,0.2); } .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); } .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); } .cm-s-pastel-on-dark .CodeMirror-gutters { background: #34302f; border-right: 0px; padding: 0 3px; } .cm-s-pastel-on-dark .CodeMirror-guttermarker { color: white; } .cm-s-pastel-on-dark .CodeMirror-guttermarker-subtle { color: #8F938F; } .cm-s-pastel-on-dark .CodeMirror-linenumber { color: #8F938F; } .cm-s-pastel-on-dark .CodeMirror-cursor { border-left: 1px solid #A7A7A7; } .cm-s-pastel-on-dark span.cm-comment { color: #A6C6FF; } .cm-s-pastel-on-dark span.cm-atom { color: #DE8E30; } .cm-s-pastel-on-dark span.cm-number { color: #CCCCCC; } .cm-s-pastel-on-dark span.cm-property { color: #8F938F; } .cm-s-pastel-on-dark span.cm-attribute { color: #a6e22e; } .cm-s-pastel-on-dark span.cm-keyword { color: #AEB2F8; } .cm-s-pastel-on-dark span.cm-string { color: #66A968; } .cm-s-pastel-on-dark span.cm-variable { color: #AEB2F8; } .cm-s-pastel-on-dark span.cm-variable-2 { color: #BEBF55; } .cm-s-pastel-on-dark span.cm-variable-3, .cm-s-pastel-on-dark span.cm-type { color: #DE8E30; } .cm-s-pastel-on-dark span.cm-def { color: #757aD8; } .cm-s-pastel-on-dark span.cm-bracket { color: #f8f8f2; } .cm-s-pastel-on-dark span.cm-tag { color: #C1C144; } .cm-s-pastel-on-dark span.cm-link { color: #ae81ff; } .cm-s-pastel-on-dark span.cm-qualifier,.cm-s-pastel-on-dark span.cm-builtin { color: #C1C144; } .cm-s-pastel-on-dark span.cm-error { background: #757aD8; color: #f8f8f0; } .cm-s-pastel-on-dark .CodeMirror-activeline-background { background: rgba(255, 255, 255, 0.031); } .cm-s-pastel-on-dark .CodeMirror-matchingbracket { border: 1px solid rgba(255,255,255,0.25); color: #8F938F !important; margin: -1px -1px 0 -1px; } ================================================ FILE: third_party/CodeMirror/theme/railscasts.css ================================================ /* Name: Railscasts Author: Ryan Bates (http://railscasts.com) CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-railscasts.CodeMirror {background: #2b2b2b; color: #f4f1ed;} .cm-s-railscasts div.CodeMirror-selected {background: #272935 !important;} .cm-s-railscasts .CodeMirror-gutters {background: #2b2b2b; border-right: 0px;} .cm-s-railscasts .CodeMirror-linenumber {color: #5a647e;} .cm-s-railscasts .CodeMirror-cursor {border-left: 1px solid #d4cfc9 !important;} .cm-s-railscasts span.cm-comment {color: #bc9458;} .cm-s-railscasts span.cm-atom {color: #b6b3eb;} .cm-s-railscasts span.cm-number {color: #b6b3eb;} .cm-s-railscasts span.cm-property, .cm-s-railscasts span.cm-attribute {color: #a5c261;} .cm-s-railscasts span.cm-keyword {color: #da4939;} .cm-s-railscasts span.cm-string {color: #ffc66d;} .cm-s-railscasts span.cm-variable {color: #a5c261;} .cm-s-railscasts span.cm-variable-2 {color: #6d9cbe;} .cm-s-railscasts span.cm-def {color: #cc7833;} .cm-s-railscasts span.cm-error {background: #da4939; color: #d4cfc9;} .cm-s-railscasts span.cm-bracket {color: #f4f1ed;} .cm-s-railscasts span.cm-tag {color: #da4939;} .cm-s-railscasts span.cm-link {color: #b6b3eb;} .cm-s-railscasts .CodeMirror-matchingbracket { text-decoration: underline; color: white !important;} .cm-s-railscasts .CodeMirror-activeline-background { background: #303040; } ================================================ FILE: third_party/CodeMirror/theme/rubyblue.css ================================================ .cm-s-rubyblue.CodeMirror { background: #112435; color: white; } .cm-s-rubyblue div.CodeMirror-selected { background: #38566F; } .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); } .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); } .cm-s-rubyblue .CodeMirror-gutters { background: #1F4661; border-right: 7px solid #3E7087; } .cm-s-rubyblue .CodeMirror-guttermarker { color: white; } .cm-s-rubyblue .CodeMirror-guttermarker-subtle { color: #3E7087; } .cm-s-rubyblue .CodeMirror-linenumber { color: white; } .cm-s-rubyblue .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-rubyblue span.cm-comment { color: #999; font-style:italic; line-height: 1em; } .cm-s-rubyblue span.cm-atom { color: #F4C20B; } .cm-s-rubyblue span.cm-number, .cm-s-rubyblue span.cm-attribute { color: #82C6E0; } .cm-s-rubyblue span.cm-keyword { color: #F0F; } .cm-s-rubyblue span.cm-string { color: #F08047; } .cm-s-rubyblue span.cm-meta { color: #F0F; } .cm-s-rubyblue span.cm-variable-2, .cm-s-rubyblue span.cm-tag { color: #7BD827; } .cm-s-rubyblue span.cm-variable-3, .cm-s-rubyblue span.cm-def, .cm-s-rubyblue span.cm-type { color: white; } .cm-s-rubyblue span.cm-bracket { color: #F0F; } .cm-s-rubyblue span.cm-link { color: #F4C20B; } .cm-s-rubyblue span.CodeMirror-matchingbracket { color:#F0F !important; } .cm-s-rubyblue span.cm-builtin, .cm-s-rubyblue span.cm-special { color: #FF9D00; } .cm-s-rubyblue span.cm-error { color: #AF2018; } .cm-s-rubyblue .CodeMirror-activeline-background { background: #173047; } ================================================ FILE: third_party/CodeMirror/theme/seti.css ================================================ /* Name: seti Author: Michael Kaminsky (http://github.com/mkaminsky11) Original seti color scheme by Jesse Weed (https://github.com/jesseweed/seti-syntax) */ .cm-s-seti.CodeMirror { background-color: #151718 !important; color: #CFD2D1 !important; border: none; } .cm-s-seti .CodeMirror-gutters { color: #404b53; background-color: #0E1112; border: none; } .cm-s-seti .CodeMirror-cursor { border-left: solid thin #f8f8f0; } .cm-s-seti .CodeMirror-linenumber { color: #6D8A88; } .cm-s-seti.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); } .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); } .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); } .cm-s-seti span.cm-comment { color: #41535b; } .cm-s-seti span.cm-string, .cm-s-seti span.cm-string-2 { color: #55b5db; } .cm-s-seti span.cm-number { color: #cd3f45; } .cm-s-seti span.cm-variable { color: #55b5db; } .cm-s-seti span.cm-variable-2 { color: #a074c4; } .cm-s-seti span.cm-def { color: #55b5db; } .cm-s-seti span.cm-keyword { color: #ff79c6; } .cm-s-seti span.cm-operator { color: #9fca56; } .cm-s-seti span.cm-keyword { color: #e6cd69; } .cm-s-seti span.cm-atom { color: #cd3f45; } .cm-s-seti span.cm-meta { color: #55b5db; } .cm-s-seti span.cm-tag { color: #55b5db; } .cm-s-seti span.cm-attribute { color: #9fca56; } .cm-s-seti span.cm-qualifier { color: #9fca56; } .cm-s-seti span.cm-property { color: #a074c4; } .cm-s-seti span.cm-variable-3, .cm-s-seti span.cm-type { color: #9fca56; } .cm-s-seti span.cm-builtin { color: #9fca56; } .cm-s-seti .CodeMirror-activeline-background { background: #101213; } .cm-s-seti .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/shadowfox.css ================================================ /* Name: shadowfox Author: overdodactyl (http://github.com/overdodactyl) Original shadowfox color scheme by Firefox */ .cm-s-shadowfox.CodeMirror { background: #2a2a2e; color: #b1b1b3; } .cm-s-shadowfox div.CodeMirror-selected { background: #353B48; } .cm-s-shadowfox .CodeMirror-line::selection, .cm-s-shadowfox .CodeMirror-line > span::selection, .cm-s-shadowfox .CodeMirror-line > span > span::selection { background: #353B48; } .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; } .cm-s-shadowfox .CodeMirror-gutters { background: #0c0c0d ; border-right: 1px solid #0c0c0d; } .cm-s-shadowfox .CodeMirror-guttermarker { color: #555; } .cm-s-shadowfox .CodeMirror-linenumber { color: #939393; } .cm-s-shadowfox .CodeMirror-cursor { border-left: 1px solid #fff; } .cm-s-shadowfox span.cm-comment { color: #939393; } .cm-s-shadowfox span.cm-atom { color: #FF7DE9; } .cm-s-shadowfox span.cm-quote { color: #FF7DE9; } .cm-s-shadowfox span.cm-builtin { color: #FF7DE9; } .cm-s-shadowfox span.cm-attribute { color: #FF7DE9; } .cm-s-shadowfox span.cm-keyword { color: #FF7DE9; } .cm-s-shadowfox span.cm-error { color: #FF7DE9; } .cm-s-shadowfox span.cm-number { color: #6B89FF; } .cm-s-shadowfox span.cm-string { color: #6B89FF; } .cm-s-shadowfox span.cm-string-2 { color: #6B89FF; } .cm-s-shadowfox span.cm-meta { color: #939393; } .cm-s-shadowfox span.cm-hr { color: #939393; } .cm-s-shadowfox span.cm-header { color: #75BFFF; } .cm-s-shadowfox span.cm-qualifier { color: #75BFFF; } .cm-s-shadowfox span.cm-variable-2 { color: #75BFFF; } .cm-s-shadowfox span.cm-property { color: #86DE74; } .cm-s-shadowfox span.cm-def { color: #75BFFF; } .cm-s-shadowfox span.cm-bracket { color: #75BFFF; } .cm-s-shadowfox span.cm-tag { color: #75BFFF; } .cm-s-shadowfox span.cm-link:visited { color: #75BFFF; } .cm-s-shadowfox span.cm-variable { color: #B98EFF; } .cm-s-shadowfox span.cm-variable-3 { color: #d7d7db; } .cm-s-shadowfox span.cm-link { color: #737373; } .cm-s-shadowfox span.cm-operator { color: #b1b1b3; } .cm-s-shadowfox span.cm-special { color: #d7d7db; } .cm-s-shadowfox .CodeMirror-activeline-background { background: rgba(185, 215, 253, .15) } .cm-s-shadowfox .CodeMirror-matchingbracket { outline: solid 1px rgba(255, 255, 255, .25); color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/solarized.css ================================================ /* Solarized theme for code-mirror http://ethanschoonover.com/solarized */ /* Solarized color palette http://ethanschoonover.com/solarized/img/solarized-palette.png */ .solarized.base03 { color: #002b36; } .solarized.base02 { color: #073642; } .solarized.base01 { color: #586e75; } .solarized.base00 { color: #657b83; } .solarized.base0 { color: #839496; } .solarized.base1 { color: #93a1a1; } .solarized.base2 { color: #eee8d5; } .solarized.base3 { color: #fdf6e3; } .solarized.solar-yellow { color: #b58900; } .solarized.solar-orange { color: #cb4b16; } .solarized.solar-red { color: #dc322f; } .solarized.solar-magenta { color: #d33682; } .solarized.solar-violet { color: #6c71c4; } .solarized.solar-blue { color: #268bd2; } .solarized.solar-cyan { color: #2aa198; } .solarized.solar-green { color: #859900; } /* Color scheme for code-mirror */ .cm-s-solarized { line-height: 1.45em; color-profile: sRGB; rendering-intent: auto; } .cm-s-solarized.cm-s-dark { color: #839496; background-color: #002b36; text-shadow: #002b36 0 1px; } .cm-s-solarized.cm-s-light { background-color: #fdf6e3; color: #657b83; text-shadow: #eee8d5 0 1px; } .cm-s-solarized .CodeMirror-widget { text-shadow: none; } .cm-s-solarized .cm-header { color: #586e75; } .cm-s-solarized .cm-quote { color: #93a1a1; } .cm-s-solarized .cm-keyword { color: #cb4b16; } .cm-s-solarized .cm-atom { color: #d33682; } .cm-s-solarized .cm-number { color: #d33682; } .cm-s-solarized .cm-def { color: #2aa198; } .cm-s-solarized .cm-variable { color: #839496; } .cm-s-solarized .cm-variable-2 { color: #b58900; } .cm-s-solarized .cm-variable-3, .cm-s-solarized .cm-type { color: #6c71c4; } .cm-s-solarized .cm-property { color: #2aa198; } .cm-s-solarized .cm-operator { color: #6c71c4; } .cm-s-solarized .cm-comment { color: #586e75; font-style:italic; } .cm-s-solarized .cm-string { color: #859900; } .cm-s-solarized .cm-string-2 { color: #b58900; } .cm-s-solarized .cm-meta { color: #859900; } .cm-s-solarized .cm-qualifier { color: #b58900; } .cm-s-solarized .cm-builtin { color: #d33682; } .cm-s-solarized .cm-bracket { color: #cb4b16; } .cm-s-solarized .CodeMirror-matchingbracket { color: #859900; } .cm-s-solarized .CodeMirror-nonmatchingbracket { color: #dc322f; } .cm-s-solarized .cm-tag { color: #93a1a1; } .cm-s-solarized .cm-attribute { color: #2aa198; } .cm-s-solarized .cm-hr { color: transparent; border-top: 1px solid #586e75; display: block; } .cm-s-solarized .cm-link { color: #93a1a1; cursor: pointer; } .cm-s-solarized .cm-special { color: #6c71c4; } .cm-s-solarized .cm-em { color: #999; text-decoration: underline; text-decoration-style: dotted; } .cm-s-solarized .cm-error, .cm-s-solarized .cm-invalidchar { color: #586e75; border-bottom: 1px dotted #dc322f; } .cm-s-solarized.cm-s-dark div.CodeMirror-selected { background: #073642; } .cm-s-solarized.cm-s-dark.CodeMirror ::selection { background: rgba(7, 54, 66, 0.99); } .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); } .cm-s-solarized.cm-s-light div.CodeMirror-selected { background: #eee8d5; } .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; } .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; } /* Editor styling */ /* Little shadow on the view-port of the buffer view */ .cm-s-solarized.CodeMirror { -moz-box-shadow: inset 7px 0 12px -6px #000; -webkit-box-shadow: inset 7px 0 12px -6px #000; box-shadow: inset 7px 0 12px -6px #000; } /* Remove gutter border */ .cm-s-solarized .CodeMirror-gutters { border-right: 0; } /* Gutter colors and line number styling based of color scheme (dark / light) */ /* Dark */ .cm-s-solarized.cm-s-dark .CodeMirror-gutters { background-color: #073642; } .cm-s-solarized.cm-s-dark .CodeMirror-linenumber { color: #586e75; text-shadow: #021014 0 -1px; } /* Light */ .cm-s-solarized.cm-s-light .CodeMirror-gutters { background-color: #eee8d5; } .cm-s-solarized.cm-s-light .CodeMirror-linenumber { color: #839496; } /* Common */ .cm-s-solarized .CodeMirror-linenumber { padding: 0 5px; } .cm-s-solarized .CodeMirror-guttermarker-subtle { color: #586e75; } .cm-s-solarized.cm-s-dark .CodeMirror-guttermarker { color: #ddd; } .cm-s-solarized.cm-s-light .CodeMirror-guttermarker { color: #cb4b16; } .cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text { color: #586e75; } /* Cursor */ .cm-s-solarized .CodeMirror-cursor { border-left: 1px solid #819090; } /* Fat cursor */ .cm-s-solarized.cm-s-light.cm-fat-cursor .CodeMirror-cursor { background: #77ee77; } .cm-s-solarized.cm-s-light .cm-animate-fat-cursor { background-color: #77ee77; } .cm-s-solarized.cm-s-dark.cm-fat-cursor .CodeMirror-cursor { background: #586e75; } .cm-s-solarized.cm-s-dark .cm-animate-fat-cursor { background-color: #586e75; } /* Active line */ .cm-s-solarized.cm-s-dark .CodeMirror-activeline-background { background: rgba(255, 255, 255, 0.06); } .cm-s-solarized.cm-s-light .CodeMirror-activeline-background { background: rgba(0, 0, 0, 0.06); } ================================================ FILE: third_party/CodeMirror/theme/ssms.css ================================================ .cm-s-ssms span.cm-keyword { color: blue; } .cm-s-ssms span.cm-comment { color: darkgreen; } .cm-s-ssms span.cm-string { color: red; } .cm-s-ssms span.cm-def { color: black; } .cm-s-ssms span.cm-variable { color: black; } .cm-s-ssms span.cm-variable-2 { color: black; } .cm-s-ssms span.cm-atom { color: darkgray; } .cm-s-ssms .CodeMirror-linenumber { color: teal; } .cm-s-ssms .CodeMirror-activeline-background { background: #ffffff; } .cm-s-ssms span.cm-string-2 { color: #FF00FF; } .cm-s-ssms span.cm-operator, .cm-s-ssms span.cm-bracket, .cm-s-ssms span.cm-punctuation { color: darkgray; } .cm-s-ssms .CodeMirror-gutters { border-right: 3px solid #ffee62; background-color: #ffffff; } .cm-s-ssms div.CodeMirror-selected { background: #ADD6FF; } ================================================ FILE: third_party/CodeMirror/theme/the-matrix.css ================================================ .cm-s-the-matrix.CodeMirror { background: #000000; color: #00FF00; } .cm-s-the-matrix div.CodeMirror-selected { background: #2D2D2D; } .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); } .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); } .cm-s-the-matrix .CodeMirror-gutters { background: #060; border-right: 2px solid #00FF00; } .cm-s-the-matrix .CodeMirror-guttermarker { color: #0f0; } .cm-s-the-matrix .CodeMirror-guttermarker-subtle { color: white; } .cm-s-the-matrix .CodeMirror-linenumber { color: #FFFFFF; } .cm-s-the-matrix .CodeMirror-cursor { border-left: 1px solid #00FF00; } .cm-s-the-matrix span.cm-keyword { color: #008803; font-weight: bold; } .cm-s-the-matrix span.cm-atom { color: #3FF; } .cm-s-the-matrix span.cm-number { color: #FFB94F; } .cm-s-the-matrix span.cm-def { color: #99C; } .cm-s-the-matrix span.cm-variable { color: #F6C; } .cm-s-the-matrix span.cm-variable-2 { color: #C6F; } .cm-s-the-matrix span.cm-variable-3, .cm-s-the-matrix span.cm-type { color: #96F; } .cm-s-the-matrix span.cm-property { color: #62FFA0; } .cm-s-the-matrix span.cm-operator { color: #999; } .cm-s-the-matrix span.cm-comment { color: #CCCCCC; } .cm-s-the-matrix span.cm-string { color: #39C; } .cm-s-the-matrix span.cm-meta { color: #C9F; } .cm-s-the-matrix span.cm-qualifier { color: #FFF700; } .cm-s-the-matrix span.cm-builtin { color: #30a; } .cm-s-the-matrix span.cm-bracket { color: #cc7; } .cm-s-the-matrix span.cm-tag { color: #FFBD40; } .cm-s-the-matrix span.cm-attribute { color: #FFF700; } .cm-s-the-matrix span.cm-error { color: #FF0000; } .cm-s-the-matrix .CodeMirror-activeline-background { background: #040; } ================================================ FILE: third_party/CodeMirror/theme/tomorrow-night-bright.css ================================================ /* Name: Tomorrow Night - Bright Author: Chris Kempson Port done by Gerard Braad */ .cm-s-tomorrow-night-bright.CodeMirror { background: #000000; color: #eaeaea; } .cm-s-tomorrow-night-bright div.CodeMirror-selected { background: #424242; } .cm-s-tomorrow-night-bright .CodeMirror-gutters { background: #000000; border-right: 0px; } .cm-s-tomorrow-night-bright .CodeMirror-guttermarker { color: #e78c45; } .cm-s-tomorrow-night-bright .CodeMirror-guttermarker-subtle { color: #777; } .cm-s-tomorrow-night-bright .CodeMirror-linenumber { color: #424242; } .cm-s-tomorrow-night-bright .CodeMirror-cursor { border-left: 1px solid #6A6A6A; } .cm-s-tomorrow-night-bright span.cm-comment { color: #d27b53; } .cm-s-tomorrow-night-bright span.cm-atom { color: #a16a94; } .cm-s-tomorrow-night-bright span.cm-number { color: #a16a94; } .cm-s-tomorrow-night-bright span.cm-property, .cm-s-tomorrow-night-bright span.cm-attribute { color: #99cc99; } .cm-s-tomorrow-night-bright span.cm-keyword { color: #d54e53; } .cm-s-tomorrow-night-bright span.cm-string { color: #e7c547; } .cm-s-tomorrow-night-bright span.cm-variable { color: #b9ca4a; } .cm-s-tomorrow-night-bright span.cm-variable-2 { color: #7aa6da; } .cm-s-tomorrow-night-bright span.cm-def { color: #e78c45; } .cm-s-tomorrow-night-bright span.cm-bracket { color: #eaeaea; } .cm-s-tomorrow-night-bright span.cm-tag { color: #d54e53; } .cm-s-tomorrow-night-bright span.cm-link { color: #a16a94; } .cm-s-tomorrow-night-bright span.cm-error { background: #d54e53; color: #6A6A6A; } .cm-s-tomorrow-night-bright .CodeMirror-activeline-background { background: #2a2a2a; } .cm-s-tomorrow-night-bright .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/tomorrow-night-eighties.css ================================================ /* Name: Tomorrow Night - Eighties Author: Chris Kempson CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror) Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16) */ .cm-s-tomorrow-night-eighties.CodeMirror { background: #000000; color: #CCCCCC; } .cm-s-tomorrow-night-eighties div.CodeMirror-selected { background: #2D2D2D; } .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); } .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); } .cm-s-tomorrow-night-eighties .CodeMirror-gutters { background: #000000; border-right: 0px; } .cm-s-tomorrow-night-eighties .CodeMirror-guttermarker { color: #f2777a; } .cm-s-tomorrow-night-eighties .CodeMirror-guttermarker-subtle { color: #777; } .cm-s-tomorrow-night-eighties .CodeMirror-linenumber { color: #515151; } .cm-s-tomorrow-night-eighties .CodeMirror-cursor { border-left: 1px solid #6A6A6A; } .cm-s-tomorrow-night-eighties span.cm-comment { color: #d27b53; } .cm-s-tomorrow-night-eighties span.cm-atom { color: #a16a94; } .cm-s-tomorrow-night-eighties span.cm-number { color: #a16a94; } .cm-s-tomorrow-night-eighties span.cm-property, .cm-s-tomorrow-night-eighties span.cm-attribute { color: #99cc99; } .cm-s-tomorrow-night-eighties span.cm-keyword { color: #f2777a; } .cm-s-tomorrow-night-eighties span.cm-string { color: #ffcc66; } .cm-s-tomorrow-night-eighties span.cm-variable { color: #99cc99; } .cm-s-tomorrow-night-eighties span.cm-variable-2 { color: #6699cc; } .cm-s-tomorrow-night-eighties span.cm-def { color: #f99157; } .cm-s-tomorrow-night-eighties span.cm-bracket { color: #CCCCCC; } .cm-s-tomorrow-night-eighties span.cm-tag { color: #f2777a; } .cm-s-tomorrow-night-eighties span.cm-link { color: #a16a94; } .cm-s-tomorrow-night-eighties span.cm-error { background: #f2777a; color: #6A6A6A; } .cm-s-tomorrow-night-eighties .CodeMirror-activeline-background { background: #343600; } .cm-s-tomorrow-night-eighties .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; } ================================================ FILE: third_party/CodeMirror/theme/ttcn.css ================================================ .cm-s-ttcn .cm-quote { color: #090; } .cm-s-ttcn .cm-negative { color: #d44; } .cm-s-ttcn .cm-positive { color: #292; } .cm-s-ttcn .cm-header, .cm-strong { font-weight: bold; } .cm-s-ttcn .cm-em { font-style: italic; } .cm-s-ttcn .cm-link { text-decoration: underline; } .cm-s-ttcn .cm-strikethrough { text-decoration: line-through; } .cm-s-ttcn .cm-header { color: #00f; font-weight: bold; } .cm-s-ttcn .cm-atom { color: #219; } .cm-s-ttcn .cm-attribute { color: #00c; } .cm-s-ttcn .cm-bracket { color: #997; } .cm-s-ttcn .cm-comment { color: #333333; } .cm-s-ttcn .cm-def { color: #00f; } .cm-s-ttcn .cm-em { font-style: italic; } .cm-s-ttcn .cm-error { color: #f00; } .cm-s-ttcn .cm-hr { color: #999; } .cm-s-ttcn .cm-invalidchar { color: #f00; } .cm-s-ttcn .cm-keyword { font-weight:bold; } .cm-s-ttcn .cm-link { color: #00c; text-decoration: underline; } .cm-s-ttcn .cm-meta { color: #555; } .cm-s-ttcn .cm-negative { color: #d44; } .cm-s-ttcn .cm-positive { color: #292; } .cm-s-ttcn .cm-qualifier { color: #555; } .cm-s-ttcn .cm-strikethrough { text-decoration: line-through; } .cm-s-ttcn .cm-string { color: #006400; } .cm-s-ttcn .cm-string-2 { color: #f50; } .cm-s-ttcn .cm-strong { font-weight: bold; } .cm-s-ttcn .cm-tag { color: #170; } .cm-s-ttcn .cm-variable { color: #8B2252; } .cm-s-ttcn .cm-variable-2 { color: #05a; } .cm-s-ttcn .cm-variable-3, .cm-s-ttcn .cm-type { color: #085; } .cm-s-ttcn .cm-invalidchar { color: #f00; } /* ASN */ .cm-s-ttcn .cm-accessTypes, .cm-s-ttcn .cm-compareTypes { color: #27408B; } .cm-s-ttcn .cm-cmipVerbs { color: #8B2252; } .cm-s-ttcn .cm-modifier { color:#D2691E; } .cm-s-ttcn .cm-status { color:#8B4545; } .cm-s-ttcn .cm-storage { color:#A020F0; } .cm-s-ttcn .cm-tags { color:#006400; } /* CFG */ .cm-s-ttcn .cm-externalCommands { color: #8B4545; font-weight:bold; } .cm-s-ttcn .cm-fileNCtrlMaskOptions, .cm-s-ttcn .cm-sectionTitle { color: #2E8B57; font-weight:bold; } /* TTCN */ .cm-s-ttcn .cm-booleanConsts, .cm-s-ttcn .cm-otherConsts, .cm-s-ttcn .cm-verdictConsts { color: #006400; } .cm-s-ttcn .cm-configOps, .cm-s-ttcn .cm-functionOps, .cm-s-ttcn .cm-portOps, .cm-s-ttcn .cm-sutOps, .cm-s-ttcn .cm-timerOps, .cm-s-ttcn .cm-verdictOps { color: #0000FF; } .cm-s-ttcn .cm-preprocessor, .cm-s-ttcn .cm-templateMatch, .cm-s-ttcn .cm-ttcn3Macros { color: #27408B; } .cm-s-ttcn .cm-types { color: #A52A2A; font-weight:bold; } .cm-s-ttcn .cm-visibilityModifiers { font-weight:bold; } ================================================ FILE: third_party/CodeMirror/theme/twilight.css ================================================ .cm-s-twilight.CodeMirror { background: #141414; color: #f7f7f7; } /**/ .cm-s-twilight div.CodeMirror-selected { background: #323232; } /**/ .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); } .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); } .cm-s-twilight .CodeMirror-gutters { background: #222; border-right: 1px solid #aaa; } .cm-s-twilight .CodeMirror-guttermarker { color: white; } .cm-s-twilight .CodeMirror-guttermarker-subtle { color: #aaa; } .cm-s-twilight .CodeMirror-linenumber { color: #aaa; } .cm-s-twilight .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-twilight .cm-keyword { color: #f9ee98; } /**/ .cm-s-twilight .cm-atom { color: #FC0; } .cm-s-twilight .cm-number { color: #ca7841; } /**/ .cm-s-twilight .cm-def { color: #8DA6CE; } .cm-s-twilight span.cm-variable-2, .cm-s-twilight span.cm-tag { color: #607392; } /**/ .cm-s-twilight span.cm-variable-3, .cm-s-twilight span.cm-def, .cm-s-twilight span.cm-type { color: #607392; } /**/ .cm-s-twilight .cm-operator { color: #cda869; } /**/ .cm-s-twilight .cm-comment { color:#777; font-style:italic; font-weight:normal; } /**/ .cm-s-twilight .cm-string { color:#8f9d6a; font-style:italic; } /**/ .cm-s-twilight .cm-string-2 { color:#bd6b18; } /*?*/ .cm-s-twilight .cm-meta { background-color:#141414; color:#f7f7f7; } /*?*/ .cm-s-twilight .cm-builtin { color: #cda869; } /*?*/ .cm-s-twilight .cm-tag { color: #997643; } /**/ .cm-s-twilight .cm-attribute { color: #d6bb6d; } /*?*/ .cm-s-twilight .cm-header { color: #FF6400; } .cm-s-twilight .cm-hr { color: #AEAEAE; } .cm-s-twilight .cm-link { color:#ad9361; font-style:italic; text-decoration:none; } /**/ .cm-s-twilight .cm-error { border-bottom: 1px solid red; } .cm-s-twilight .CodeMirror-activeline-background { background: #27282E; } .cm-s-twilight .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/vibrant-ink.css ================================================ /* Taken from the popular Visual Studio Vibrant Ink Schema */ .cm-s-vibrant-ink.CodeMirror { background: black; color: white; } .cm-s-vibrant-ink div.CodeMirror-selected { background: #35493c; } .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); } .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); } .cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } .cm-s-vibrant-ink .CodeMirror-guttermarker { color: white; } .cm-s-vibrant-ink .CodeMirror-guttermarker-subtle { color: #d0d0d0; } .cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; } .cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-vibrant-ink .cm-keyword { color: #CC7832; } .cm-s-vibrant-ink .cm-atom { color: #FC0; } .cm-s-vibrant-ink .cm-number { color: #FFEE98; } .cm-s-vibrant-ink .cm-def { color: #8DA6CE; } .cm-s-vibrant-ink span.cm-variable-2, .cm-s-vibrant span.cm-tag { color: #FFC66D; } .cm-s-vibrant-ink span.cm-variable-3, .cm-s-vibrant span.cm-def, .cm-s-vibrant span.cm-type { color: #FFC66D; } .cm-s-vibrant-ink .cm-operator { color: #888; } .cm-s-vibrant-ink .cm-comment { color: gray; font-weight: bold; } .cm-s-vibrant-ink .cm-string { color: #A5C25C; } .cm-s-vibrant-ink .cm-string-2 { color: red; } .cm-s-vibrant-ink .cm-meta { color: #D8FA3C; } .cm-s-vibrant-ink .cm-builtin { color: #8DA6CE; } .cm-s-vibrant-ink .cm-tag { color: #8DA6CE; } .cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; } .cm-s-vibrant-ink .cm-header { color: #FF6400; } .cm-s-vibrant-ink .cm-hr { color: #AEAEAE; } .cm-s-vibrant-ink .cm-link { color: blue; } .cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; } .cm-s-vibrant-ink .CodeMirror-activeline-background { background: #27282E; } .cm-s-vibrant-ink .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/xq-dark.css ================================================ /* Copyright (C) 2011 by MarkLogic Corporation Author: Mike Brevoort Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ .cm-s-xq-dark.CodeMirror { background: #0a001f; color: #f8f8f8; } .cm-s-xq-dark div.CodeMirror-selected { background: #27007A; } .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); } .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); } .cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } .cm-s-xq-dark .CodeMirror-guttermarker { color: #FFBD40; } .cm-s-xq-dark .CodeMirror-guttermarker-subtle { color: #f8f8f8; } .cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; } .cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-xq-dark span.cm-keyword { color: #FFBD40; } .cm-s-xq-dark span.cm-atom { color: #6C8CD5; } .cm-s-xq-dark span.cm-number { color: #164; } .cm-s-xq-dark span.cm-def { color: #FFF; text-decoration:underline; } .cm-s-xq-dark span.cm-variable { color: #FFF; } .cm-s-xq-dark span.cm-variable-2 { color: #EEE; } .cm-s-xq-dark span.cm-variable-3, .cm-s-xq-dark span.cm-type { color: #DDD; } .cm-s-xq-dark span.cm-property {} .cm-s-xq-dark span.cm-operator {} .cm-s-xq-dark span.cm-comment { color: gray; } .cm-s-xq-dark span.cm-string { color: #9FEE00; } .cm-s-xq-dark span.cm-meta { color: yellow; } .cm-s-xq-dark span.cm-qualifier { color: #FFF700; } .cm-s-xq-dark span.cm-builtin { color: #30a; } .cm-s-xq-dark span.cm-bracket { color: #cc7; } .cm-s-xq-dark span.cm-tag { color: #FFBD40; } .cm-s-xq-dark span.cm-attribute { color: #FFF700; } .cm-s-xq-dark span.cm-error { color: #f00; } .cm-s-xq-dark .CodeMirror-activeline-background { background: #27282E; } .cm-s-xq-dark .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; } ================================================ FILE: third_party/CodeMirror/theme/xq-light.css ================================================ /* Copyright (C) 2011 by MarkLogic Corporation Author: Mike Brevoort Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ .cm-s-xq-light span.cm-keyword { line-height: 1em; font-weight: bold; color: #5A5CAD; } .cm-s-xq-light span.cm-atom { color: #6C8CD5; } .cm-s-xq-light span.cm-number { color: #164; } .cm-s-xq-light span.cm-def { text-decoration:underline; } .cm-s-xq-light span.cm-variable { color: black; } .cm-s-xq-light span.cm-variable-2 { color:black; } .cm-s-xq-light span.cm-variable-3, .cm-s-xq-light span.cm-type { color: black; } .cm-s-xq-light span.cm-property {} .cm-s-xq-light span.cm-operator {} .cm-s-xq-light span.cm-comment { color: #0080FF; font-style: italic; } .cm-s-xq-light span.cm-string { color: red; } .cm-s-xq-light span.cm-meta { color: yellow; } .cm-s-xq-light span.cm-qualifier { color: grey; } .cm-s-xq-light span.cm-builtin { color: #7EA656; } .cm-s-xq-light span.cm-bracket { color: #cc7; } .cm-s-xq-light span.cm-tag { color: #3F7F7F; } .cm-s-xq-light span.cm-attribute { color: #7F007F; } .cm-s-xq-light span.cm-error { color: #f00; } .cm-s-xq-light .CodeMirror-activeline-background { background: #e8f2ff; } .cm-s-xq-light .CodeMirror-matchingbracket { outline:1px solid grey;color:black !important;background:yellow; } ================================================ FILE: third_party/CodeMirror/theme/yeti.css ================================================ /* Name: yeti Author: Michael Kaminsky (http://github.com/mkaminsky11) Original yeti color scheme by Jesse Weed (https://github.com/jesseweed/yeti-syntax) */ .cm-s-yeti.CodeMirror { background-color: #ECEAE8 !important; color: #d1c9c0 !important; border: none; } .cm-s-yeti .CodeMirror-gutters { color: #adaba6; background-color: #E5E1DB; border: none; } .cm-s-yeti .CodeMirror-cursor { border-left: solid thin #d1c9c0; } .cm-s-yeti .CodeMirror-linenumber { color: #adaba6; } .cm-s-yeti.CodeMirror-focused div.CodeMirror-selected { background: #DCD8D2; } .cm-s-yeti .CodeMirror-line::selection, .cm-s-yeti .CodeMirror-line > span::selection, .cm-s-yeti .CodeMirror-line > span > span::selection { background: #DCD8D2; } .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; } .cm-s-yeti span.cm-comment { color: #d4c8be; } .cm-s-yeti span.cm-string, .cm-s-yeti span.cm-string-2 { color: #96c0d8; } .cm-s-yeti span.cm-number { color: #a074c4; } .cm-s-yeti span.cm-variable { color: #55b5db; } .cm-s-yeti span.cm-variable-2 { color: #a074c4; } .cm-s-yeti span.cm-def { color: #55b5db; } .cm-s-yeti span.cm-operator { color: #9fb96e; } .cm-s-yeti span.cm-keyword { color: #9fb96e; } .cm-s-yeti span.cm-atom { color: #a074c4; } .cm-s-yeti span.cm-meta { color: #96c0d8; } .cm-s-yeti span.cm-tag { color: #96c0d8; } .cm-s-yeti span.cm-attribute { color: #9fb96e; } .cm-s-yeti span.cm-qualifier { color: #96c0d8; } .cm-s-yeti span.cm-property { color: #a074c4; } .cm-s-yeti span.cm-builtin { color: #a074c4; } .cm-s-yeti span.cm-variable-3, .cm-s-yeti span.cm-type { color: #96c0d8; } .cm-s-yeti .CodeMirror-activeline-background { background: #E7E4E0; } .cm-s-yeti .CodeMirror-matchingbracket { text-decoration: underline; } ================================================ FILE: third_party/CodeMirror/theme/zenburn.css ================================================ /** * " * Using Zenburn color palette from the Emacs Zenburn Theme * https://github.com/bbatsov/zenburn-emacs/blob/master/zenburn-theme.el * * Also using parts of https://github.com/xavi/coderay-lighttable-theme * " * From: https://github.com/wisenomad/zenburn-lighttable-theme/blob/master/zenburn.css */ .cm-s-zenburn .CodeMirror-gutters { background: #3f3f3f !important; } .cm-s-zenburn .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { color: #999; } .cm-s-zenburn .CodeMirror-cursor { border-left: 1px solid white; } .cm-s-zenburn { background-color: #3f3f3f; color: #dcdccc; } .cm-s-zenburn span.cm-builtin { color: #dcdccc; font-weight: bold; } .cm-s-zenburn span.cm-comment { color: #7f9f7f; } .cm-s-zenburn span.cm-keyword { color: #f0dfaf; font-weight: bold; } .cm-s-zenburn span.cm-atom { color: #bfebbf; } .cm-s-zenburn span.cm-def { color: #dcdccc; } .cm-s-zenburn span.cm-variable { color: #dfaf8f; } .cm-s-zenburn span.cm-variable-2 { color: #dcdccc; } .cm-s-zenburn span.cm-string { color: #cc9393; } .cm-s-zenburn span.cm-string-2 { color: #cc9393; } .cm-s-zenburn span.cm-number { color: #dcdccc; } .cm-s-zenburn span.cm-tag { color: #93e0e3; } .cm-s-zenburn span.cm-property { color: #dfaf8f; } .cm-s-zenburn span.cm-attribute { color: #dfaf8f; } .cm-s-zenburn span.cm-qualifier { color: #7cb8bb; } .cm-s-zenburn span.cm-meta { color: #f0dfaf; } .cm-s-zenburn span.cm-header { color: #f0efd0; } .cm-s-zenburn span.cm-operator { color: #f0efd0; } .cm-s-zenburn span.CodeMirror-matchingbracket { box-sizing: border-box; background: transparent; border-bottom: 1px solid; } .cm-s-zenburn span.CodeMirror-nonmatchingbracket { border-bottom: 1px solid; background: none; } .cm-s-zenburn .CodeMirror-activeline { background: #000000; } .cm-s-zenburn .CodeMirror-activeline-background { background: #000000; } .cm-s-zenburn div.CodeMirror-selected { background: #545454; } .cm-s-zenburn .CodeMirror-focused div.CodeMirror-selected { background: #4f4f4f; } ================================================ FILE: third_party/DMP/AUTHORS ================================================ # Below is a list of people and organizations that have contributed # to the Diff Match Patch project. Google Inc. Duncan Cross (Lua port) Jan Weiß (Objective C port) Matthaeus G. Chajdas (C# port) Mike Slemmer (C++ port) ================================================ FILE: third_party/DMP/LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: third_party/DMP/METADATA ================================================ name: "diff-match-patch" description: "Library required for synchronizing plain text." third_party { url { type: GIT value: "https://github.com/google/diff-match-patch" } version: "f7ec0851994c8989cfb709dbda202ad1881472d4" last_upgrade_date { year: 2018 month: 6 day: 18 } license_type: NOTICE } ================================================ FILE: third_party/DMP/diff_match_patch.py ================================================ #!/usr/bin/python2.4 from __future__ import division """Diff Match and Patch Copyright 2018 The diff-match-patch Authors. https://github.com/google/diff-match-patch Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ """Functions for diff, match and patch. Computes the difference between two texts to create a patch. Applies the patch onto another text, allowing for errors. """ __author__ = 'fraser@google.com (Neil Fraser)' import re import sys import time import urllib class diff_match_patch: """Class containing the diff, match and patch methods. Also contains the behaviour settings. """ def __init__(self): """Inits a diff_match_patch object with default settings. Redefine these in your program to override the defaults. """ # Number of seconds to map a diff before giving up (0 for infinity). self.Diff_Timeout = 1.0 # Cost of an empty edit operation in terms of edit characters. self.Diff_EditCost = 4 # At what point is no match declared (0.0 = perfection, 1.0 = very loose). self.Match_Threshold = 0.5 # How far to search for a match (0 = exact location, 1000+ = broad match). # A match this many characters away from the expected location will add # 1.0 to the score (0.0 is a perfect match). self.Match_Distance = 1000 # When deleting a large block of text (over ~64 characters), how close do # the contents have to be to match the expected contents. (0.0 = perfection, # 1.0 = very loose). Note that Match_Threshold controls how closely the # end points of a delete need to match. self.Patch_DeleteThreshold = 0.5 # Chunk size for context length. self.Patch_Margin = 4 # The number of bits in an int. # Python has no maximum, thus to disable patch splitting set to 0. # However to avoid long patches in certain pathological cases, use 32. # Multiple short patches (using native ints) are much faster than long ones. self.Match_MaxBits = 32 # DIFF FUNCTIONS # The data structure representing a diff is an array of tuples: # [(DIFF_DELETE, "Hello"), (DIFF_INSERT, "Goodbye"), (DIFF_EQUAL, " world.")] # which means: delete "Hello", add "Goodbye" and keep " world." DIFF_DELETE = -1 DIFF_INSERT = 1 DIFF_EQUAL = 0 def diff_main(self, text1, text2, checklines=True, deadline=None): """Find the differences between two texts. Simplifies the problem by stripping any common prefix or suffix off the texts before diffing. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Optional speedup flag. If present and false, then don't run a line-level diff first to identify the changed areas. Defaults to true, which does a faster, slightly less optimal diff. deadline: Optional time when the diff should be complete by. Used internally for recursive calls. Users should set DiffTimeout instead. Returns: Array of changes. """ # Set a deadline by which time the diff must be complete. if deadline == None: # Unlike in most languages, Python counts time in seconds. if self.Diff_Timeout <= 0: deadline = sys.maxint else: deadline = time.time() + self.Diff_Timeout # Check for null inputs. if text1 == None or text2 == None: raise ValueError("Null inputs. (diff_main)") # Check for equality (speedup). if text1 == text2: if text1: return [(self.DIFF_EQUAL, text1)] return [] # Trim off common prefix (speedup). commonlength = self.diff_commonPrefix(text1, text2) commonprefix = text1[:commonlength] text1 = text1[commonlength:] text2 = text2[commonlength:] # Trim off common suffix (speedup). commonlength = self.diff_commonSuffix(text1, text2) if commonlength == 0: commonsuffix = '' else: commonsuffix = text1[-commonlength:] text1 = text1[:-commonlength] text2 = text2[:-commonlength] # Compute the diff on the middle block. diffs = self.diff_compute(text1, text2, checklines, deadline) # Restore the prefix and suffix. if commonprefix: diffs[:0] = [(self.DIFF_EQUAL, commonprefix)] if commonsuffix: diffs.append((self.DIFF_EQUAL, commonsuffix)) self.diff_cleanupMerge(diffs) return diffs def diff_compute(self, text1, text2, checklines, deadline): """Find the differences between two texts. Assumes that the texts do not have any common prefix or suffix. Args: text1: Old string to be diffed. text2: New string to be diffed. checklines: Speedup flag. If false, then don't run a line-level diff first to identify the changed areas. If true, then run a faster, slightly less optimal diff. deadline: Time when the diff should be complete by. Returns: Array of changes. """ if not text1: # Just add some text (speedup). return [(self.DIFF_INSERT, text2)] if not text2: # Just delete some text (speedup). return [(self.DIFF_DELETE, text1)] if len(text1) > len(text2): (longtext, shorttext) = (text1, text2) else: (shorttext, longtext) = (text1, text2) i = longtext.find(shorttext) if i != -1: # Shorter text is inside the longer text (speedup). diffs = [(self.DIFF_INSERT, longtext[:i]), (self.DIFF_EQUAL, shorttext), (self.DIFF_INSERT, longtext[i + len(shorttext):])] # Swap insertions for deletions if diff is reversed. if len(text1) > len(text2): diffs[0] = (self.DIFF_DELETE, diffs[0][1]) diffs[2] = (self.DIFF_DELETE, diffs[2][1]) return diffs if len(shorttext) == 1: # Single character string. # After the previous speedup, the character can't be an equality. return [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)] # Check to see if the problem can be split in two. hm = self.diff_halfMatch(text1, text2) if hm: # A half-match was found, sort out the return data. (text1_a, text1_b, text2_a, text2_b, mid_common) = hm # Send both pairs off for separate processing. diffs_a = self.diff_main(text1_a, text2_a, checklines, deadline) diffs_b = self.diff_main(text1_b, text2_b, checklines, deadline) # Merge the results. return diffs_a + [(self.DIFF_EQUAL, mid_common)] + diffs_b if checklines and len(text1) > 100 and len(text2) > 100: return self.diff_lineMode(text1, text2, deadline) return self.diff_bisect(text1, text2, deadline) def diff_lineMode(self, text1, text2, deadline): """Do a quick line-level diff on both strings, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. Args: text1: Old string to be diffed. text2: New string to be diffed. deadline: Time when the diff should be complete by. Returns: Array of changes. """ # Scan the text on a line-by-line basis first. (text1, text2, linearray) = self.diff_linesToChars(text1, text2) diffs = self.diff_main(text1, text2, False, deadline) # Convert the diff back to original text. self.diff_charsToLines(diffs, linearray) # Eliminate freak matches (e.g. blank lines) self.diff_cleanupSemantic(diffs) # Rediff any replacement blocks, this time character-by-character. # Add a dummy entry at the end. diffs.append((self.DIFF_EQUAL, '')) pointer = 0 count_delete = 0 count_insert = 0 text_delete = '' text_insert = '' while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_INSERT: count_insert += 1 text_insert += diffs[pointer][1] elif diffs[pointer][0] == self.DIFF_DELETE: count_delete += 1 text_delete += diffs[pointer][1] elif diffs[pointer][0] == self.DIFF_EQUAL: # Upon reaching an equality, check for prior redundancies. if count_delete >= 1 and count_insert >= 1: # Delete the offending records and add the merged ones. subDiff = self.diff_main(text_delete, text_insert, False, deadline) diffs[pointer - count_delete - count_insert : pointer] = subDiff pointer = pointer - count_delete - count_insert + len(subDiff) count_insert = 0 count_delete = 0 text_delete = '' text_insert = '' pointer += 1 diffs.pop() # Remove the dummy entry at the end. return diffs def diff_bisect(self, text1, text2, deadline): """Find the 'middle snake' of a diff, split the problem in two and return the recursively constructed diff. See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. Args: text1: Old string to be diffed. text2: New string to be diffed. deadline: Time at which to bail if not yet complete. Returns: Array of diff tuples. """ # Cache the text lengths to prevent multiple calls. text1_length = len(text1) text2_length = len(text2) max_d = (text1_length + text2_length + 1) // 2 v_offset = max_d v_length = 2 * max_d v1 = [-1] * v_length v1[v_offset + 1] = 0 v2 = v1[:] delta = text1_length - text2_length # If the total number of characters is odd, then the front path will # collide with the reverse path. front = (delta % 2 != 0) # Offsets for start and end of k loop. # Prevents mapping of space beyond the grid. k1start = 0 k1end = 0 k2start = 0 k2end = 0 for d in xrange(max_d): # Bail out if deadline is reached. if time.time() > deadline: break # Walk the front path one step. for k1 in xrange(-d + k1start, d + 1 - k1end, 2): k1_offset = v_offset + k1 if k1 == -d or (k1 != d and v1[k1_offset - 1] < v1[k1_offset + 1]): x1 = v1[k1_offset + 1] else: x1 = v1[k1_offset - 1] + 1 y1 = x1 - k1 while (x1 < text1_length and y1 < text2_length and text1[x1] == text2[y1]): x1 += 1 y1 += 1 v1[k1_offset] = x1 if x1 > text1_length: # Ran off the right of the graph. k1end += 2 elif y1 > text2_length: # Ran off the bottom of the graph. k1start += 2 elif front: k2_offset = v_offset + delta - k1 if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] != -1: # Mirror x2 onto top-left coordinate system. x2 = text1_length - v2[k2_offset] if x1 >= x2: # Overlap detected. return self.diff_bisectSplit(text1, text2, x1, y1, deadline) # Walk the reverse path one step. for k2 in xrange(-d + k2start, d + 1 - k2end, 2): k2_offset = v_offset + k2 if k2 == -d or (k2 != d and v2[k2_offset - 1] < v2[k2_offset + 1]): x2 = v2[k2_offset + 1] else: x2 = v2[k2_offset - 1] + 1 y2 = x2 - k2 while (x2 < text1_length and y2 < text2_length and text1[-x2 - 1] == text2[-y2 - 1]): x2 += 1 y2 += 1 v2[k2_offset] = x2 if x2 > text1_length: # Ran off the left of the graph. k2end += 2 elif y2 > text2_length: # Ran off the top of the graph. k2start += 2 elif not front: k1_offset = v_offset + delta - k2 if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] != -1: x1 = v1[k1_offset] y1 = v_offset + x1 - k1_offset # Mirror x2 onto top-left coordinate system. x2 = text1_length - x2 if x1 >= x2: # Overlap detected. return self.diff_bisectSplit(text1, text2, x1, y1, deadline) # Diff took too long and hit the deadline or # number of diffs equals number of characters, no commonality at all. return [(self.DIFF_DELETE, text1), (self.DIFF_INSERT, text2)] def diff_bisectSplit(self, text1, text2, x, y, deadline): """Given the location of the 'middle snake', split the diff in two parts and recurse. Args: text1: Old string to be diffed. text2: New string to be diffed. x: Index of split point in text1. y: Index of split point in text2. deadline: Time at which to bail if not yet complete. Returns: Array of diff tuples. """ text1a = text1[:x] text2a = text2[:y] text1b = text1[x:] text2b = text2[y:] # Compute both diffs serially. diffs = self.diff_main(text1a, text2a, False, deadline) diffsb = self.diff_main(text1b, text2b, False, deadline) return diffs + diffsb def diff_linesToChars(self, text1, text2): """Split two texts into an array of strings. Reduce the texts to a string of hashes where each Unicode character represents one line. Args: text1: First string. text2: Second string. Returns: Three element tuple, containing the encoded text1, the encoded text2 and the array of unique strings. The zeroth element of the array of unique strings is intentionally blank. """ lineArray = [] # e.g. lineArray[4] == "Hello\n" lineHash = {} # e.g. lineHash["Hello\n"] == 4 # "\x00" is a valid character, but various debuggers don't like it. # So we'll insert a junk entry to avoid generating a null character. lineArray.append('') def diff_linesToCharsMunge(text): """Split a text into an array of strings. Reduce the texts to a string of hashes where each Unicode character represents one line. Modifies linearray and linehash through being a closure. Args: text: String to encode. Returns: Encoded string. """ chars = [] # Walk the text, pulling out a substring for each line. # text.split('\n') would would temporarily double our memory footprint. # Modifying text would create many large strings to garbage collect. lineStart = 0 lineEnd = -1 while lineEnd < len(text) - 1: lineEnd = text.find('\n', lineStart) if lineEnd == -1: lineEnd = len(text) - 1 line = text[lineStart:lineEnd + 1] if line in lineHash: chars.append(unichr(lineHash[line])) else: if len(lineArray) == maxLines: # Bail out at 65535 because unichr(65536) throws. line = text[lineStart:] lineEnd = len(text) lineArray.append(line) lineHash[line] = len(lineArray) - 1 chars.append(unichr(len(lineArray) - 1)) lineStart = lineEnd + 1 return "".join(chars) # Allocate 2/3rds of the space for text1, the rest for text2. maxLines = 40000 chars1 = diff_linesToCharsMunge(text1) maxLines = 65535 chars2 = diff_linesToCharsMunge(text2) return (chars1, chars2, lineArray) def diff_charsToLines(self, diffs, lineArray): """Rehydrate the text in a diff from a string of line hashes to real lines of text. Args: diffs: Array of diff tuples. lineArray: Array of unique strings. """ for x in xrange(len(diffs)): text = [] for char in diffs[x][1]: text.append(lineArray[ord(char)]) diffs[x] = (diffs[x][0], "".join(text)) def diff_commonPrefix(self, text1, text2): """Determine the common prefix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the start of each string. """ # Quick check for common null cases. if not text1 or not text2 or text1[0] != text2[0]: return 0 # Binary search. # Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0 pointermax = min(len(text1), len(text2)) pointermid = pointermax pointerstart = 0 while pointermin < pointermid: if text1[pointerstart:pointermid] == text2[pointerstart:pointermid]: pointermin = pointermid pointerstart = pointermin else: pointermax = pointermid pointermid = (pointermax - pointermin) // 2 + pointermin return pointermid def diff_commonSuffix(self, text1, text2): """Determine the common suffix of two strings. Args: text1: First string. text2: Second string. Returns: The number of characters common to the end of each string. """ # Quick check for common null cases. if not text1 or not text2 or text1[-1] != text2[-1]: return 0 # Binary search. # Performance analysis: https://neil.fraser.name/news/2007/10/09/ pointermin = 0 pointermax = min(len(text1), len(text2)) pointermid = pointermax pointerend = 0 while pointermin < pointermid: if (text1[-pointermid:len(text1) - pointerend] == text2[-pointermid:len(text2) - pointerend]): pointermin = pointermid pointerend = pointermin else: pointermax = pointermid pointermid = (pointermax - pointermin) // 2 + pointermin return pointermid def diff_commonOverlap(self, text1, text2): """Determine if the suffix of one string is the prefix of another. Args: text1 First string. text2 Second string. Returns: The number of characters common to the end of the first string and the start of the second string. """ # Cache the text lengths to prevent multiple calls. text1_length = len(text1) text2_length = len(text2) # Eliminate the null case. if text1_length == 0 or text2_length == 0: return 0 # Truncate the longer string. if text1_length > text2_length: text1 = text1[-text2_length:] elif text1_length < text2_length: text2 = text2[:text1_length] text_length = min(text1_length, text2_length) # Quick check for the worst case. if text1 == text2: return text_length # Start by looking for a single character match # and increase length until no match is found. # Performance analysis: https://neil.fraser.name/news/2010/11/04/ best = 0 length = 1 while True: pattern = text1[-length:] found = text2.find(pattern) if found == -1: return best length += found if found == 0 or text1[-length:] == text2[:length]: best = length length += 1 def diff_halfMatch(self, text1, text2): """Do the two texts share a substring which is at least half the length of the longer text? This speedup can produce non-minimal diffs. Args: text1: First string. text2: Second string. Returns: Five element Array, containing the prefix of text1, the suffix of text1, the prefix of text2, the suffix of text2 and the common middle. Or None if there was no match. """ if self.Diff_Timeout <= 0: # Don't risk returning a non-optimal diff if we have unlimited time. return None if len(text1) > len(text2): (longtext, shorttext) = (text1, text2) else: (shorttext, longtext) = (text1, text2) if len(longtext) < 4 or len(shorttext) * 2 < len(longtext): return None # Pointless. def diff_halfMatchI(longtext, shorttext, i): """Does a substring of shorttext exist within longtext such that the substring is at least half the length of longtext? Closure, but does not reference any external variables. Args: longtext: Longer string. shorttext: Shorter string. i: Start index of quarter length substring within longtext. Returns: Five element Array, containing the prefix of longtext, the suffix of longtext, the prefix of shorttext, the suffix of shorttext and the common middle. Or None if there was no match. """ seed = longtext[i:i + len(longtext) // 4] best_common = '' j = shorttext.find(seed) while j != -1: prefixLength = self.diff_commonPrefix(longtext[i:], shorttext[j:]) suffixLength = self.diff_commonSuffix(longtext[:i], shorttext[:j]) if len(best_common) < suffixLength + prefixLength: best_common = (shorttext[j - suffixLength:j] + shorttext[j:j + prefixLength]) best_longtext_a = longtext[:i - suffixLength] best_longtext_b = longtext[i + prefixLength:] best_shorttext_a = shorttext[:j - suffixLength] best_shorttext_b = shorttext[j + prefixLength:] j = shorttext.find(seed, j + 1) if len(best_common) * 2 >= len(longtext): return (best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common) else: return None # First check if the second quarter is the seed for a half-match. hm1 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 3) // 4) # Check again based on the third quarter. hm2 = diff_halfMatchI(longtext, shorttext, (len(longtext) + 1) // 2) if not hm1 and not hm2: return None elif not hm2: hm = hm1 elif not hm1: hm = hm2 else: # Both matched. Select the longest. if len(hm1[4]) > len(hm2[4]): hm = hm1 else: hm = hm2 # A half-match was found, sort out the return data. if len(text1) > len(text2): (text1_a, text1_b, text2_a, text2_b, mid_common) = hm else: (text2_a, text2_b, text1_a, text1_b, mid_common) = hm return (text1_a, text1_b, text2_a, text2_b, mid_common) def diff_cleanupSemantic(self, diffs): """Reduce the number of edits by eliminating semantically trivial equalities. Args: diffs: Array of diff tuples. """ changes = False equalities = [] # Stack of indices where equalities are found. lastequality = None # Always equal to diffs[equalities[-1]][1] pointer = 0 # Index of current position. # Number of chars that changed prior to the equality. length_insertions1, length_deletions1 = 0, 0 # Number of chars that changed after the equality. length_insertions2, length_deletions2 = 0, 0 while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_EQUAL: # Equality found. equalities.append(pointer) length_insertions1, length_insertions2 = length_insertions2, 0 length_deletions1, length_deletions2 = length_deletions2, 0 lastequality = diffs[pointer][1] else: # An insertion or deletion. if diffs[pointer][0] == self.DIFF_INSERT: length_insertions2 += len(diffs[pointer][1]) else: length_deletions2 += len(diffs[pointer][1]) # Eliminate an equality that is smaller or equal to the edits on both # sides of it. if (lastequality and (len(lastequality) <= max(length_insertions1, length_deletions1)) and (len(lastequality) <= max(length_insertions2, length_deletions2))): # Duplicate record. diffs.insert(equalities[-1], (self.DIFF_DELETE, lastequality)) # Change second copy to insert. diffs[equalities[-1] + 1] = (self.DIFF_INSERT, diffs[equalities[-1] + 1][1]) # Throw away the equality we just deleted. equalities.pop() # Throw away the previous equality (it needs to be reevaluated). if len(equalities): equalities.pop() if len(equalities): pointer = equalities[-1] else: pointer = -1 # Reset the counters. length_insertions1, length_deletions1 = 0, 0 length_insertions2, length_deletions2 = 0, 0 lastequality = None changes = True pointer += 1 # Normalize the diff. if changes: self.diff_cleanupMerge(diffs) self.diff_cleanupSemanticLossless(diffs) # Find any overlaps between deletions and insertions. # e.g: abcxxxxxxdef # -> abcxxxdef # e.g: xxxabcdefxxx # -> defxxxabc # Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 1 while pointer < len(diffs): if (diffs[pointer - 1][0] == self.DIFF_DELETE and diffs[pointer][0] == self.DIFF_INSERT): deletion = diffs[pointer - 1][1] insertion = diffs[pointer][1] overlap_length1 = self.diff_commonOverlap(deletion, insertion) overlap_length2 = self.diff_commonOverlap(insertion, deletion) if overlap_length1 >= overlap_length2: if (overlap_length1 >= len(deletion) / 2.0 or overlap_length1 >= len(insertion) / 2.0): # Overlap found. Insert an equality and trim the surrounding edits. diffs.insert(pointer, (self.DIFF_EQUAL, insertion[:overlap_length1])) diffs[pointer - 1] = (self.DIFF_DELETE, deletion[:len(deletion) - overlap_length1]) diffs[pointer + 1] = (self.DIFF_INSERT, insertion[overlap_length1:]) pointer += 1 else: if (overlap_length2 >= len(deletion) / 2.0 or overlap_length2 >= len(insertion) / 2.0): # Reverse overlap found. # Insert an equality and swap and trim the surrounding edits. diffs.insert(pointer, (self.DIFF_EQUAL, deletion[:overlap_length2])) diffs[pointer - 1] = (self.DIFF_INSERT, insertion[:len(insertion) - overlap_length2]) diffs[pointer + 1] = (self.DIFF_DELETE, deletion[overlap_length2:]) pointer += 1 pointer += 1 pointer += 1 def diff_cleanupSemanticLossless(self, diffs): """Look for single edits surrounded on both sides by equalities which can be shifted sideways to align the edit to a word boundary. e.g: The cat came. -> The cat came. Args: diffs: Array of diff tuples. """ def diff_cleanupSemanticScore(one, two): """Given two strings, compute a score representing whether the internal boundary falls on logical boundaries. Scores range from 6 (best) to 0 (worst). Closure, but does not reference any external variables. Args: one: First string. two: Second string. Returns: The score. """ if not one or not two: # Edges are the best. return 6 # Each port of this function behaves slightly differently due to # subtle differences in each language's definition of things like # 'whitespace'. Since this function's purpose is largely cosmetic, # the choice has been made to use each language's native features # rather than force total conformity. char1 = one[-1] char2 = two[0] nonAlphaNumeric1 = not char1.isalnum() nonAlphaNumeric2 = not char2.isalnum() whitespace1 = nonAlphaNumeric1 and char1.isspace() whitespace2 = nonAlphaNumeric2 and char2.isspace() lineBreak1 = whitespace1 and (char1 == "\r" or char1 == "\n") lineBreak2 = whitespace2 and (char2 == "\r" or char2 == "\n") blankLine1 = lineBreak1 and self.BLANKLINEEND.search(one) blankLine2 = lineBreak2 and self.BLANKLINESTART.match(two) if blankLine1 or blankLine2: # Five points for blank lines. return 5 elif lineBreak1 or lineBreak2: # Four points for line breaks. return 4 elif nonAlphaNumeric1 and not whitespace1 and whitespace2: # Three points for end of sentences. return 3 elif whitespace1 or whitespace2: # Two points for whitespace. return 2 elif nonAlphaNumeric1 or nonAlphaNumeric2: # One point for non-alphanumeric. return 1 return 0 pointer = 1 # Intentionally ignore the first and last element (don't need checking). while pointer < len(diffs) - 1: if (diffs[pointer - 1][0] == self.DIFF_EQUAL and diffs[pointer + 1][0] == self.DIFF_EQUAL): # This is a single edit surrounded by equalities. equality1 = diffs[pointer - 1][1] edit = diffs[pointer][1] equality2 = diffs[pointer + 1][1] # First, shift the edit as far left as possible. commonOffset = self.diff_commonSuffix(equality1, edit) if commonOffset: commonString = edit[-commonOffset:] equality1 = equality1[:-commonOffset] edit = commonString + edit[:-commonOffset] equality2 = commonString + equality2 # Second, step character by character right, looking for the best fit. bestEquality1 = equality1 bestEdit = edit bestEquality2 = equality2 bestScore = (diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2)) while edit and equality2 and edit[0] == equality2[0]: equality1 += edit[0] edit = edit[1:] + equality2[0] equality2 = equality2[1:] score = (diff_cleanupSemanticScore(equality1, edit) + diff_cleanupSemanticScore(edit, equality2)) # The >= encourages trailing rather than leading whitespace on edits. if score >= bestScore: bestScore = score bestEquality1 = equality1 bestEdit = edit bestEquality2 = equality2 if diffs[pointer - 1][1] != bestEquality1: # We have an improvement, save it back to the diff. if bestEquality1: diffs[pointer - 1] = (diffs[pointer - 1][0], bestEquality1) else: del diffs[pointer - 1] pointer -= 1 diffs[pointer] = (diffs[pointer][0], bestEdit) if bestEquality2: diffs[pointer + 1] = (diffs[pointer + 1][0], bestEquality2) else: del diffs[pointer + 1] pointer -= 1 pointer += 1 # Define some regex patterns for matching boundaries. BLANKLINEEND = re.compile(r"\n\r?\n$") BLANKLINESTART = re.compile(r"^\r?\n\r?\n") def diff_cleanupEfficiency(self, diffs): """Reduce the number of edits by eliminating operationally trivial equalities. Args: diffs: Array of diff tuples. """ changes = False equalities = [] # Stack of indices where equalities are found. lastequality = None # Always equal to diffs[equalities[-1]][1] pointer = 0 # Index of current position. pre_ins = False # Is there an insertion operation before the last equality. pre_del = False # Is there a deletion operation before the last equality. post_ins = False # Is there an insertion operation after the last equality. post_del = False # Is there a deletion operation after the last equality. while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_EQUAL: # Equality found. if (len(diffs[pointer][1]) < self.Diff_EditCost and (post_ins or post_del)): # Candidate found. equalities.append(pointer) pre_ins = post_ins pre_del = post_del lastequality = diffs[pointer][1] else: # Not a candidate, and can never become one. equalities = [] lastequality = None post_ins = post_del = False else: # An insertion or deletion. if diffs[pointer][0] == self.DIFF_DELETE: post_del = True else: post_ins = True # Five types to be split: # ABXYCD # AXCD # ABXC # AXCD # ABXC if lastequality and ((pre_ins and pre_del and post_ins and post_del) or ((len(lastequality) < self.Diff_EditCost / 2) and (pre_ins + pre_del + post_ins + post_del) == 3)): # Duplicate record. diffs.insert(equalities[-1], (self.DIFF_DELETE, lastequality)) # Change second copy to insert. diffs[equalities[-1] + 1] = (self.DIFF_INSERT, diffs[equalities[-1] + 1][1]) equalities.pop() # Throw away the equality we just deleted. lastequality = None if pre_ins and pre_del: # No changes made which could affect previous entry, keep going. post_ins = post_del = True equalities = [] else: if len(equalities): equalities.pop() # Throw away the previous equality. if len(equalities): pointer = equalities[-1] else: pointer = -1 post_ins = post_del = False changes = True pointer += 1 if changes: self.diff_cleanupMerge(diffs) def diff_cleanupMerge(self, diffs): """Reorder and merge like edit sections. Merge equalities. Any edit section can move as long as it doesn't cross an equality. Args: diffs: Array of diff tuples. """ diffs.append((self.DIFF_EQUAL, '')) # Add a dummy entry at the end. pointer = 0 count_delete = 0 count_insert = 0 text_delete = '' text_insert = '' while pointer < len(diffs): if diffs[pointer][0] == self.DIFF_INSERT: count_insert += 1 text_insert += diffs[pointer][1] pointer += 1 elif diffs[pointer][0] == self.DIFF_DELETE: count_delete += 1 text_delete += diffs[pointer][1] pointer += 1 elif diffs[pointer][0] == self.DIFF_EQUAL: # Upon reaching an equality, check for prior redundancies. if count_delete + count_insert > 1: if count_delete != 0 and count_insert != 0: # Factor out any common prefixies. commonlength = self.diff_commonPrefix(text_insert, text_delete) if commonlength != 0: x = pointer - count_delete - count_insert - 1 if x >= 0 and diffs[x][0] == self.DIFF_EQUAL: diffs[x] = (diffs[x][0], diffs[x][1] + text_insert[:commonlength]) else: diffs.insert(0, (self.DIFF_EQUAL, text_insert[:commonlength])) pointer += 1 text_insert = text_insert[commonlength:] text_delete = text_delete[commonlength:] # Factor out any common suffixies. commonlength = self.diff_commonSuffix(text_insert, text_delete) if commonlength != 0: diffs[pointer] = (diffs[pointer][0], text_insert[-commonlength:] + diffs[pointer][1]) text_insert = text_insert[:-commonlength] text_delete = text_delete[:-commonlength] # Delete the offending records and add the merged ones. new_ops = [] if len(text_delete) != 0: new_ops.append((self.DIFF_DELETE, text_delete)) if len(text_insert) != 0: new_ops.append((self.DIFF_INSERT, text_insert)) pointer -= count_delete + count_insert diffs[pointer : pointer + count_delete + count_insert] = new_ops pointer += len(new_ops) + 1 elif pointer != 0 and diffs[pointer - 1][0] == self.DIFF_EQUAL: # Merge this equality with the previous one. diffs[pointer - 1] = (diffs[pointer - 1][0], diffs[pointer - 1][1] + diffs[pointer][1]) del diffs[pointer] else: pointer += 1 count_insert = 0 count_delete = 0 text_delete = '' text_insert = '' if diffs[-1][1] == '': diffs.pop() # Remove the dummy entry at the end. # Second pass: look for single edits surrounded on both sides by equalities # which can be shifted sideways to eliminate an equality. # e.g: ABAC -> ABAC changes = False pointer = 1 # Intentionally ignore the first and last element (don't need checking). while pointer < len(diffs) - 1: if (diffs[pointer - 1][0] == self.DIFF_EQUAL and diffs[pointer + 1][0] == self.DIFF_EQUAL): # This is a single edit surrounded by equalities. if diffs[pointer][1].endswith(diffs[pointer - 1][1]): # Shift the edit over the previous equality. if diffs[pointer - 1][1] != "": diffs[pointer] = (diffs[pointer][0], diffs[pointer - 1][1] + diffs[pointer][1][:-len(diffs[pointer - 1][1])]) diffs[pointer + 1] = (diffs[pointer + 1][0], diffs[pointer - 1][1] + diffs[pointer + 1][1]) del diffs[pointer - 1] changes = True elif diffs[pointer][1].startswith(diffs[pointer + 1][1]): # Shift the edit over the next equality. diffs[pointer - 1] = (diffs[pointer - 1][0], diffs[pointer - 1][1] + diffs[pointer + 1][1]) diffs[pointer] = (diffs[pointer][0], diffs[pointer][1][len(diffs[pointer + 1][1]):] + diffs[pointer + 1][1]) del diffs[pointer + 1] changes = True pointer += 1 # If shifts were made, the diff needs reordering and another shift sweep. if changes: self.diff_cleanupMerge(diffs) def diff_xIndex(self, diffs, loc): """loc is a location in text1, compute and return the equivalent location in text2. e.g. "The cat" vs "The big cat", 1->1, 5->8 Args: diffs: Array of diff tuples. loc: Location within text1. Returns: Location within text2. """ chars1 = 0 chars2 = 0 last_chars1 = 0 last_chars2 = 0 for x in xrange(len(diffs)): (op, text) = diffs[x] if op != self.DIFF_INSERT: # Equality or deletion. chars1 += len(text) if op != self.DIFF_DELETE: # Equality or insertion. chars2 += len(text) if chars1 > loc: # Overshot the location. break last_chars1 = chars1 last_chars2 = chars2 if len(diffs) != x and diffs[x][0] == self.DIFF_DELETE: # The location was deleted. return last_chars2 # Add the remaining len(character). return last_chars2 + (loc - last_chars1) def diff_prettyHtml(self, diffs): """Convert a diff array into a pretty HTML report. Args: diffs: Array of diff tuples. Returns: HTML representation. """ html = [] for (op, data) in diffs: text = (data.replace("&", "&").replace("<", "<") .replace(">", ">").replace("\n", "¶
    ")) if op == self.DIFF_INSERT: html.append("%s" % text) elif op == self.DIFF_DELETE: html.append("%s" % text) elif op == self.DIFF_EQUAL: html.append("%s" % text) return "".join(html) def diff_text1(self, diffs): """Compute and return the source text (all equalities and deletions). Args: diffs: Array of diff tuples. Returns: Source text. """ text = [] for (op, data) in diffs: if op != self.DIFF_INSERT: text.append(data) return "".join(text) def diff_text2(self, diffs): """Compute and return the destination text (all equalities and insertions). Args: diffs: Array of diff tuples. Returns: Destination text. """ text = [] for (op, data) in diffs: if op != self.DIFF_DELETE: text.append(data) return "".join(text) def diff_levenshtein(self, diffs): """Compute the Levenshtein distance; the number of inserted, deleted or substituted characters. Args: diffs: Array of diff tuples. Returns: Number of changes. """ levenshtein = 0 insertions = 0 deletions = 0 for (op, data) in diffs: if op == self.DIFF_INSERT: insertions += len(data) elif op == self.DIFF_DELETE: deletions += len(data) elif op == self.DIFF_EQUAL: # A deletion and an insertion is one substitution. levenshtein += max(insertions, deletions) insertions = 0 deletions = 0 levenshtein += max(insertions, deletions) return levenshtein def diff_toDelta(self, diffs): """Crush the diff into an encoded string which describes the operations required to transform text1 into text2. E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. Operations are tab-separated. Inserted text is escaped using %xx notation. Args: diffs: Array of diff tuples. Returns: Delta text. """ text = [] for (op, data) in diffs: if op == self.DIFF_INSERT: # High ascii will raise UnicodeDecodeError. Use Unicode instead. data = data.encode("utf-8") text.append("+" + urllib.quote(data, "!~*'();/?:@&=+$,# ")) elif op == self.DIFF_DELETE: text.append("-%d" % len(data)) elif op == self.DIFF_EQUAL: text.append("=%d" % len(data)) return "\t".join(text) def diff_fromDelta(self, text1, delta): """Given the original text1, and an encoded string which describes the operations required to transform text1 into text2, compute the full diff. Args: text1: Source string for the diff. delta: Delta text. Returns: Array of diff tuples. Raises: ValueError: If invalid input. """ if type(delta) == unicode: # Deltas should be composed of a subset of ascii chars, Unicode not # required. If this encode raises UnicodeEncodeError, delta is invalid. delta = delta.encode("ascii") diffs = [] pointer = 0 # Cursor in text1 tokens = delta.split("\t") for token in tokens: if token == "": # Blank tokens are ok (from a trailing \t). continue # Each token begins with a one character parameter which specifies the # operation of this token (delete, insert, equality). param = token[1:] if token[0] == "+": param = urllib.unquote(param).decode("utf-8") diffs.append((self.DIFF_INSERT, param)) elif token[0] == "-" or token[0] == "=": try: n = int(param) except ValueError: raise ValueError("Invalid number in diff_fromDelta: " + param) if n < 0: raise ValueError("Negative number in diff_fromDelta: " + param) text = text1[pointer : pointer + n] pointer += n if token[0] == "=": diffs.append((self.DIFF_EQUAL, text)) else: diffs.append((self.DIFF_DELETE, text)) else: # Anything else is an error. raise ValueError("Invalid diff operation in diff_fromDelta: " + token[0]) if pointer != len(text1): raise ValueError( "Delta length (%d) does not equal source text length (%d)." % (pointer, len(text1))) return diffs # MATCH FUNCTIONS def match_main(self, text, pattern, loc): """Locate the best instance of 'pattern' in 'text' near 'loc'. Args: text: The text to search. pattern: The pattern to search for. loc: The location to search around. Returns: Best match index or -1. """ # Check for null inputs. if text == None or pattern == None: raise ValueError("Null inputs. (match_main)") loc = max(0, min(loc, len(text))) if text == pattern: # Shortcut (potentially not guaranteed by the algorithm) return 0 elif not text: # Nothing to match. return -1 elif text[loc:loc + len(pattern)] == pattern: # Perfect match at the perfect spot! (Includes case of null pattern) return loc else: # Do a fuzzy compare. match = self.match_bitap(text, pattern, loc) return match def match_bitap(self, text, pattern, loc): """Locate the best instance of 'pattern' in 'text' near 'loc' using the Bitap algorithm. Args: text: The text to search. pattern: The pattern to search for. loc: The location to search around. Returns: Best match index or -1. """ # Python doesn't have a maxint limit, so ignore this check. #if self.Match_MaxBits != 0 and len(pattern) > self.Match_MaxBits: # raise ValueError("Pattern too long for this application.") # Initialise the alphabet. s = self.match_alphabet(pattern) def match_bitapScore(e, x): """Compute and return the score for a match with e errors and x location. Accesses loc and pattern through being a closure. Args: e: Number of errors in match. x: Location of match. Returns: Overall score for match (0.0 = good, 1.0 = bad). """ accuracy = float(e) / len(pattern) proximity = abs(loc - x) if not self.Match_Distance: # Dodge divide by zero error. return proximity and 1.0 or accuracy return accuracy + (proximity / float(self.Match_Distance)) # Highest score beyond which we give up. score_threshold = self.Match_Threshold # Is there a nearby exact match? (speedup) best_loc = text.find(pattern, loc) if best_loc != -1: score_threshold = min(match_bitapScore(0, best_loc), score_threshold) # What about in the other direction? (speedup) best_loc = text.rfind(pattern, loc + len(pattern)) if best_loc != -1: score_threshold = min(match_bitapScore(0, best_loc), score_threshold) # Initialise the bit arrays. matchmask = 1 << (len(pattern) - 1) best_loc = -1 bin_max = len(pattern) + len(text) # Empty initialization added to appease pychecker. last_rd = None for d in xrange(len(pattern)): # Scan for the best match each iteration allows for one more error. # Run a binary search to determine how far from 'loc' we can stray at # this error level. bin_min = 0 bin_mid = bin_max while bin_min < bin_mid: if match_bitapScore(d, loc + bin_mid) <= score_threshold: bin_min = bin_mid else: bin_max = bin_mid bin_mid = (bin_max - bin_min) // 2 + bin_min # Use the result from this iteration as the maximum for the next. bin_max = bin_mid start = max(1, loc - bin_mid + 1) finish = min(loc + bin_mid, len(text)) + len(pattern) rd = [0] * (finish + 2) rd[finish + 1] = (1 << d) - 1 for j in xrange(finish, start - 1, -1): if len(text) <= j - 1: # Out of range. charMatch = 0 else: charMatch = s.get(text[j - 1], 0) if d == 0: # First pass: exact match. rd[j] = ((rd[j + 1] << 1) | 1) & charMatch else: # Subsequent passes: fuzzy match. rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | ( ((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1] if rd[j] & matchmask: score = match_bitapScore(d, j - 1) # This match will almost certainly be better than any existing match. # But check anyway. if score <= score_threshold: # Told you so. score_threshold = score best_loc = j - 1 if best_loc > loc: # When passing loc, don't exceed our current distance from loc. start = max(1, 2 * loc - best_loc) else: # Already passed loc, downhill from here on in. break # No hope for a (better) match at greater error levels. if match_bitapScore(d + 1, loc) > score_threshold: break last_rd = rd return best_loc def match_alphabet(self, pattern): """Initialise the alphabet for the Bitap algorithm. Args: pattern: The text to encode. Returns: Hash of character locations. """ s = {} for char in pattern: s[char] = 0 for i in xrange(len(pattern)): s[pattern[i]] |= 1 << (len(pattern) - i - 1) return s # PATCH FUNCTIONS def patch_addContext(self, patch, text): """Increase the context until it is unique, but don't let the pattern expand beyond Match_MaxBits. Args: patch: The patch to grow. text: Source text. """ if len(text) == 0: return pattern = text[patch.start2 : patch.start2 + patch.length1] padding = 0 # Look for the first and last matches of pattern in text. If two different # matches are found, increase the pattern length. while (text.find(pattern) != text.rfind(pattern) and (self.Match_MaxBits == 0 or len(pattern) < self.Match_MaxBits - self.Patch_Margin - self.Patch_Margin)): padding += self.Patch_Margin pattern = text[max(0, patch.start2 - padding) : patch.start2 + patch.length1 + padding] # Add one chunk for good luck. padding += self.Patch_Margin # Add the prefix. prefix = text[max(0, patch.start2 - padding) : patch.start2] if prefix: patch.diffs[:0] = [(self.DIFF_EQUAL, prefix)] # Add the suffix. suffix = text[patch.start2 + patch.length1 : patch.start2 + patch.length1 + padding] if suffix: patch.diffs.append((self.DIFF_EQUAL, suffix)) # Roll back the start points. patch.start1 -= len(prefix) patch.start2 -= len(prefix) # Extend lengths. patch.length1 += len(prefix) + len(suffix) patch.length2 += len(prefix) + len(suffix) def patch_make(self, a, b=None, c=None): """Compute a list of patches to turn text1 into text2. Use diffs if provided, otherwise compute it ourselves. There are four ways to call this function, depending on what data is available to the caller: Method 1: a = text1, b = text2 Method 2: a = diffs Method 3 (optimal): a = text1, b = diffs Method 4 (deprecated, use method 3): a = text1, b = text2, c = diffs Args: a: text1 (methods 1,3,4) or Array of diff tuples for text1 to text2 (method 2). b: text2 (methods 1,4) or Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). c: Array of diff tuples for text1 to text2 (method 4) or undefined (methods 1,2,3). Returns: Array of Patch objects. """ text1 = None diffs = None # Note that texts may arrive as 'str' or 'unicode'. if isinstance(a, basestring) and isinstance(b, basestring) and c is None: # Method 1: text1, text2 # Compute diffs from text1 and text2. text1 = a diffs = self.diff_main(text1, b, True) if len(diffs) > 2: self.diff_cleanupSemantic(diffs) self.diff_cleanupEfficiency(diffs) elif isinstance(a, list) and b is None and c is None: # Method 2: diffs # Compute text1 from diffs. diffs = a text1 = self.diff_text1(diffs) elif isinstance(a, basestring) and isinstance(b, list) and c is None: # Method 3: text1, diffs text1 = a diffs = b elif (isinstance(a, basestring) and isinstance(b, basestring) and isinstance(c, list)): # Method 4: text1, text2, diffs # text2 is not used. text1 = a diffs = c else: raise ValueError("Unknown call format to patch_make.") if not diffs: return [] # Get rid of the None case. patches = [] patch = patch_obj() char_count1 = 0 # Number of characters into the text1 string. char_count2 = 0 # Number of characters into the text2 string. prepatch_text = text1 # Recreate the patches to determine context info. postpatch_text = text1 for x in xrange(len(diffs)): (diff_type, diff_text) = diffs[x] if len(patch.diffs) == 0 and diff_type != self.DIFF_EQUAL: # A new patch starts here. patch.start1 = char_count1 patch.start2 = char_count2 if diff_type == self.DIFF_INSERT: # Insertion patch.diffs.append(diffs[x]) patch.length2 += len(diff_text) postpatch_text = (postpatch_text[:char_count2] + diff_text + postpatch_text[char_count2:]) elif diff_type == self.DIFF_DELETE: # Deletion. patch.length1 += len(diff_text) patch.diffs.append(diffs[x]) postpatch_text = (postpatch_text[:char_count2] + postpatch_text[char_count2 + len(diff_text):]) elif (diff_type == self.DIFF_EQUAL and len(diff_text) <= 2 * self.Patch_Margin and len(patch.diffs) != 0 and len(diffs) != x + 1): # Small equality inside a patch. patch.diffs.append(diffs[x]) patch.length1 += len(diff_text) patch.length2 += len(diff_text) if (diff_type == self.DIFF_EQUAL and len(diff_text) >= 2 * self.Patch_Margin): # Time for a new patch. if len(patch.diffs) != 0: self.patch_addContext(patch, prepatch_text) patches.append(patch) patch = patch_obj() # Unlike Unidiff, our patch lists have a rolling context. # https://github.com/google/diff-match-patch/wiki/Unidiff # Update prepatch text & pos to reflect the application of the # just completed patch. prepatch_text = postpatch_text char_count1 = char_count2 # Update the current character count. if diff_type != self.DIFF_INSERT: char_count1 += len(diff_text) if diff_type != self.DIFF_DELETE: char_count2 += len(diff_text) # Pick up the leftover patch if not empty. if len(patch.diffs) != 0: self.patch_addContext(patch, prepatch_text) patches.append(patch) return patches def patch_deepCopy(self, patches): """Given an array of patches, return another array that is identical. Args: patches: Array of Patch objects. Returns: Array of Patch objects. """ patchesCopy = [] for patch in patches: patchCopy = patch_obj() # No need to deep copy the tuples since they are immutable. patchCopy.diffs = patch.diffs[:] patchCopy.start1 = patch.start1 patchCopy.start2 = patch.start2 patchCopy.length1 = patch.length1 patchCopy.length2 = patch.length2 patchesCopy.append(patchCopy) return patchesCopy def patch_apply(self, patches, text): """Merge a set of patches onto the text. Return a patched text, as well as a list of true/false values indicating which patches were applied. Args: patches: Array of Patch objects. text: Old text. Returns: Two element Array, containing the new text and an array of boolean values. """ if not patches: return (text, []) # Deep copy the patches so that no changes are made to originals. patches = self.patch_deepCopy(patches) nullPadding = self.patch_addPadding(patches) text = nullPadding + text + nullPadding self.patch_splitMax(patches) # delta keeps track of the offset between the expected and actual location # of the previous patch. If there are patches expected at positions 10 and # 20, but the first patch was found at 12, delta is 2 and the second patch # has an effective expected position of 22. delta = 0 results = [] for patch in patches: expected_loc = patch.start2 + delta text1 = self.diff_text1(patch.diffs) end_loc = -1 if len(text1) > self.Match_MaxBits: # patch_splitMax will only provide an oversized pattern in the case of # a monster delete. start_loc = self.match_main(text, text1[:self.Match_MaxBits], expected_loc) if start_loc != -1: end_loc = self.match_main(text, text1[-self.Match_MaxBits:], expected_loc + len(text1) - self.Match_MaxBits) if end_loc == -1 or start_loc >= end_loc: # Can't find valid trailing context. Drop this patch. start_loc = -1 else: start_loc = self.match_main(text, text1, expected_loc) if start_loc == -1: # No match found. :( results.append(False) # Subtract the delta for this failed patch from subsequent patches. delta -= patch.length2 - patch.length1 else: # Found a match. :) results.append(True) delta = start_loc - expected_loc if end_loc == -1: text2 = text[start_loc : start_loc + len(text1)] else: text2 = text[start_loc : end_loc + self.Match_MaxBits] if text1 == text2: # Perfect match, just shove the replacement text in. text = (text[:start_loc] + self.diff_text2(patch.diffs) + text[start_loc + len(text1):]) else: # Imperfect match. # Run a diff to get a framework of equivalent indices. diffs = self.diff_main(text1, text2, False) if (len(text1) > self.Match_MaxBits and self.diff_levenshtein(diffs) / float(len(text1)) > self.Patch_DeleteThreshold): # The end points match, but the content is unacceptably bad. results[-1] = False else: self.diff_cleanupSemanticLossless(diffs) index1 = 0 for (op, data) in patch.diffs: if op != self.DIFF_EQUAL: index2 = self.diff_xIndex(diffs, index1) if op == self.DIFF_INSERT: # Insertion text = text[:start_loc + index2] + data + text[start_loc + index2:] elif op == self.DIFF_DELETE: # Deletion text = text[:start_loc + index2] + text[start_loc + self.diff_xIndex(diffs, index1 + len(data)):] if op != self.DIFF_DELETE: index1 += len(data) # Strip the padding off. text = text[len(nullPadding):-len(nullPadding)] return (text, results) def patch_addPadding(self, patches): """Add some padding on text start and end so that edges can match something. Intended to be called only from within patch_apply. Args: patches: Array of Patch objects. Returns: The padding string added to each side. """ paddingLength = self.Patch_Margin nullPadding = "" for x in xrange(1, paddingLength + 1): nullPadding += chr(x) # Bump all the patches forward. for patch in patches: patch.start1 += paddingLength patch.start2 += paddingLength # Add some padding on start of first diff. patch = patches[0] diffs = patch.diffs if not diffs or diffs[0][0] != self.DIFF_EQUAL: # Add nullPadding equality. diffs.insert(0, (self.DIFF_EQUAL, nullPadding)) patch.start1 -= paddingLength # Should be 0. patch.start2 -= paddingLength # Should be 0. patch.length1 += paddingLength patch.length2 += paddingLength elif paddingLength > len(diffs[0][1]): # Grow first equality. extraLength = paddingLength - len(diffs[0][1]) newText = nullPadding[len(diffs[0][1]):] + diffs[0][1] diffs[0] = (diffs[0][0], newText) patch.start1 -= extraLength patch.start2 -= extraLength patch.length1 += extraLength patch.length2 += extraLength # Add some padding on end of last diff. patch = patches[-1] diffs = patch.diffs if not diffs or diffs[-1][0] != self.DIFF_EQUAL: # Add nullPadding equality. diffs.append((self.DIFF_EQUAL, nullPadding)) patch.length1 += paddingLength patch.length2 += paddingLength elif paddingLength > len(diffs[-1][1]): # Grow last equality. extraLength = paddingLength - len(diffs[-1][1]) newText = diffs[-1][1] + nullPadding[:extraLength] diffs[-1] = (diffs[-1][0], newText) patch.length1 += extraLength patch.length2 += extraLength return nullPadding def patch_splitMax(self, patches): """Look through the patches and break up any which are longer than the maximum limit of the match algorithm. Intended to be called only from within patch_apply. Args: patches: Array of Patch objects. """ patch_size = self.Match_MaxBits if patch_size == 0: # Python has the option of not splitting strings due to its ability # to handle integers of arbitrary precision. return for x in xrange(len(patches)): if patches[x].length1 <= patch_size: continue bigpatch = patches[x] # Remove the big old patch. del patches[x] x -= 1 start1 = bigpatch.start1 start2 = bigpatch.start2 precontext = '' while len(bigpatch.diffs) != 0: # Create one of several smaller patches. patch = patch_obj() empty = True patch.start1 = start1 - len(precontext) patch.start2 = start2 - len(precontext) if precontext: patch.length1 = patch.length2 = len(precontext) patch.diffs.append((self.DIFF_EQUAL, precontext)) while (len(bigpatch.diffs) != 0 and patch.length1 < patch_size - self.Patch_Margin): (diff_type, diff_text) = bigpatch.diffs[0] if diff_type == self.DIFF_INSERT: # Insertions are harmless. patch.length2 += len(diff_text) start2 += len(diff_text) patch.diffs.append(bigpatch.diffs.pop(0)) empty = False elif (diff_type == self.DIFF_DELETE and len(patch.diffs) == 1 and patch.diffs[0][0] == self.DIFF_EQUAL and len(diff_text) > 2 * patch_size): # This is a large deletion. Let it pass in one chunk. patch.length1 += len(diff_text) start1 += len(diff_text) empty = False patch.diffs.append((diff_type, diff_text)) del bigpatch.diffs[0] else: # Deletion or equality. Only take as much as we can stomach. diff_text = diff_text[:patch_size - patch.length1 - self.Patch_Margin] patch.length1 += len(diff_text) start1 += len(diff_text) if diff_type == self.DIFF_EQUAL: patch.length2 += len(diff_text) start2 += len(diff_text) else: empty = False patch.diffs.append((diff_type, diff_text)) if diff_text == bigpatch.diffs[0][1]: del bigpatch.diffs[0] else: bigpatch.diffs[0] = (bigpatch.diffs[0][0], bigpatch.diffs[0][1][len(diff_text):]) # Compute the head context for the next patch. precontext = self.diff_text2(patch.diffs) precontext = precontext[-self.Patch_Margin:] # Append the end context for this patch. postcontext = self.diff_text1(bigpatch.diffs)[:self.Patch_Margin] if postcontext: patch.length1 += len(postcontext) patch.length2 += len(postcontext) if len(patch.diffs) != 0 and patch.diffs[-1][0] == self.DIFF_EQUAL: patch.diffs[-1] = (self.DIFF_EQUAL, patch.diffs[-1][1] + postcontext) else: patch.diffs.append((self.DIFF_EQUAL, postcontext)) if not empty: x += 1 patches.insert(x, patch) def patch_toText(self, patches): """Take a list of patches and return a textual representation. Args: patches: Array of Patch objects. Returns: Text representation of patches. """ text = [] for patch in patches: text.append(str(patch)) return "".join(text) def patch_fromText(self, textline): """Parse a textual representation of patches and return a list of patch objects. Args: textline: Text representation of patches. Returns: Array of Patch objects. Raises: ValueError: If invalid input. """ if type(textline) == unicode: # Patches should be composed of a subset of ascii chars, Unicode not # required. If this encode raises UnicodeEncodeError, patch is invalid. textline = textline.encode("ascii") patches = [] if not textline: return patches text = textline.split('\n') while len(text) != 0: m = re.match("^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$", text[0]) if not m: raise ValueError("Invalid patch string: " + text[0]) patch = patch_obj() patches.append(patch) patch.start1 = int(m.group(1)) if m.group(2) == '': patch.start1 -= 1 patch.length1 = 1 elif m.group(2) == '0': patch.length1 = 0 else: patch.start1 -= 1 patch.length1 = int(m.group(2)) patch.start2 = int(m.group(3)) if m.group(4) == '': patch.start2 -= 1 patch.length2 = 1 elif m.group(4) == '0': patch.length2 = 0 else: patch.start2 -= 1 patch.length2 = int(m.group(4)) del text[0] while len(text) != 0: if text[0]: sign = text[0][0] else: sign = '' line = urllib.unquote(text[0][1:]) line = line.decode("utf-8") if sign == '+': # Insertion. patch.diffs.append((self.DIFF_INSERT, line)) elif sign == '-': # Deletion. patch.diffs.append((self.DIFF_DELETE, line)) elif sign == ' ': # Minor equality. patch.diffs.append((self.DIFF_EQUAL, line)) elif sign == '@': # Start of next patch. break elif sign == '': # Blank line? Whatever. pass else: # WTF? raise ValueError("Invalid patch mode: '%s'\n%s" % (sign, line)) del text[0] return patches class patch_obj: """Class representing one patch operation. """ def __init__(self): """Initializes with an empty list of diffs. """ self.diffs = [] self.start1 = None self.start2 = None self.length1 = 0 self.length2 = 0 def __str__(self): """Emulate GNU diff's format. Header: @@ -382,8 +481,9 @@ Indices are printed as 1-based, not 0-based. Returns: The GNU diff string. """ if self.length1 == 0: coords1 = str(self.start1) + ",0" elif self.length1 == 1: coords1 = str(self.start1 + 1) else: coords1 = str(self.start1 + 1) + "," + str(self.length1) if self.length2 == 0: coords2 = str(self.start2) + ",0" elif self.length2 == 1: coords2 = str(self.start2 + 1) else: coords2 = str(self.start2 + 1) + "," + str(self.length2) text = ["@@ -", coords1, " +", coords2, " @@\n"] # Escape the body of the patch with %xx notation. for (op, data) in self.diffs: if op == diff_match_patch.DIFF_INSERT: text.append("+") elif op == diff_match_patch.DIFF_DELETE: text.append("-") elif op == diff_match_patch.DIFF_EQUAL: text.append(" ") # High ascii will raise UnicodeDecodeError. Use Unicode instead. data = data.encode("utf-8") text.append(urllib.quote(data, "!~*'();/?:@&=+$,# ") + "\n") return "".join(text) ================================================ FILE: third_party/DMP/diff_match_patch_uncompressed.js ================================================ /** * Diff Match and Patch * Copyright 2018 The diff-match-patch Authors. * https://github.com/google/diff-match-patch * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Computes the difference between two texts to create a patch. * Applies the patch onto another text, allowing for errors. * @author fraser@google.com (Neil Fraser) */ /** * Class containing the diff, match and patch methods. * @constructor */ var diff_match_patch = function() { // Defaults. // Redefine these in your program to override the defaults. // Number of seconds to map a diff before giving up (0 for infinity). this.Diff_Timeout = 1.0; // Cost of an empty edit operation in terms of edit characters. this.Diff_EditCost = 4; // At what point is no match declared (0.0 = perfection, 1.0 = very loose). this.Match_Threshold = 0.5; // How far to search for a match (0 = exact location, 1000+ = broad match). // A match this many characters away from the expected location will add // 1.0 to the score (0.0 is a perfect match). this.Match_Distance = 1000; // When deleting a large block of text (over ~64 characters), how close do // the contents have to be to match the expected contents. (0.0 = perfection, // 1.0 = very loose). Note that Match_Threshold controls how closely the // end points of a delete need to match. this.Patch_DeleteThreshold = 0.5; // Chunk size for context length. this.Patch_Margin = 4; // The number of bits in an int. this.Match_MaxBits = 32; }; // DIFF FUNCTIONS /** * The data structure representing a diff is an array of tuples: * [[DIFF_DELETE, 'Hello'], [DIFF_INSERT, 'Goodbye'], [DIFF_EQUAL, ' world.']] * which means: delete 'Hello', add 'Goodbye' and keep ' world.' */ var DIFF_DELETE = -1; var DIFF_INSERT = 1; var DIFF_EQUAL = 0; /** * Class representing one diff tuple. * Attempts to look like a two-element array (which is what this used to be). * @param {number} op Operation, one of: DIFF_DELETE, DIFF_INSERT, DIFF_EQUAL. * @param {string} text Text to be deleted, inserted, or retained. * @constructor */ diff_match_patch.Diff = function(op, text) { this[0] = op; this[1] = text; }; diff_match_patch.Diff.prototype.length = 2; /** * Emulate the output of a two-element array. * @return {string} Diff operation as a string. */ diff_match_patch.Diff.prototype.toString = function() { return this[0] + ',' + this[1]; }; /** * Find the differences between two texts. Simplifies the problem by stripping * any common prefix or suffix off the texts before diffing. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean=} opt_checklines Optional speedup flag. If present and false, * then don't run a line-level diff first to identify the changed areas. * Defaults to true, which does a faster, slightly less optimal diff. * @param {number=} opt_deadline Optional time when the diff should be complete * by. Used internally for recursive calls. Users should set DiffTimeout * instead. * @return {!Array.} Array of diff tuples. */ diff_match_patch.prototype.diff_main = function(text1, text2, opt_checklines, opt_deadline) { // Set a deadline by which time the diff must be complete. if (typeof opt_deadline == 'undefined') { if (this.Diff_Timeout <= 0) { opt_deadline = Number.MAX_VALUE; } else { opt_deadline = (new Date).getTime() + this.Diff_Timeout * 1000; } } var deadline = opt_deadline; // Check for null inputs. if (text1 == null || text2 == null) { throw new Error('Null input. (diff_main)'); } // Check for equality (speedup). if (text1 == text2) { if (text1) { return [new diff_match_patch.Diff(DIFF_EQUAL, text1)]; } return []; } if (typeof opt_checklines == 'undefined') { opt_checklines = true; } var checklines = opt_checklines; // Trim off common prefix (speedup). var commonlength = this.diff_commonPrefix(text1, text2); var commonprefix = text1.substring(0, commonlength); text1 = text1.substring(commonlength); text2 = text2.substring(commonlength); // Trim off common suffix (speedup). commonlength = this.diff_commonSuffix(text1, text2); var commonsuffix = text1.substring(text1.length - commonlength); text1 = text1.substring(0, text1.length - commonlength); text2 = text2.substring(0, text2.length - commonlength); // Compute the diff on the middle block. var diffs = this.diff_compute_(text1, text2, checklines, deadline); // Restore the prefix and suffix. if (commonprefix) { diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, commonprefix)); } if (commonsuffix) { diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, commonsuffix)); } this.diff_cleanupMerge(diffs); return diffs; }; /** * Find the differences between two texts. Assumes that the texts do not * have any common prefix or suffix. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {boolean} checklines Speedup flag. If false, then don't run a * line-level diff first to identify the changed areas. * If true, then run a faster, slightly less optimal diff. * @param {number} deadline Time when the diff should be complete by. * @return {!Array.} Array of diff tuples. * @private */ diff_match_patch.prototype.diff_compute_ = function(text1, text2, checklines, deadline) { var diffs; if (!text1) { // Just add some text (speedup). return [new diff_match_patch.Diff(DIFF_INSERT, text2)]; } if (!text2) { // Just delete some text (speedup). return [new diff_match_patch.Diff(DIFF_DELETE, text1)]; } var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; var i = longtext.indexOf(shorttext); if (i != -1) { // Shorter text is inside the longer text (speedup). diffs = [new diff_match_patch.Diff(DIFF_INSERT, longtext.substring(0, i)), new diff_match_patch.Diff(DIFF_EQUAL, shorttext), new diff_match_patch.Diff(DIFF_INSERT, longtext.substring(i + shorttext.length))]; // Swap insertions for deletions if diff is reversed. if (text1.length > text2.length) { diffs[0][0] = diffs[2][0] = DIFF_DELETE; } return diffs; } if (shorttext.length == 1) { // Single character string. // After the previous speedup, the character can't be an equality. return [new diff_match_patch.Diff(DIFF_DELETE, text1), new diff_match_patch.Diff(DIFF_INSERT, text2)]; } // Check to see if the problem can be split in two. var hm = this.diff_halfMatch_(text1, text2); if (hm) { // A half-match was found, sort out the return data. var text1_a = hm[0]; var text1_b = hm[1]; var text2_a = hm[2]; var text2_b = hm[3]; var mid_common = hm[4]; // Send both pairs off for separate processing. var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); // Merge the results. return diffs_a.concat([new diff_match_patch.Diff(DIFF_EQUAL, mid_common)], diffs_b); } if (checklines && text1.length > 100 && text2.length > 100) { return this.diff_lineMode_(text1, text2, deadline); } return this.diff_bisect_(text1, text2, deadline); }; /** * Do a quick line-level diff on both strings, then rediff the parts for * greater accuracy. * This speedup can produce non-minimal diffs. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time when the diff should be complete by. * @return {!Array.} Array of diff tuples. * @private */ diff_match_patch.prototype.diff_lineMode_ = function(text1, text2, deadline) { // Scan the text on a line-by-line basis first. var a = this.diff_linesToChars_(text1, text2); text1 = a.chars1; text2 = a.chars2; var linearray = a.lineArray; var diffs = this.diff_main(text1, text2, false, deadline); // Convert the diff back to original text. this.diff_charsToLines_(diffs, linearray); // Eliminate freak matches (e.g. blank lines) this.diff_cleanupSemantic(diffs); // Rediff any replacement blocks, this time character-by-character. // Add a dummy entry at the end. diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, '')); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ''; var text_insert = ''; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete >= 1 && count_insert >= 1) { // Delete the offending records and add the merged ones. diffs.splice(pointer - count_delete - count_insert, count_delete + count_insert); pointer = pointer - count_delete - count_insert; var subDiff = this.diff_main(text_delete, text_insert, false, deadline); for (var j = subDiff.length - 1; j >= 0; j--) { diffs.splice(pointer, 0, subDiff[j]); } pointer = pointer + subDiff.length; } count_insert = 0; count_delete = 0; text_delete = ''; text_insert = ''; break; } pointer++; } diffs.pop(); // Remove the dummy entry at the end. return diffs; }; /** * Find the 'middle snake' of a diff, split the problem in two * and return the recursively constructed diff. * See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} deadline Time at which to bail if not yet complete. * @return {!Array.} Array of diff tuples. * @private */ diff_match_patch.prototype.diff_bisect_ = function(text1, text2, deadline) { // Cache the text lengths to prevent multiple calls. var text1_length = text1.length; var text2_length = text2.length; var max_d = Math.ceil((text1_length + text2_length) / 2); var v_offset = max_d; var v_length = 2 * max_d; var v1 = new Array(v_length); var v2 = new Array(v_length); // Setting all elements to -1 is faster in Chrome & Firefox than mixing // integers and undefined. for (var x = 0; x < v_length; x++) { v1[x] = -1; v2[x] = -1; } v1[v_offset + 1] = 0; v2[v_offset + 1] = 0; var delta = text1_length - text2_length; // If the total number of characters is odd, then the front path will collide // with the reverse path. var front = (delta % 2 != 0); // Offsets for start and end of k loop. // Prevents mapping of space beyond the grid. var k1start = 0; var k1end = 0; var k2start = 0; var k2end = 0; for (var d = 0; d < max_d; d++) { // Bail out if deadline is reached. if ((new Date()).getTime() > deadline) { break; } // Walk the front path one step. for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { var k1_offset = v_offset + k1; var x1; if (k1 == -d || (k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1])) { x1 = v1[k1_offset + 1]; } else { x1 = v1[k1_offset - 1] + 1; } var y1 = x1 - k1; while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) == text2.charAt(y1)) { x1++; y1++; } v1[k1_offset] = x1; if (x1 > text1_length) { // Ran off the right of the graph. k1end += 2; } else if (y1 > text2_length) { // Ran off the bottom of the graph. k1start += 2; } else if (front) { var k2_offset = v_offset + delta - k1; if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { // Mirror x2 onto top-left coordinate system. var x2 = text1_length - v2[k2_offset]; if (x1 >= x2) { // Overlap detected. return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); } } } } // Walk the reverse path one step. for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { var k2_offset = v_offset + k2; var x2; if (k2 == -d || (k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1])) { x2 = v2[k2_offset + 1]; } else { x2 = v2[k2_offset - 1] + 1; } var y2 = x2 - k2; while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) == text2.charAt(text2_length - y2 - 1)) { x2++; y2++; } v2[k2_offset] = x2; if (x2 > text1_length) { // Ran off the left of the graph. k2end += 2; } else if (y2 > text2_length) { // Ran off the top of the graph. k2start += 2; } else if (!front) { var k1_offset = v_offset + delta - k2; if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { var x1 = v1[k1_offset]; var y1 = v_offset + x1 - k1_offset; // Mirror x2 onto top-left coordinate system. x2 = text1_length - x2; if (x1 >= x2) { // Overlap detected. return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); } } } } } // Diff took too long and hit the deadline or // number of diffs equals number of characters, no commonality at all. return [new diff_match_patch.Diff(DIFF_DELETE, text1), new diff_match_patch.Diff(DIFF_INSERT, text2)]; }; /** * Given the location of the 'middle snake', split the diff in two parts * and recurse. * @param {string} text1 Old string to be diffed. * @param {string} text2 New string to be diffed. * @param {number} x Index of split point in text1. * @param {number} y Index of split point in text2. * @param {number} deadline Time at which to bail if not yet complete. * @return {!Array.} Array of diff tuples. * @private */ diff_match_patch.prototype.diff_bisectSplit_ = function(text1, text2, x, y, deadline) { var text1a = text1.substring(0, x); var text2a = text2.substring(0, y); var text1b = text1.substring(x); var text2b = text2.substring(y); // Compute both diffs serially. var diffs = this.diff_main(text1a, text2a, false, deadline); var diffsb = this.diff_main(text1b, text2b, false, deadline); return diffs.concat(diffsb); }; /** * Split two texts into an array of strings. Reduce the texts to a string of * hashes where each Unicode character represents one line. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {{chars1: string, chars2: string, lineArray: !Array.}} * An object containing the encoded text1, the encoded text2 and * the array of unique strings. * The zeroth element of the array of unique strings is intentionally blank. * @private */ diff_match_patch.prototype.diff_linesToChars_ = function(text1, text2) { var lineArray = []; // e.g. lineArray[4] == 'Hello\n' var lineHash = {}; // e.g. lineHash['Hello\n'] == 4 // '\x00' is a valid character, but various debuggers don't like it. // So we'll insert a junk entry to avoid generating a null character. lineArray[0] = ''; /** * Split a text into an array of strings. Reduce the texts to a string of * hashes where each Unicode character represents one line. * Modifies linearray and linehash through being a closure. * @param {string} text String to encode. * @return {string} Encoded string. * @private */ function diff_linesToCharsMunge_(text) { var chars = ''; // Walk the text, pulling out a substring for each line. // text.split('\n') would would temporarily double our memory footprint. // Modifying text would create many large strings to garbage collect. var lineStart = 0; var lineEnd = -1; // Keeping our own length variable is faster than looking it up. var lineArrayLength = lineArray.length; while (lineEnd < text.length - 1) { lineEnd = text.indexOf('\n', lineStart); if (lineEnd == -1) { lineEnd = text.length - 1; } var line = text.substring(lineStart, lineEnd + 1); if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : (lineHash[line] !== undefined)) { chars += String.fromCharCode(lineHash[line]); } else { if (lineArrayLength == maxLines) { // Bail out at 65535 because // String.fromCharCode(65536) == String.fromCharCode(0) line = text.substring(lineStart); lineEnd = text.length; } chars += String.fromCharCode(lineArrayLength); lineHash[line] = lineArrayLength; lineArray[lineArrayLength++] = line; } lineStart = lineEnd + 1; } return chars; } // Allocate 2/3rds of the space for text1, the rest for text2. var maxLines = 40000; var chars1 = diff_linesToCharsMunge_(text1); maxLines = 65535; var chars2 = diff_linesToCharsMunge_(text2); return {chars1: chars1, chars2: chars2, lineArray: lineArray}; }; /** * Rehydrate the text in a diff from a string of line hashes to real lines of * text. * @param {!Array.} diffs Array of diff tuples. * @param {!Array.} lineArray Array of unique strings. * @private */ diff_match_patch.prototype.diff_charsToLines_ = function(diffs, lineArray) { for (var x = 0; x < diffs.length; x++) { var chars = diffs[x][1]; var text = []; for (var y = 0; y < chars.length; y++) { text[y] = lineArray[chars.charCodeAt(y)]; } diffs[x][1] = text.join(''); } }; /** * Determine the common prefix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the start of each * string. */ diff_match_patch.prototype.diff_commonPrefix = function(text1, text2) { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerstart = 0; while (pointermin < pointermid) { if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { pointermin = pointermid; pointerstart = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine the common suffix of two strings. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of each string. */ diff_match_patch.prototype.diff_commonSuffix = function(text1, text2) { // Quick check for common null cases. if (!text1 || !text2 || text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { return 0; } // Binary search. // Performance analysis: https://neil.fraser.name/news/2007/10/09/ var pointermin = 0; var pointermax = Math.min(text1.length, text2.length); var pointermid = pointermax; var pointerend = 0; while (pointermin < pointermid) { if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { pointermin = pointermid; pointerend = pointermin; } else { pointermax = pointermid; } pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); } return pointermid; }; /** * Determine if the suffix of one string is the prefix of another. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {number} The number of characters common to the end of the first * string and the start of the second string. * @private */ diff_match_patch.prototype.diff_commonOverlap_ = function(text1, text2) { // Cache the text lengths to prevent multiple calls. var text1_length = text1.length; var text2_length = text2.length; // Eliminate the null case. if (text1_length == 0 || text2_length == 0) { return 0; } // Truncate the longer string. if (text1_length > text2_length) { text1 = text1.substring(text1_length - text2_length); } else if (text1_length < text2_length) { text2 = text2.substring(0, text1_length); } var text_length = Math.min(text1_length, text2_length); // Quick check for the worst case. if (text1 == text2) { return text_length; } // Start by looking for a single character match // and increase length until no match is found. // Performance analysis: https://neil.fraser.name/news/2010/11/04/ var best = 0; var length = 1; while (true) { var pattern = text1.substring(text_length - length); var found = text2.indexOf(pattern); if (found == -1) { return best; } length += found; if (found == 0 || text1.substring(text_length - length) == text2.substring(0, length)) { best = length; length++; } } }; /** * Do the two texts share a substring which is at least half the length of the * longer text? * This speedup can produce non-minimal diffs. * @param {string} text1 First string. * @param {string} text2 Second string. * @return {Array.} Five element Array, containing the prefix of * text1, the suffix of text1, the prefix of text2, the suffix of * text2 and the common middle. Or null if there was no match. * @private */ diff_match_patch.prototype.diff_halfMatch_ = function(text1, text2) { if (this.Diff_Timeout <= 0) { // Don't risk returning a non-optimal diff if we have unlimited time. return null; } var longtext = text1.length > text2.length ? text1 : text2; var shorttext = text1.length > text2.length ? text2 : text1; if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { return null; // Pointless. } var dmp = this; // 'this' becomes 'window' in a closure. /** * Does a substring of shorttext exist within longtext such that the substring * is at least half the length of longtext? * Closure, but does not reference any external variables. * @param {string} longtext Longer string. * @param {string} shorttext Shorter string. * @param {number} i Start index of quarter length substring within longtext. * @return {Array.} Five element Array, containing the prefix of * longtext, the suffix of longtext, the prefix of shorttext, the suffix * of shorttext and the common middle. Or null if there was no match. * @private */ function diff_halfMatchI_(longtext, shorttext, i) { // Start with a 1/4 length substring at position i as a seed. var seed = longtext.substring(i, i + Math.floor(longtext.length / 4)); var j = -1; var best_common = ''; var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; while ((j = shorttext.indexOf(seed, j + 1)) != -1) { var prefixLength = dmp.diff_commonPrefix(longtext.substring(i), shorttext.substring(j)); var suffixLength = dmp.diff_commonSuffix(longtext.substring(0, i), shorttext.substring(0, j)); if (best_common.length < suffixLength + prefixLength) { best_common = shorttext.substring(j - suffixLength, j) + shorttext.substring(j, j + prefixLength); best_longtext_a = longtext.substring(0, i - suffixLength); best_longtext_b = longtext.substring(i + prefixLength); best_shorttext_a = shorttext.substring(0, j - suffixLength); best_shorttext_b = shorttext.substring(j + prefixLength); } } if (best_common.length * 2 >= longtext.length) { return [best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b, best_common]; } else { return null; } } // First check if the second quarter is the seed for a half-match. var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); // Check again based on the third quarter. var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); var hm; if (!hm1 && !hm2) { return null; } else if (!hm2) { hm = hm1; } else if (!hm1) { hm = hm2; } else { // Both matched. Select the longest. hm = hm1[4].length > hm2[4].length ? hm1 : hm2; } // A half-match was found, sort out the return data. var text1_a, text1_b, text2_a, text2_b; if (text1.length > text2.length) { text1_a = hm[0]; text1_b = hm[1]; text2_a = hm[2]; text2_b = hm[3]; } else { text2_a = hm[0]; text2_b = hm[1]; text1_a = hm[2]; text1_b = hm[3]; } var mid_common = hm[4]; return [text1_a, text1_b, text2_a, text2_b, mid_common]; }; /** * Reduce the number of edits by eliminating semantically trivial equalities. * @param {!Array.} diffs Array of diff tuples. */ diff_match_patch.prototype.diff_cleanupSemantic = function(diffs) { var changes = false; var equalities = []; // Stack of indices where equalities are found. var equalitiesLength = 0; // Keeping our own length var is faster in JS. /** @type {?string} */ var lastequality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1] var pointer = 0; // Index of current position. // Number of characters that changed prior to the equality. var length_insertions1 = 0; var length_deletions1 = 0; // Number of characters that changed after the equality. var length_insertions2 = 0; var length_deletions2 = 0; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. equalities[equalitiesLength++] = pointer; length_insertions1 = length_insertions2; length_deletions1 = length_deletions2; length_insertions2 = 0; length_deletions2 = 0; lastequality = diffs[pointer][1]; } else { // An insertion or deletion. if (diffs[pointer][0] == DIFF_INSERT) { length_insertions2 += diffs[pointer][1].length; } else { length_deletions2 += diffs[pointer][1].length; } // Eliminate an equality that is smaller or equal to the edits on both // sides of it. if (lastequality && (lastequality.length <= Math.max(length_insertions1, length_deletions1)) && (lastequality.length <= Math.max(length_insertions2, length_deletions2))) { // Duplicate record. diffs.splice(equalities[equalitiesLength - 1], 0, new diff_match_patch.Diff(DIFF_DELETE, lastequality)); // Change second copy to insert. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; // Throw away the equality we just deleted. equalitiesLength--; // Throw away the previous equality (it needs to be reevaluated). equalitiesLength--; pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; length_insertions1 = 0; // Reset the counters. length_deletions1 = 0; length_insertions2 = 0; length_deletions2 = 0; lastequality = null; changes = true; } } pointer++; } // Normalize the diff. if (changes) { this.diff_cleanupMerge(diffs); } this.diff_cleanupSemanticLossless(diffs); // Find any overlaps between deletions and insertions. // e.g: abcxxxxxxdef // -> abcxxxdef // e.g: xxxabcdefxxx // -> defxxxabc // Only extract an overlap if it is as big as the edit ahead or behind it. pointer = 1; while (pointer < diffs.length) { if (diffs[pointer - 1][0] == DIFF_DELETE && diffs[pointer][0] == DIFF_INSERT) { var deletion = diffs[pointer - 1][1]; var insertion = diffs[pointer][1]; var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); if (overlap_length1 >= overlap_length2) { if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { // Overlap found. Insert an equality and trim the surrounding edits. diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))); diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); diffs[pointer + 1][1] = insertion.substring(overlap_length1); pointer++; } } else { if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { // Reverse overlap found. // Insert an equality and swap and trim the surrounding edits. diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))); diffs[pointer - 1][0] = DIFF_INSERT; diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); diffs[pointer + 1][0] = DIFF_DELETE; diffs[pointer + 1][1] = deletion.substring(overlap_length2); pointer++; } } pointer++; } pointer++; } }; /** * Look for single edits surrounded on both sides by equalities * which can be shifted sideways to align the edit to a word boundary. * e.g: The cat came. -> The cat came. * @param {!Array.} diffs Array of diff tuples. */ diff_match_patch.prototype.diff_cleanupSemanticLossless = function(diffs) { /** * Given two strings, compute a score representing whether the internal * boundary falls on logical boundaries. * Scores range from 6 (best) to 0 (worst). * Closure, but does not reference any external variables. * @param {string} one First string. * @param {string} two Second string. * @return {number} The score. * @private */ function diff_cleanupSemanticScore_(one, two) { if (!one || !two) { // Edges are the best. return 6; } // Each port of this function behaves slightly differently due to // subtle differences in each language's definition of things like // 'whitespace'. Since this function's purpose is largely cosmetic, // the choice has been made to use each language's native features // rather than force total conformity. var char1 = one.charAt(one.length - 1); var char2 = two.charAt(0); var nonAlphaNumeric1 = char1.match(diff_match_patch.nonAlphaNumericRegex_); var nonAlphaNumeric2 = char2.match(diff_match_patch.nonAlphaNumericRegex_); var whitespace1 = nonAlphaNumeric1 && char1.match(diff_match_patch.whitespaceRegex_); var whitespace2 = nonAlphaNumeric2 && char2.match(diff_match_patch.whitespaceRegex_); var lineBreak1 = whitespace1 && char1.match(diff_match_patch.linebreakRegex_); var lineBreak2 = whitespace2 && char2.match(diff_match_patch.linebreakRegex_); var blankLine1 = lineBreak1 && one.match(diff_match_patch.blanklineEndRegex_); var blankLine2 = lineBreak2 && two.match(diff_match_patch.blanklineStartRegex_); if (blankLine1 || blankLine2) { // Five points for blank lines. return 5; } else if (lineBreak1 || lineBreak2) { // Four points for line breaks. return 4; } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { // Three points for end of sentences. return 3; } else if (whitespace1 || whitespace2) { // Two points for whitespace. return 2; } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { // One point for non-alphanumeric. return 1; } return 0; } var pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { // This is a single edit surrounded by equalities. var equality1 = diffs[pointer - 1][1]; var edit = diffs[pointer][1]; var equality2 = diffs[pointer + 1][1]; // First, shift the edit as far left as possible. var commonOffset = this.diff_commonSuffix(equality1, edit); if (commonOffset) { var commonString = edit.substring(edit.length - commonOffset); equality1 = equality1.substring(0, equality1.length - commonOffset); edit = commonString + edit.substring(0, edit.length - commonOffset); equality2 = commonString + equality2; } // Second, step character by character right, looking for the best fit. var bestEquality1 = equality1; var bestEdit = edit; var bestEquality2 = equality2; var bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); while (edit.charAt(0) === equality2.charAt(0)) { equality1 += edit.charAt(0); edit = edit.substring(1) + equality2.charAt(0); equality2 = equality2.substring(1); var score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); // The >= encourages trailing rather than leading whitespace on edits. if (score >= bestScore) { bestScore = score; bestEquality1 = equality1; bestEdit = edit; bestEquality2 = equality2; } } if (diffs[pointer - 1][1] != bestEquality1) { // We have an improvement, save it back to the diff. if (bestEquality1) { diffs[pointer - 1][1] = bestEquality1; } else { diffs.splice(pointer - 1, 1); pointer--; } diffs[pointer][1] = bestEdit; if (bestEquality2) { diffs[pointer + 1][1] = bestEquality2; } else { diffs.splice(pointer + 1, 1); pointer--; } } } pointer++; } }; // Define some regex patterns for matching boundaries. diff_match_patch.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; diff_match_patch.whitespaceRegex_ = /\s/; diff_match_patch.linebreakRegex_ = /[\r\n]/; diff_match_patch.blanklineEndRegex_ = /\n\r?\n$/; diff_match_patch.blanklineStartRegex_ = /^\r?\n\r?\n/; /** * Reduce the number of edits by eliminating operationally trivial equalities. * @param {!Array.} diffs Array of diff tuples. */ diff_match_patch.prototype.diff_cleanupEfficiency = function(diffs) { var changes = false; var equalities = []; // Stack of indices where equalities are found. var equalitiesLength = 0; // Keeping our own length var is faster in JS. /** @type {?string} */ var lastequality = null; // Always equal to diffs[equalities[equalitiesLength - 1]][1] var pointer = 0; // Index of current position. // Is there an insertion operation before the last equality. var pre_ins = false; // Is there a deletion operation before the last equality. var pre_del = false; // Is there an insertion operation after the last equality. var post_ins = false; // Is there a deletion operation after the last equality. var post_del = false; while (pointer < diffs.length) { if (diffs[pointer][0] == DIFF_EQUAL) { // Equality found. if (diffs[pointer][1].length < this.Diff_EditCost && (post_ins || post_del)) { // Candidate found. equalities[equalitiesLength++] = pointer; pre_ins = post_ins; pre_del = post_del; lastequality = diffs[pointer][1]; } else { // Not a candidate, and can never become one. equalitiesLength = 0; lastequality = null; } post_ins = post_del = false; } else { // An insertion or deletion. if (diffs[pointer][0] == DIFF_DELETE) { post_del = true; } else { post_ins = true; } /* * Five types to be split: * ABXYCD * AXCD * ABXC * AXCD * ABXC */ if (lastequality && ((pre_ins && pre_del && post_ins && post_del) || ((lastequality.length < this.Diff_EditCost / 2) && (pre_ins + pre_del + post_ins + post_del) == 3))) { // Duplicate record. diffs.splice(equalities[equalitiesLength - 1], 0, new diff_match_patch.Diff(DIFF_DELETE, lastequality)); // Change second copy to insert. diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; equalitiesLength--; // Throw away the equality we just deleted; lastequality = null; if (pre_ins && pre_del) { // No changes made which could affect previous entry, keep going. post_ins = post_del = true; equalitiesLength = 0; } else { equalitiesLength--; // Throw away the previous equality. pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; post_ins = post_del = false; } changes = true; } } pointer++; } if (changes) { this.diff_cleanupMerge(diffs); } }; /** * Reorder and merge like edit sections. Merge equalities. * Any edit section can move as long as it doesn't cross an equality. * @param {!Array.} diffs Array of diff tuples. */ diff_match_patch.prototype.diff_cleanupMerge = function(diffs) { // Add a dummy entry at the end. diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, '')); var pointer = 0; var count_delete = 0; var count_insert = 0; var text_delete = ''; var text_insert = ''; var commonlength; while (pointer < diffs.length) { switch (diffs[pointer][0]) { case DIFF_INSERT: count_insert++; text_insert += diffs[pointer][1]; pointer++; break; case DIFF_DELETE: count_delete++; text_delete += diffs[pointer][1]; pointer++; break; case DIFF_EQUAL: // Upon reaching an equality, check for prior redundancies. if (count_delete + count_insert > 1) { if (count_delete !== 0 && count_insert !== 0) { // Factor out any common prefixies. commonlength = this.diff_commonPrefix(text_insert, text_delete); if (commonlength !== 0) { if ((pointer - count_delete - count_insert) > 0 && diffs[pointer - count_delete - count_insert - 1][0] == DIFF_EQUAL) { diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); } else { diffs.splice(0, 0, new diff_match_patch.Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))); pointer++; } text_insert = text_insert.substring(commonlength); text_delete = text_delete.substring(commonlength); } // Factor out any common suffixies. commonlength = this.diff_commonSuffix(text_insert, text_delete); if (commonlength !== 0) { diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; text_insert = text_insert.substring(0, text_insert.length - commonlength); text_delete = text_delete.substring(0, text_delete.length - commonlength); } } // Delete the offending records and add the merged ones. pointer -= count_delete + count_insert; diffs.splice(pointer, count_delete + count_insert); if (text_delete.length) { diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_DELETE, text_delete)); pointer++; } if (text_insert.length) { diffs.splice(pointer, 0, new diff_match_patch.Diff(DIFF_INSERT, text_insert)); pointer++; } pointer++; } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { // Merge this equality with the previous one. diffs[pointer - 1][1] += diffs[pointer][1]; diffs.splice(pointer, 1); } else { pointer++; } count_insert = 0; count_delete = 0; text_delete = ''; text_insert = ''; break; } } if (diffs[diffs.length - 1][1] === '') { diffs.pop(); // Remove the dummy entry at the end. } // Second pass: look for single edits surrounded on both sides by equalities // which can be shifted sideways to eliminate an equality. // e.g: ABAC -> ABAC var changes = false; pointer = 1; // Intentionally ignore the first and last element (don't need checking). while (pointer < diffs.length - 1) { if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { // This is a single edit surrounded by equalities. if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { // Shift the edit over the previous equality. diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; diffs.splice(pointer - 1, 1); changes = true; } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { // Shift the edit over the next equality. diffs[pointer - 1][1] += diffs[pointer + 1][1]; diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; diffs.splice(pointer + 1, 1); changes = true; } } pointer++; } // If shifts were made, the diff needs reordering and another shift sweep. if (changes) { this.diff_cleanupMerge(diffs); } }; /** * loc is a location in text1, compute and return the equivalent location in * text2. * e.g. 'The cat' vs 'The big cat', 1->1, 5->8 * @param {!Array.} diffs Array of diff tuples. * @param {number} loc Location within text1. * @return {number} Location within text2. */ diff_match_patch.prototype.diff_xIndex = function(diffs, loc) { var chars1 = 0; var chars2 = 0; var last_chars1 = 0; var last_chars2 = 0; var x; for (x = 0; x < diffs.length; x++) { if (diffs[x][0] !== DIFF_INSERT) { // Equality or deletion. chars1 += diffs[x][1].length; } if (diffs[x][0] !== DIFF_DELETE) { // Equality or insertion. chars2 += diffs[x][1].length; } if (chars1 > loc) { // Overshot the location. break; } last_chars1 = chars1; last_chars2 = chars2; } // Was the location was deleted? if (diffs.length != x && diffs[x][0] === DIFF_DELETE) { return last_chars2; } // Add the remaining character length. return last_chars2 + (loc - last_chars1); }; /** * Convert a diff array into a pretty HTML report. * @param {!Array.} diffs Array of diff tuples. * @return {string} HTML representation. */ diff_match_patch.prototype.diff_prettyHtml = function(diffs) { var html = []; var pattern_amp = /&/g; var pattern_lt = //g; var pattern_para = /\n/g; for (var x = 0; x < diffs.length; x++) { var op = diffs[x][0]; // Operation (insert, delete, equal) var data = diffs[x][1]; // Text of change. var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<') .replace(pattern_gt, '>').replace(pattern_para, '¶
    '); switch (op) { case DIFF_INSERT: html[x] = '' + text + ''; break; case DIFF_DELETE: html[x] = '' + text + ''; break; case DIFF_EQUAL: html[x] = '' + text + ''; break; } } return html.join(''); }; /** * Compute and return the source text (all equalities and deletions). * @param {!Array.} diffs Array of diff tuples. * @return {string} Source text. */ diff_match_patch.prototype.diff_text1 = function(diffs) { var text = []; for (var x = 0; x < diffs.length; x++) { if (diffs[x][0] !== DIFF_INSERT) { text[x] = diffs[x][1]; } } return text.join(''); }; /** * Compute and return the destination text (all equalities and insertions). * @param {!Array.} diffs Array of diff tuples. * @return {string} Destination text. */ diff_match_patch.prototype.diff_text2 = function(diffs) { var text = []; for (var x = 0; x < diffs.length; x++) { if (diffs[x][0] !== DIFF_DELETE) { text[x] = diffs[x][1]; } } return text.join(''); }; /** * Compute the Levenshtein distance; the number of inserted, deleted or * substituted characters. * @param {!Array.} diffs Array of diff tuples. * @return {number} Number of changes. */ diff_match_patch.prototype.diff_levenshtein = function(diffs) { var levenshtein = 0; var insertions = 0; var deletions = 0; for (var x = 0; x < diffs.length; x++) { var op = diffs[x][0]; var data = diffs[x][1]; switch (op) { case DIFF_INSERT: insertions += data.length; break; case DIFF_DELETE: deletions += data.length; break; case DIFF_EQUAL: // A deletion and an insertion is one substitution. levenshtein += Math.max(insertions, deletions); insertions = 0; deletions = 0; break; } } levenshtein += Math.max(insertions, deletions); return levenshtein; }; /** * Crush the diff into an encoded string which describes the operations * required to transform text1 into text2. * E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'. * Operations are tab-separated. Inserted text is escaped using %xx notation. * @param {!Array.} diffs Array of diff tuples. * @return {string} Delta text. */ diff_match_patch.prototype.diff_toDelta = function(diffs) { var text = []; for (var x = 0; x < diffs.length; x++) { switch (diffs[x][0]) { case DIFF_INSERT: text[x] = '+' + encodeURI(diffs[x][1]); break; case DIFF_DELETE: text[x] = '-' + diffs[x][1].length; break; case DIFF_EQUAL: text[x] = '=' + diffs[x][1].length; break; } } return text.join('\t').replace(/%20/g, ' '); }; /** * Given the original text1, and an encoded string which describes the * operations required to transform text1 into text2, compute the full diff. * @param {string} text1 Source string for the diff. * @param {string} delta Delta text. * @return {!Array.} Array of diff tuples. * @throws {!Error} If invalid input. */ diff_match_patch.prototype.diff_fromDelta = function(text1, delta) { var diffs = []; var diffsLength = 0; // Keeping our own length var is faster in JS. var pointer = 0; // Cursor in text1 var tokens = delta.split(/\t/g); for (var x = 0; x < tokens.length; x++) { // Each token begins with a one character parameter which specifies the // operation of this token (delete, insert, equality). var param = tokens[x].substring(1); switch (tokens[x].charAt(0)) { case '+': try { diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_INSERT, decodeURI(param)); } catch (ex) { // Malformed URI sequence. throw new Error('Illegal escape in diff_fromDelta: ' + param); } break; case '-': // Fall through. case '=': var n = parseInt(param, 10); if (isNaN(n) || n < 0) { throw new Error('Invalid number in diff_fromDelta: ' + param); } var text = text1.substring(pointer, pointer += n); if (tokens[x].charAt(0) == '=') { diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_EQUAL, text); } else { diffs[diffsLength++] = new diff_match_patch.Diff(DIFF_DELETE, text); } break; default: // Blank tokens are ok (from a trailing \t). // Anything else is an error. if (tokens[x]) { throw new Error('Invalid diff operation in diff_fromDelta: ' + tokens[x]); } } } if (pointer != text1.length) { throw new Error('Delta length (' + pointer + ') does not equal source text length (' + text1.length + ').'); } return diffs; }; // MATCH FUNCTIONS /** * Locate the best instance of 'pattern' in 'text' near 'loc'. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. */ diff_match_patch.prototype.match_main = function(text, pattern, loc) { // Check for null inputs. if (text == null || pattern == null || loc == null) { throw new Error('Null input. (match_main)'); } loc = Math.max(0, Math.min(loc, text.length)); if (text == pattern) { // Shortcut (potentially not guaranteed by the algorithm) return 0; } else if (!text.length) { // Nothing to match. return -1; } else if (text.substring(loc, loc + pattern.length) == pattern) { // Perfect match at the perfect spot! (Includes case of null pattern) return loc; } else { // Do a fuzzy compare. return this.match_bitap_(text, pattern, loc); } }; /** * Locate the best instance of 'pattern' in 'text' near 'loc' using the * Bitap algorithm. * @param {string} text The text to search. * @param {string} pattern The pattern to search for. * @param {number} loc The location to search around. * @return {number} Best match index or -1. * @private */ diff_match_patch.prototype.match_bitap_ = function(text, pattern, loc) { if (pattern.length > this.Match_MaxBits) { throw new Error('Pattern too long for this browser.'); } // Initialise the alphabet. var s = this.match_alphabet_(pattern); var dmp = this; // 'this' becomes 'window' in a closure. /** * Compute and return the score for a match with e errors and x location. * Accesses loc and pattern through being a closure. * @param {number} e Number of errors in match. * @param {number} x Location of match. * @return {number} Overall score for match (0.0 = good, 1.0 = bad). * @private */ function match_bitapScore_(e, x) { var accuracy = e / pattern.length; var proximity = Math.abs(loc - x); if (!dmp.Match_Distance) { // Dodge divide by zero error. return proximity ? 1.0 : accuracy; } return accuracy + (proximity / dmp.Match_Distance); } // Highest score beyond which we give up. var score_threshold = this.Match_Threshold; // Is there a nearby exact match? (speedup) var best_loc = text.indexOf(pattern, loc); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); // What about in the other direction? (speedup) best_loc = text.lastIndexOf(pattern, loc + pattern.length); if (best_loc != -1) { score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); } } // Initialise the bit arrays. var matchmask = 1 << (pattern.length - 1); best_loc = -1; var bin_min, bin_mid; var bin_max = pattern.length + text.length; var last_rd; for (var d = 0; d < pattern.length; d++) { // Scan for the best match; each iteration allows for one more error. // Run a binary search to determine how far from 'loc' we can stray at this // error level. bin_min = 0; bin_mid = bin_max; while (bin_min < bin_mid) { if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { bin_min = bin_mid; } else { bin_max = bin_mid; } bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); } // Use the result from this iteration as the maximum for the next. bin_max = bin_mid; var start = Math.max(1, loc - bin_mid + 1); var finish = Math.min(loc + bin_mid, text.length) + pattern.length; var rd = Array(finish + 2); rd[finish + 1] = (1 << d) - 1; for (var j = finish; j >= start; j--) { // The alphabet (s) is a sparse hash, so the following line generates // warnings. var charMatch = s[text.charAt(j - 1)]; if (d === 0) { // First pass: exact match. rd[j] = ((rd[j + 1] << 1) | 1) & charMatch; } else { // Subsequent passes: fuzzy match. rd[j] = (((rd[j + 1] << 1) | 1) & charMatch) | (((last_rd[j + 1] | last_rd[j]) << 1) | 1) | last_rd[j + 1]; } if (rd[j] & matchmask) { var score = match_bitapScore_(d, j - 1); // This match will almost certainly be better than any existing match. // But check anyway. if (score <= score_threshold) { // Told you so. score_threshold = score; best_loc = j - 1; if (best_loc > loc) { // When passing loc, don't exceed our current distance from loc. start = Math.max(1, 2 * loc - best_loc); } else { // Already passed loc, downhill from here on in. break; } } } } // No hope for a (better) match at greater error levels. if (match_bitapScore_(d + 1, loc) > score_threshold) { break; } last_rd = rd; } return best_loc; }; /** * Initialise the alphabet for the Bitap algorithm. * @param {string} pattern The text to encode. * @return {!Object} Hash of character locations. * @private */ diff_match_patch.prototype.match_alphabet_ = function(pattern) { var s = {}; for (var i = 0; i < pattern.length; i++) { s[pattern.charAt(i)] = 0; } for (var i = 0; i < pattern.length; i++) { s[pattern.charAt(i)] |= 1 << (pattern.length - i - 1); } return s; }; // PATCH FUNCTIONS /** * Increase the context until it is unique, * but don't let the pattern expand beyond Match_MaxBits. * @param {!diff_match_patch.patch_obj} patch The patch to grow. * @param {string} text Source text. * @private */ diff_match_patch.prototype.patch_addContext_ = function(patch, text) { if (text.length == 0) { return; } if (patch.start2 === null) { throw Error('patch not initialized'); } var pattern = text.substring(patch.start2, patch.start2 + patch.length1); var padding = 0; // Look for the first and last matches of pattern in text. If two different // matches are found, increase the pattern length. while (text.indexOf(pattern) != text.lastIndexOf(pattern) && pattern.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin) { padding += this.Patch_Margin; pattern = text.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding); } // Add one chunk for good luck. padding += this.Patch_Margin; // Add the prefix. var prefix = text.substring(patch.start2 - padding, patch.start2); if (prefix) { patch.diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, prefix)); } // Add the suffix. var suffix = text.substring(patch.start2 + patch.length1, patch.start2 + patch.length1 + padding); if (suffix) { patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, suffix)); } // Roll back the start points. patch.start1 -= prefix.length; patch.start2 -= prefix.length; // Extend the lengths. patch.length1 += prefix.length + suffix.length; patch.length2 += prefix.length + suffix.length; }; /** * Compute a list of patches to turn text1 into text2. * Use diffs if provided, otherwise compute it ourselves. * There are four ways to call this function, depending on what data is * available to the caller: * Method 1: * a = text1, b = text2 * Method 2: * a = diffs * Method 3 (optimal): * a = text1, b = diffs * Method 4 (deprecated, use method 3): * a = text1, b = text2, c = diffs * * @param {string|!Array.} a text1 (methods 1,3,4) or * Array of diff tuples for text1 to text2 (method 2). * @param {string|!Array.} opt_b text2 (methods 1,4) or * Array of diff tuples for text1 to text2 (method 3) or undefined (method 2). * @param {string|!Array.} opt_c Array of diff tuples * for text1 to text2 (method 4) or undefined (methods 1,2,3). * @return {!Array.} Array of Patch objects. */ diff_match_patch.prototype.patch_make = function(a, opt_b, opt_c) { var text1, diffs; if (typeof a == 'string' && typeof opt_b == 'string' && typeof opt_c == 'undefined') { // Method 1: text1, text2 // Compute diffs from text1 and text2. text1 = /** @type {string} */(a); diffs = this.diff_main(text1, /** @type {string} */(opt_b), true); if (diffs.length > 2) { this.diff_cleanupSemantic(diffs); this.diff_cleanupEfficiency(diffs); } } else if (a && typeof a == 'object' && typeof opt_b == 'undefined' && typeof opt_c == 'undefined') { // Method 2: diffs // Compute text1 from diffs. diffs = /** @type {!Array.} */(a); text1 = this.diff_text1(diffs); } else if (typeof a == 'string' && opt_b && typeof opt_b == 'object' && typeof opt_c == 'undefined') { // Method 3: text1, diffs text1 = /** @type {string} */(a); diffs = /** @type {!Array.} */(opt_b); } else if (typeof a == 'string' && typeof opt_b == 'string' && opt_c && typeof opt_c == 'object') { // Method 4: text1, text2, diffs // text2 is not used. text1 = /** @type {string} */(a); diffs = /** @type {!Array.} */(opt_c); } else { throw new Error('Unknown call format to patch_make.'); } if (diffs.length === 0) { return []; // Get rid of the null case. } var patches = []; var patch = new diff_match_patch.patch_obj(); var patchDiffLength = 0; // Keeping our own length var is faster in JS. var char_count1 = 0; // Number of characters into the text1 string. var char_count2 = 0; // Number of characters into the text2 string. // Start with text1 (prepatch_text) and apply the diffs until we arrive at // text2 (postpatch_text). We recreate the patches one by one to determine // context info. var prepatch_text = text1; var postpatch_text = text1; for (var x = 0; x < diffs.length; x++) { var diff_type = diffs[x][0]; var diff_text = diffs[x][1]; if (!patchDiffLength && diff_type !== DIFF_EQUAL) { // A new patch starts here. patch.start1 = char_count1; patch.start2 = char_count2; } switch (diff_type) { case DIFF_INSERT: patch.diffs[patchDiffLength++] = diffs[x]; patch.length2 += diff_text.length; postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + postpatch_text.substring(char_count2); break; case DIFF_DELETE: patch.length1 += diff_text.length; patch.diffs[patchDiffLength++] = diffs[x]; postpatch_text = postpatch_text.substring(0, char_count2) + postpatch_text.substring(char_count2 + diff_text.length); break; case DIFF_EQUAL: if (diff_text.length <= 2 * this.Patch_Margin && patchDiffLength && diffs.length != x + 1) { // Small equality inside a patch. patch.diffs[patchDiffLength++] = diffs[x]; patch.length1 += diff_text.length; patch.length2 += diff_text.length; } else if (diff_text.length >= 2 * this.Patch_Margin) { // Time for a new patch. if (patchDiffLength) { this.patch_addContext_(patch, prepatch_text); patches.push(patch); patch = new diff_match_patch.patch_obj(); patchDiffLength = 0; // Unlike Unidiff, our patch lists have a rolling context. // https://github.com/google/diff-match-patch/wiki/Unidiff // Update prepatch text & pos to reflect the application of the // just completed patch. prepatch_text = postpatch_text; char_count1 = char_count2; } } break; } // Update the current character count. if (diff_type !== DIFF_INSERT) { char_count1 += diff_text.length; } if (diff_type !== DIFF_DELETE) { char_count2 += diff_text.length; } } // Pick up the leftover patch if not empty. if (patchDiffLength) { this.patch_addContext_(patch, prepatch_text); patches.push(patch); } return patches; }; /** * Given an array of patches, return another array that is identical. * @param {!Array.} patches Array of Patch objects. * @return {!Array.} Array of Patch objects. */ diff_match_patch.prototype.patch_deepCopy = function(patches) { // Making deep copies is hard in JavaScript. var patchesCopy = []; for (var x = 0; x < patches.length; x++) { var patch = patches[x]; var patchCopy = new diff_match_patch.patch_obj(); patchCopy.diffs = []; for (var y = 0; y < patch.diffs.length; y++) { patchCopy.diffs[y] = new diff_match_patch.Diff(patch.diffs[y][0], patch.diffs[y][1]); } patchCopy.start1 = patch.start1; patchCopy.start2 = patch.start2; patchCopy.length1 = patch.length1; patchCopy.length2 = patch.length2; patchesCopy[x] = patchCopy; } return patchesCopy; }; /** * Merge a set of patches onto the text. Return a patched text, as well * as a list of true/false values indicating which patches were applied. * @param {!Array.} patches Array of Patch objects. * @param {string} text Old text. * @return {!Array.>} Two element Array, containing the * new text and an array of boolean values. */ diff_match_patch.prototype.patch_apply = function(patches, text) { if (patches.length == 0) { return [text, []]; } // Deep copy the patches so that no changes are made to originals. patches = this.patch_deepCopy(patches); var nullPadding = this.patch_addPadding(patches); text = nullPadding + text + nullPadding; this.patch_splitMax(patches); // delta keeps track of the offset between the expected and actual location // of the previous patch. If there are patches expected at positions 10 and // 20, but the first patch was found at 12, delta is 2 and the second patch // has an effective expected position of 22. var delta = 0; var results = []; for (var x = 0; x < patches.length; x++) { var expected_loc = patches[x].start2 + delta; var text1 = this.diff_text1(patches[x].diffs); var start_loc; var end_loc = -1; if (text1.length > this.Match_MaxBits) { // patch_splitMax will only provide an oversized pattern in the case of // a monster delete. start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits), expected_loc); if (start_loc != -1) { end_loc = this.match_main(text, text1.substring(text1.length - this.Match_MaxBits), expected_loc + text1.length - this.Match_MaxBits); if (end_loc == -1 || start_loc >= end_loc) { // Can't find valid trailing context. Drop this patch. start_loc = -1; } } } else { start_loc = this.match_main(text, text1, expected_loc); } if (start_loc == -1) { // No match found. :( results[x] = false; // Subtract the delta for this failed patch from subsequent patches. delta -= patches[x].length2 - patches[x].length1; } else { // Found a match. :) results[x] = true; delta = start_loc - expected_loc; var text2; if (end_loc == -1) { text2 = text.substring(start_loc, start_loc + text1.length); } else { text2 = text.substring(start_loc, end_loc + this.Match_MaxBits); } if (text1 == text2) { // Perfect match, just shove the replacement text in. text = text.substring(0, start_loc) + this.diff_text2(patches[x].diffs) + text.substring(start_loc + text1.length); } else { // Imperfect match. Run a diff to get a framework of equivalent // indices. var diffs = this.diff_main(text1, text2, false); if (text1.length > this.Match_MaxBits && this.diff_levenshtein(diffs) / text1.length > this.Patch_DeleteThreshold) { // The end points match, but the content is unacceptably bad. results[x] = false; } else { this.diff_cleanupSemanticLossless(diffs); var index1 = 0; var index2; for (var y = 0; y < patches[x].diffs.length; y++) { var mod = patches[x].diffs[y]; if (mod[0] !== DIFF_EQUAL) { index2 = this.diff_xIndex(diffs, index1); } if (mod[0] === DIFF_INSERT) { // Insertion text = text.substring(0, start_loc + index2) + mod[1] + text.substring(start_loc + index2); } else if (mod[0] === DIFF_DELETE) { // Deletion text = text.substring(0, start_loc + index2) + text.substring(start_loc + this.diff_xIndex(diffs, index1 + mod[1].length)); } if (mod[0] !== DIFF_DELETE) { index1 += mod[1].length; } } } } } } // Strip the padding off. text = text.substring(nullPadding.length, text.length - nullPadding.length); return [text, results]; }; /** * Add some padding on text start and end so that edges can match something. * Intended to be called only from within patch_apply. * @param {!Array.} patches Array of Patch objects. * @return {string} The padding string added to each side. */ diff_match_patch.prototype.patch_addPadding = function(patches) { var paddingLength = this.Patch_Margin; var nullPadding = ''; for (var x = 1; x <= paddingLength; x++) { nullPadding += String.fromCharCode(x); } // Bump all the patches forward. for (var x = 0; x < patches.length; x++) { patches[x].start1 += paddingLength; patches[x].start2 += paddingLength; } // Add some padding on start of first diff. var patch = patches[0]; var diffs = patch.diffs; if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) { // Add nullPadding equality. diffs.unshift(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding)); patch.start1 -= paddingLength; // Should be 0. patch.start2 -= paddingLength; // Should be 0. patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs[0][1].length) { // Grow first equality. var extraLength = paddingLength - diffs[0][1].length; diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]; patch.start1 -= extraLength; patch.start2 -= extraLength; patch.length1 += extraLength; patch.length2 += extraLength; } // Add some padding on end of last diff. patch = patches[patches.length - 1]; diffs = patch.diffs; if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) { // Add nullPadding equality. diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, nullPadding)); patch.length1 += paddingLength; patch.length2 += paddingLength; } else if (paddingLength > diffs[diffs.length - 1][1].length) { // Grow last equality. var extraLength = paddingLength - diffs[diffs.length - 1][1].length; diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength); patch.length1 += extraLength; patch.length2 += extraLength; } return nullPadding; }; /** * Look through the patches and break up any which are longer than the maximum * limit of the match algorithm. * Intended to be called only from within patch_apply. * @param {!Array.} patches Array of Patch objects. */ diff_match_patch.prototype.patch_splitMax = function(patches) { var patch_size = this.Match_MaxBits; for (var x = 0; x < patches.length; x++) { if (patches[x].length1 <= patch_size) { continue; } var bigpatch = patches[x]; // Remove the big old patch. patches.splice(x--, 1); var start1 = bigpatch.start1; var start2 = bigpatch.start2; var precontext = ''; while (bigpatch.diffs.length !== 0) { // Create one of several smaller patches. var patch = new diff_match_patch.patch_obj(); var empty = true; patch.start1 = start1 - precontext.length; patch.start2 = start2 - precontext.length; if (precontext !== '') { patch.length1 = patch.length2 = precontext.length; patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, precontext)); } while (bigpatch.diffs.length !== 0 && patch.length1 < patch_size - this.Patch_Margin) { var diff_type = bigpatch.diffs[0][0]; var diff_text = bigpatch.diffs[0][1]; if (diff_type === DIFF_INSERT) { // Insertions are harmless. patch.length2 += diff_text.length; start2 += diff_text.length; patch.diffs.push(bigpatch.diffs.shift()); empty = false; } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 && patch.diffs[0][0] == DIFF_EQUAL && diff_text.length > 2 * patch_size) { // This is a large deletion. Let it pass in one chunk. patch.length1 += diff_text.length; start1 += diff_text.length; empty = false; patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text)); bigpatch.diffs.shift(); } else { // Deletion or equality. Only take as much as we can stomach. diff_text = diff_text.substring(0, patch_size - patch.length1 - this.Patch_Margin); patch.length1 += diff_text.length; start1 += diff_text.length; if (diff_type === DIFF_EQUAL) { patch.length2 += diff_text.length; start2 += diff_text.length; } else { empty = false; } patch.diffs.push(new diff_match_patch.Diff(diff_type, diff_text)); if (diff_text == bigpatch.diffs[0][1]) { bigpatch.diffs.shift(); } else { bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diff_text.length); } } } // Compute the head context for the next patch. precontext = this.diff_text2(patch.diffs); precontext = precontext.substring(precontext.length - this.Patch_Margin); // Append the end context for this patch. var postcontext = this.diff_text1(bigpatch.diffs) .substring(0, this.Patch_Margin); if (postcontext !== '') { patch.length1 += postcontext.length; patch.length2 += postcontext.length; if (patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) { patch.diffs[patch.diffs.length - 1][1] += postcontext; } else { patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, postcontext)); } } if (!empty) { patches.splice(++x, 0, patch); } } } }; /** * Take a list of patches and return a textual representation. * @param {!Array.} patches Array of Patch objects. * @return {string} Text representation of patches. */ diff_match_patch.prototype.patch_toText = function(patches) { var text = []; for (var x = 0; x < patches.length; x++) { text[x] = patches[x]; } return text.join(''); }; /** * Parse a textual representation of patches and return a list of Patch objects. * @param {string} textline Text representation of patches. * @return {!Array.} Array of Patch objects. * @throws {!Error} If invalid input. */ diff_match_patch.prototype.patch_fromText = function(textline) { var patches = []; if (!textline) { return patches; } var text = textline.split('\n'); var textPointer = 0; var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; while (textPointer < text.length) { var m = text[textPointer].match(patchHeader); if (!m) { throw new Error('Invalid patch string: ' + text[textPointer]); } var patch = new diff_match_patch.patch_obj(); patches.push(patch); patch.start1 = parseInt(m[1], 10); if (m[2] === '') { patch.start1--; patch.length1 = 1; } else if (m[2] == '0') { patch.length1 = 0; } else { patch.start1--; patch.length1 = parseInt(m[2], 10); } patch.start2 = parseInt(m[3], 10); if (m[4] === '') { patch.start2--; patch.length2 = 1; } else if (m[4] == '0') { patch.length2 = 0; } else { patch.start2--; patch.length2 = parseInt(m[4], 10); } textPointer++; while (textPointer < text.length) { var sign = text[textPointer].charAt(0); try { var line = decodeURI(text[textPointer].substring(1)); } catch (ex) { // Malformed URI sequence. throw new Error('Illegal escape in patch_fromText: ' + line); } if (sign == '-') { // Deletion. patch.diffs.push(new diff_match_patch.Diff(DIFF_DELETE, line)); } else if (sign == '+') { // Insertion. patch.diffs.push(new diff_match_patch.Diff(DIFF_INSERT, line)); } else if (sign == ' ') { // Minor equality. patch.diffs.push(new diff_match_patch.Diff(DIFF_EQUAL, line)); } else if (sign == '@') { // Start of next patch. break; } else if (sign === '') { // Blank line? Whatever. } else { // WTF? throw new Error('Invalid patch mode "' + sign + '" in: ' + line); } textPointer++; } } return patches; }; /** * Class representing one patch operation. * @constructor */ diff_match_patch.patch_obj = function() { /** @type {!Array.} */ this.diffs = []; /** @type {?number} */ this.start1 = null; /** @type {?number} */ this.start2 = null; /** @type {number} */ this.length1 = 0; /** @type {number} */ this.length2 = 0; }; /** * Emulate GNU diff's format. * Header: @@ -382,8 +481,9 @@ * Indices are printed as 1-based, not 0-based. * @return {string} The GNU diff string. */ diff_match_patch.patch_obj.prototype.toString = function() { var coords1, coords2; if (this.length1 === 0) { coords1 = this.start1 + ',0'; } else if (this.length1 == 1) { coords1 = this.start1 + 1; } else { coords1 = (this.start1 + 1) + ',' + this.length1; } if (this.length2 === 0) { coords2 = this.start2 + ',0'; } else if (this.length2 == 1) { coords2 = this.start2 + 1; } else { coords2 = (this.start2 + 1) + ',' + this.length2; } var text = ['@@ -' + coords1 + ' +' + coords2 + ' @@\n']; var op; // Escape the body of the patch with %xx notation. for (var x = 0; x < this.diffs.length; x++) { switch (this.diffs[x][0]) { case DIFF_INSERT: op = '+'; break; case DIFF_DELETE: op = '-'; break; case DIFF_EQUAL: op = ' '; break; } text[x + 1] = op + encodeURI(this.diffs[x][1]) + '\n'; } return text.join('').replace(/%20/g, ' '); }; // STRIP_FOR_CLOSURE // Lines below here will not be included in the Closure-compatible library. // Export these global variables so that they survive Google's JS compiler. // In a browser, 'this' will be 'window'. // Users of node.js should 'require' the uncompressed version since Google's // JS compiler may break the following exports for non-browser environments. /** @suppress {globalThis} */ this['diff_match_patch'] = diff_match_patch; /** @suppress {globalThis} */ this['DIFF_DELETE'] = DIFF_DELETE; /** @suppress {globalThis} */ this['DIFF_INSERT'] = DIFF_INSERT; /** @suppress {globalThis} */ this['DIFF_EQUAL'] = DIFF_EQUAL; ================================================ FILE: third_party/JSHint/LICENSE ================================================ Copyright 2012 Anton Kovalyov (http://jshint.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: third_party/JSHint/README.md ================================================ # JSHint, A Static Code Analysis Tool for JavaScript \[ [Use it online](http://jshint.com/) • [Docs](http://jshint.com/docs/) • [FAQ](http://jshint.com/docs/faq) • [Install](http://jshint.com/install/) • [Contribute](http://jshint.com/contribute/) • [Blog](http://jshint.com/blog/) • [Twitter](https://twitter.com/jshint/) \] [![NPM version](https://img.shields.io/npm/v/jshint.svg?style=flat)](https://www.npmjs.com/package/jshint) [![Linux Build Status](https://img.shields.io/travis/jshint/jshint/master.svg?style=flat&label=Linux%20build)](https://travis-ci.org/jshint/jshint) [![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) [![Dependency Status](https://img.shields.io/david/jshint/jshint.svg?style=flat)](https://david-dm.org/jshint/jshint) [![devDependency Status](https://img.shields.io/david/dev/jshint/jshint.svg?style=flat)](https://david-dm.org/jshint/jshint#info=devDependencies) [![Coverage Status](https://img.shields.io/coveralls/jshint/jshint.svg?style=flat)](https://coveralls.io/r/jshint/jshint?branch=master) JSHint is a community-driven tool that detects errors and potential problems in JavaScript code. Since JSHint is so flexible, you can easily adjust it in the environment you expect your code to execute. JSHint is open source and will always stay this way. ## Our goal The project aims to help JavaScript developers write complex programs without worrying about typos and language gotchas. Any code base eventually becomes huge at some point, so simple mistakes — that would not show themselves when written — can become show stoppers and add extra hours of debugging. So, static code analysis tools come into play and help developers spot such problems. JSHint scans a program written in JavaScript and reports about commonly made mistakes and potential bugs. The potential problem could be a syntax error, a bug due to an implicit type conversion, a leaking variable, or something else entirely. Only 15% of all programs linted on [jshint.com](http://jshint.com) pass the JSHint checks. In all other cases, JSHint finds some red flags that could've been bugs or potential problems. Please note, that while static code analysis tools can spot many different kind of mistakes, it can't detect if your program is correct, fast or has memory leaks. You should always combine tools like JSHint with unit and functional tests as well as with code reviews. ## Reporting a bug To report a bug simply create a [new GitHub Issue](https://github.com/jshint/jshint/issues/new) and describe your problem or suggestion. We welcome all kinds of feedback regarding JSHint including but not limited to: * When JSHint doesn't work as expected * When JSHint complains about valid JavaScript code that works in all browsers * When you simply want a new option or feature Before reporting a bug, please look around to see if there are any open or closed tickets that discuss your issue, and remember the wisdom: pull request > bug report > tweet. ## Who uses JSHint? Engineers from these companies and projects use JSHint: * [Mozilla](https://www.mozilla.org/) * [Wikipedia](https://wikipedia.org/) * [Facebook](https://facebook.com/) * [Twitter](https://twitter.com/) * [Bootstrap](http://getbootstrap.com/) * [Disqus](https://disqus.com/) * [Medium](https://medium.com/) * [Yahoo!](https://yahoo.com/) * [SmugMug](http://smugmug.com/) * [jQuery](http://jquery.com/) * [PDF.js](http://mozilla.github.io/pdf.js) * [Coursera](http://coursera.com/) * [Adobe Brackets](http://brackets.io/) * [Apache Cordova](http://cordova.io/) * [RedHat](http://redhat.com/) * [SoundCloud](http://soundcloud.com/) * [Nodejitsu](http://nodejitsu.com/) * [Yelp](https://yelp.com/) * [Voxer](http://voxer.com/) * [EnyoJS](http://enyojs.com/) * [QuickenLoans](http://quickenloans.com/) * [Cloud9](http://c9.io/) * [CodeClimate](https://codeclimate.com/) * [Zendesk](http://zendesk.com/) * [Apache CouchDB](http://couchdb.apache.org/) * [Google](https://www.google.com/) * [Codacy](https://www.codacy.com) [ref](https://support.codacy.com/hc/en-us/articles/207995005-Special-Thanks) And many more! ## License Most files are published using [the standard MIT Expat license](https://www.gnu.org/licenses/license-list.html#Expat). One file, however, is provided under a slightly modified version of that license. The so-called [JSON license](https://www.gnu.org/licenses/license-list.html#JSON) is a non-free license, and unfortunately, we can't change it due to historical reasons. This license is included as an in-line within the file it concerns. ## The JSHint Team JSHint is currently maintained by [Rick Waldron](https://github.com/rwaldron/), [Caitlin Potter](https://github.com/caitp/), [Mike Pennisi](https://github.com/jugglinmike/), and [Luke Page](https://github.com/lukeapage). You can reach them via admin@jshint.org. ## Previous Maintainers Originating from the JSLint project in 2010, JSHint has been maintained by a number of dedicated individuals. In chronological order, they are: Douglas Crockford, Anton Kovalyov, and Mike Sherov. We appreciate their long-term commitment! ## Thank you! We really appreciate all kinds of feedback and contributions. Thanks for using and supporting JSHint! ================================================ FILE: third_party/JSHint/jshint.js ================================================ /*! 2.9.6 */ var JSHINT; if (typeof window === 'undefined') window = {}; (function () { var require; require=(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= 65 && i <= 90 || // A-Z i === 95 || // _ i >= 97 && i <= 122; // a-z } var identifierPartTable = []; for (var i = 0; i < 128; i++) { identifierPartTable[i] = identifierStartTable[i] || // $, _, A-Z, a-z i >= 48 && i <= 57; // 0-9 } module.exports = { asciiIdentifierStartTable: identifierStartTable, asciiIdentifierPartTable: identifierPartTable }; },{}],2:[function(require,module,exports){ module.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])*$/; },{}],3:[function(require,module,exports){ var 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'; var arr = str.split(',').map(function(code) { return parseInt(code, 10); }); module.exports = arr; },{}],4:[function(require,module,exports){ var 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'; var arr = str.split(',').map(function(code) { return parseInt(code, 10); }); module.exports = arr; },{}],5:[function(require,module,exports){ // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // when used in node, this will actually load the util module we depend on // versus loading the builtin util module as happens otherwise // this is a bug in node module loading as far as I am concerned var util = require('util/'); var pSlice = Array.prototype.slice; var hasOwn = Object.prototype.hasOwnProperty; // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = stackStartFunction.name; var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && !isFinite(value)) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; // if one is a primitive, the other must be same if (util.isPrimitive(a) || util.isPrimitive(b)) { return a === b; } var aIsArgs = isArguments(a), bIsArgs = isArguments(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } var ka = objectKeys(a), kb = objectKeys(b), key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (util.isString(expected)) { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; },{"util/":10}],6:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],7:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],8:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],9:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],10:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":9,"_process":7,"inherits":8}],11:[function(require,module,exports){ (function (global){ /*global window, global*/ var util = require("util") var assert = require("assert") var now = require("date-now") var slice = Array.prototype.slice var console var times = {} if (typeof global !== "undefined" && global.console) { console = global.console } else if (typeof window !== "undefined" && window.console) { console = window.console } else { console = {} } var functions = [ [log, "log"], [info, "info"], [warn, "warn"], [error, "error"], [time, "time"], [timeEnd, "timeEnd"], [trace, "trace"], [dir, "dir"], [consoleAssert, "assert"] ] for (var i = 0; i < functions.length; i++) { var tuple = functions[i] var f = tuple[0] var name = tuple[1] if (!console[name]) { console[name] = f } } module.exports = console function log() {} function info() { console.log.apply(console, arguments) } function warn() { console.log.apply(console, arguments) } function error() { console.warn.apply(console, arguments) } function time(label) { times[label] = now() } function timeEnd(label) { var time = times[label] if (!time) { throw new Error("No such label: " + label) } var duration = now() - time console.log(label + ": " + duration + "ms") } function trace() { var err = new Error() err.name = "Trace" err.message = util.format.apply(null, arguments) console.error(err.stack) } function dir(object) { console.log(util.inspect(object) + "\n") } function consoleAssert(expression) { if (!expression) { var arr = slice.call(arguments, 1) assert.ok(false, util.format.apply(null, arr)) } } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"assert":5,"date-now":12,"util":10}],12:[function(require,module,exports){ module.exports = now function now() { return new Date().getTime() } },{}],13:[function(require,module,exports){ (function (global){ /** * @license * Lodash * Copyright JS Foundation and other contributors * Released under MIT license * Based on Underscore.js 1.8.3 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.10'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', 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', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** 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/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ 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 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Gets the value at `key`, unless `key` is "__proto__". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { return key == '__proto__' ? undefined : object[key]; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); return result; } if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { var index = -1; iteratees = arrayMap(iteratees.length ? iteratees : [identity], baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array == null ? 0 : array.length, valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '

    ' + func(text) + '

    '; * }); * * p('fred, barney, & pebbles'); * // => '

    fred, barney, & pebbles

    ' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement(''); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, & pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<%- value %>'); * compiled({ 'value': '