diff --git a/.gitattributes b/.gitattributes index c7d9f3332a950355d5a77d85000f05e6f45435ea..669e9ba17c56825a7fd26e47a4bca3d80d6a9b0a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -32,3 +32,37 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +music/(((stereofect)))_Winter_Solstice_2012.mp3 filter=lfs diff=lfs merge=lfs -text +music/Adversity.mp3 filter=lfs diff=lfs merge=lfs -text +music/Adversity.wav filter=lfs diff=lfs merge=lfs -text +music/all_ages_bitcrusher.mp3 filter=lfs diff=lfs merge=lfs -text +music/Ant_Neely_-_07_-_Not_Fit_For_Human_Consumption.mp3 filter=lfs diff=lfs merge=lfs -text +music/BLEO_-_02_-_Tart_Pts_1__2_feat_KeFF.mp3 filter=lfs diff=lfs merge=lfs -text +music/BLEO_-_04_-_Death_Destroyer_Radio_Edit_feat_Rhinostrich.mp3 filter=lfs diff=lfs merge=lfs -text +music/Boss[[:space:]]Loop[[:space:]]1.mp3 filter=lfs diff=lfs merge=lfs -text +music/Boss[[:space:]]Loop[[:space:]]1.wav filter=lfs diff=lfs merge=lfs -text +music/Broke_For_Free_-_01_-_Night_Owl.mp3 filter=lfs diff=lfs merge=lfs -text +music/conspiracy_bitcrusher_final.mp3 filter=lfs diff=lfs merge=lfs -text +music/Eric_Skiff_-_06_-_Searching.mp3 filter=lfs diff=lfs merge=lfs -text +music/Eric_Skiff_-_09_-_Come_and_Find_Me_-_B_mix.mp3 filter=lfs diff=lfs merge=lfs -text +music/Fex_coming_soon.mp3 filter=lfs diff=lfs merge=lfs -text +music/gurh.mp3 filter=lfs diff=lfs merge=lfs -text +music/intricate_cloudy_sin.mp3 filter=lfs diff=lfs merge=lfs -text +music/Jackson_D_Zero_One.mp3 filter=lfs diff=lfs merge=lfs -text +music/Obsibilo_-_02_-_Comme_Des_Orages.mp3 filter=lfs diff=lfs merge=lfs -text +music/Obsibilo_-_Soixante-8.mp3 filter=lfs diff=lfs merge=lfs -text +music/Revolution_Void_-_08_-_Obscure_Terrain.mp3 filter=lfs diff=lfs merge=lfs -text +music/RoccoW_-_Messeah.mp3 filter=lfs diff=lfs merge=lfs -text +music/Rolemusic_-_07_-_Beach_Wedding_Dance.mp3 filter=lfs diff=lfs merge=lfs -text +music/Roots[[:space:]]of[[:space:]]Supremacy.mp3 filter=lfs diff=lfs merge=lfs -text +music/Roots[[:space:]]of[[:space:]]Supremacy.wav filter=lfs diff=lfs merge=lfs -text +music/Skizofonik_System.mp3 filter=lfs diff=lfs merge=lfs -text +music/Spectrofuzz_Sunset_84.mp3 filter=lfs diff=lfs merge=lfs -text +music/Sycamore_Drive_-_03_-_The_Waves_Call_Her_Name.mp3 filter=lfs diff=lfs merge=lfs -text +music/ThatAndyGuy-Chip-loop.mp3 filter=lfs diff=lfs merge=lfs -text +music/ThatAndyGuy-Chip.mp3 filter=lfs diff=lfs merge=lfs -text +music/Tortue_Super_Sonic_-_11_-_Y.mp3 filter=lfs diff=lfs merge=lfs -text +music/Various_Artists_-_15_-_Slimeball_vomit.mp3 filter=lfs diff=lfs merge=lfs -text +music/Vernon_Lenoir_-_Brazilicon_alley.mp3 filter=lfs diff=lfs merge=lfs -text +music/what.mp3 filter=lfs diff=lfs merge=lfs -text +music/Yonnie_The_Green.mp3 filter=lfs diff=lfs merge=lfs -text diff --git a/.nojekyll b/.nojekyll new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..ebaba6dc5bdf6f104c396fc89087a793a9ac9ad1 --- /dev/null +++ b/Makefile @@ -0,0 +1,137 @@ +# Partially based off of: +# http://nefariousdesigns.co.uk/website-builds-using-make.html + +# if a mod is specified but doesn't exist, raise an error +err:=$(shell if [ ! -z '$(mod)' ] && [ ! -d 'mods/$(mod)' ]; then echo 'Mod [$(mod)] not found!'; fi) +ifneq '$(err)' '' +$(error $(err)) +endif + +mod-dir=$(shell if [ -z '$(mod)' ]; then echo 'default'; else echo $(mod); fi) + +err:=$(shell if [ ! -f 'mods/$(mod-dir)/intro.js' ]; then echo 'File mods/$(mod-dir)/intro.js not found!'; fi) +ifneq '$(err)' '' +$(error $(err)) +endif + +js-target = scripts/build/untrusted.js +js-target-min = scripts/build/untrusted.min.js + +js-modules = scripts/util.js \ + mods/$(mod-dir)/intro.js\ + scripts/_head.js \ + scripts/game.js \ + scripts/codeEditor.js \ + scripts/display.js \ + scripts/dynamicObject.js \ + scripts/inventory.js \ + scripts/map.js \ + scripts/objects.js \ + scripts/player.js \ + scripts/reference.js \ + scripts/sound.js \ + scripts/validate.js \ + scripts/ui.js \ + levels/levels.js \ + scripts/_launcher_release.js \ + scripts/_tail.js + +js-modules-debug = scripts/util.js \ + mods/$(mod-dir)/intro.js\ + scripts/_head.js \ + scripts/game.js \ + scripts/codeEditor.js \ + scripts/display.js \ + scripts/dynamicObject.js \ + scripts/inventory.js \ + scripts/map.js \ + scripts/objects.js \ + scripts/player.js \ + scripts/reference.js \ + scripts/sound.js \ + scripts/validate.js \ + scripts/ui.js \ + levels/levels.js \ + scripts/_launcher_debug.js \ + scripts/_tail.js + +yui-jar = tools/yuicompressor-2.4.8pre.jar + +# `make` or `make debug` merges scripts (using debug launcher) +debug: + @echo "Building level file…\t\t\t\c" + @./compile_levels.sh $(mod-dir) + @echo "[ Done ]" + @echo "Merging JS files…\t\t\t\c" + @cat $(js-modules-debug) > $(js-target) + @./parse_target.sh $(js-target) $(mod-dir) + @echo "[ Done ]" + +# `make release` merges and compresses scripts (using release launcher) +release: + @rm -f $(js-target-min) + @echo "Building level file…\t\t\t\c" + @./compile_levels.sh $(mod-dir) + @echo "[ Done ]" + @echo "Merging JS files…\t\t\t\c" + @cat $(js-modules) > $(js-target) + @./parse_target.sh $(js-target) $(mod-dir) + @echo "[ Done ]" + @echo "Compressing merged JS…\t\t\t\c" + @java -jar $(yui-jar) -o $(js-target-min) $(js-target) + @echo "[ Done ]" + +# `make clean` removes built scripts +clean: + @rm -f $(js-target) $(js-target-min) + +# to use `make deploy` to deploy Untrusted to your own server, create +# a deploy.sh script (ncftpput is helpful for uploading via FTP). +deploy: release + @echo "Deploying to server…\t\t\t\c" + @rm -rf _site + @mkdir _site + @cp -R levels scripts styles images sound index.html _site + @./deploy.sh /untrusted _site + @rm -rf _site + @echo "[ Done ]" + +# `make deploy-full` also deploys music and libs +deploy-full: release + @echo "Deploying to server…\t\t\t\c" + @rm -rf _site + @mkdir _site + @cp -R levels scripts styles images sound music lib index.html _site + @./deploy.sh /untrusted _site + @rm -rf _site + @echo "[ Done ]" + +# `make deploy-debug` deploys the debug version to /debug +deploy-debug: debug + @echo "Deploying to server…\t\t\t\c" + @rm -rf _site + @mkdir _site + @cp -R levels scripts styles images sound index.html _site + @./deploy.sh /untrusted/debug _site + @rm -rf _site + @echo "[ Done ]" + +# `make deploy-debug` deploys the debug version to /debug +deploy-debug-full: debug + @echo "Deploying to server…\t\t\t\c" + @rm -rf _site + @mkdir _site + @cp -R levels scripts styles images sound music lib index.html _site + @./deploy.sh /untrusted/debug _site + @rm -rf _site + @echo "[ Done ]" + +deploy-github: + @git checkout gh-pages && git merge master --no-commit && make release && git commit -am "build" && git push origin gh-pages; git checkout master && make + +# run-local will start a mini python webserver and host a local +# instance of the game will run on an available port +# the option -c-1 disables caching +runlocal: debug + @echo "Running local instance" + ./node_modules/http-server/bin/http-server -c-1 diff --git a/README.md b/README.md index e3024567b392f4e1a9a3ddda549aef95cf8ac5ab..ca8c8c1fd57e9c1d5ce83591cc5b0b0095242082 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,115 @@ ---- -title: Untrusted Test Only -emoji: 🌖 -colorFrom: purple -colorTo: yellow -sdk: static -pinned: false -license: cc-by-nc-sa-3.0 ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +**Untrusted —or— the Continuing Adventures of Dr. Eval** is an exciting Meta-JavaScript Adventure Game wherein you guide the dashing, steadfast Dr. Eval through a mysterious MACHINE CONTINUUM, wherein, using only his trusty computer and the TURING-COMPLETE power of JavaScript, he must literally ALTER HIS REALITY in order to find his freedom! You must literally edit and re-execute the very JavaScript running the game in your browser to save Dr. Eval from this dark and confusing reality! + +### Overview + +The game presents you with a roguelike-like playing environment and a console window with the JavaScript code generating each level. As loaded, each level is unbeatable, and most of the JavaScript is blocked from editing. The challenge is to open a path to the next level using only the limited tools left open to you. + +### Development + +Run +``` +make +``` +to merge the JavaScript files into `scripts/build/untrusted.js` (and enables debug features). + +``` +make release +``` +merges and minifies the JavaScript files into `scripts/build/untrusted.min.js` (and disables debug features). + +To run the game locally, you need to set up a local server to serve `index.html` (this step is necessary due to Access-Control-Allow-Origin restrictions). + +First install [http-server](https://github.com/nodeapps/http-server/#installing-globally) if you haven't already: + +``` +npm install http-server +``` + +Then run: + +``` +make runlocal +``` + +Build your own mod in the `mods` directory: + +``` +make mod=example_mod +``` + +### Contributing Levels + +To add a new level, create a jsx file in [/levels/bonus](https://github.com/AlexNisnevich/untrusted/tree/master/levels/bonus) and add the level filename to the `bonusLevels` array in [game.js](https://github.com/AlexNisnevich/untrusted/blob/master/scripts/game.js#L40). + +If you are adding any new commands that the player can use, make sure to add them to `reference.js`. + +#### The .jsx file format + +jsx files are like regular JavaScript files, but have some additional syntax: +- `#BEGIN_EDITABLE#` and `#END_EDITABLE#` surround editable lines +- `#{#` and `#}#` wrap editable sections (parts of lines) +- `#BEGIN_PROPERTIES#` and `#END_PROPERTIES#` surround the properties object at the start of the file. Available properties include: + - `commandsIntroduced`: array of new commands introduced in the level (see `reference.js`) + - `mapProperties`: optionally contains any of the following: + - `allowOverwrite`: if true, placed static objects can be overwritten by other objects + - `keyDelay`: specifies the lag, in milliseconds, between player keystrokes (default: 0) + - `refreshRate`: the refresh rate of the level, in milliseconds (required for dynamic objects with `interval` properties to work correctly) + - `showDrawingCanvas`: if true, the drawing canvas overlay is displayed + - `showDummyDom`: if true, a dummy DOM will be displayed instead of the regular map + - `music`: name of the background track for the level (see `sound.js`) + - `startingMessage`: message displayed at the bottom of the screen when the level starts (if any) + - `version`: increase the level version whenever you update a level + - `nextBonusLevel`: load another level automatically when this one is solved +- `#START_OF_START_LEVEL#` and `#END_OF_START_LEVEL#` should be the first and last line of the `startLevel` method, respectively + +#### Adding music + +To add a new background music track, add an MP3 file (that you have permission to use) to the [/music](https://github.com/AlexNisnevich/untrusted/tree/master/music) and add a new entry to the `tracks` array in [sound.js](https://github.com/AlexNisnevich/untrusted/blob/master/scripts/sound.js). + +### Acknowledgements + +Untrusted is a game by [Alex Nisnevich](http://alex.nisnevich.com/) and [Greg Shuflin](https://github.com/neunenak). + +We'd like to thank: + +- [Dmitry Mazin](https://github.com/dmazin) for design assistance and for the implementation of multiline editing +- [Jordan Arnesen](https://github.com/extrajordanary) for playtesting and design of lvl17 +- [Natasha Hull-Richter](http://nhull.com) for extensive playtesting and assistance in level design +- Alex Bolotov, Colin Curtin, Conrad Irwin, Devin C-R, Eugene Evans, Gilbert Hsyu, Jacob Nisnevich, James Silvey, Jason Jiang, Jimmy Hack, Philip Shao, Ryan Fitzgerald, Stephen Liu, Yayoi Ukai, and Yuval Gnessin for playtesting and feedback +- [Ondřej Žára](https://github.com/ondras) for his [rot.js](http://ondras.github.io/rot.js/) library +- [Marijn Haverbeke](https://github.com/marijnh) for his [CodeMirror](http://codemirror.net/) library +- [Brian Harvey](http://www.cs.berkeley.edu/~bh/) for allowing us to use his likeness in lvl19 + +#### Soundtrack + +You can [listen to the full soundtrack here](https://soundcloud.com/untrusted/sets/untrusted-soundtrack). + +The music that appears in Untrusted, in order, is: + +- "The Green" - [Jonathan Holliday](http://www.soundclick.com/bands/default.cfm?bandID=836578) (used with permission) +- "Dmitry's Thing #2" - [Dmitry Mazin](https://soundcloud.com/dmitry-mazin) (written for Untrusted) +- "Obscure Terrain" - [Revolution Void](http://revolutionvoid.com/) (CC-BY-NC-SA) +- "coming soon" - [Fex](http://artistserver.com/Fex) (public domain) +- "cloudy sin" - [iNTRICATE](https://soundcloud.com/stk13) (used with permission) +- "Dynamic Punctuality" - [Dmitry Mazin](https://soundcloud.com/dmitry-mazin) (written for Untrusted) +- "Y" - [Tortue Super Sonic](https://soundcloud.com/tss-tortue-super-sonic) (CC-BY-NC-SA) +- "Night Owl" - [Broke for Free](http://brokeforfree.com/) (CC-BY) +- "The Waves Call Her Name" - [Sycamore Drive](http://sycamoredrive.bandcamp.com/) (CC-BY-NC-SA) +- "Come and Find Me - B mix" - [Eric Skiff](http://ericskiff.com/) (CC-BY) +- "Conspiracy" - [Mike and Alan](https://www.facebook.com/MicAndAlan) (used with permission) +- "Messeah" - [RoccoW](https://soundcloud.com/roccow) (CC-BY) +- "Searching" - [Eric Skiff](http://ericskiff.com/) (CC-BY) +- "Da Funk Do You Know 'bout Chip?" - [That Andy Guy](https://soundcloud.com/that-andy-guy) (used with permission) +- "Soixante-8" - [Obsibilo](http://freemusicarchive.org/music/Obsibilo/) (CC-BY-NC-SA) +- "Tart (Pts 1 and 2)" - [BLEO feat KeFF](http://bleo.dummydrome.com/) (CC-BY-NC-SA) +- "Beach Wedding Dance" - [Rolemusic](https://soundcloud.com/rolemusic) (CC-BY-NC-SA) +- "Boss Loop 1" - [Essa](http://www.youtube.com/user/Essasmusic) (free to use) +- "Adversity" - [Seropard](https://soundcloud.com/seropard) (free to use) +- "Comme Des Orages" - [Obsibilo](http://freemusicarchive.org/music/Obsibilo/) (CC-BY-NC-SA) +- "Brazilicon Alley" - [Vernon Lenoir](http://vernonlenoir.wordpress.com/) (CC-BY-NC-SA), based on "Aquarela do Brazil" by Ary Barroso + +### License +This work is dual-licensed. + +- Untrusted and the Untrusted soundtrack are licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License (CC-BY-NC-SA 3.0). In other words, you are free to use and modify Untrusted for non-commercial purposes, provided that you credit us and your work is also licensed under CC-BY-NC-SA. +- Additionally, the Untrusted code *without the soundtrack* is licenced under a commercial license. This means that you are able to use Untrusted for commercial purposes under some conditions, provided that you do not use any of the music. Please [contact us](mailto:alex.nisnevich@gmail.com,greg.shuflin@gmail.com) for details. diff --git a/compile_levels.sh b/compile_levels.sh new file mode 100644 index 0000000000000000000000000000000000000000..fccff78c24752b4f9a0d9735f0d4105f0c8c15b4 --- /dev/null +++ b/compile_levels.sh @@ -0,0 +1,14 @@ +echo "Game.prototype._levels = {" > levels/levels.js + +mod=$1 + +for lvl in mods/$mod/*.jsx +do + lvlfn=`basename $lvl` + printf %s " 'levels/$lvlfn': '" >> levels/levels.js + echo "$lvl" | xargs sed "s#\\\#\\\\\\\#g" | sed "s#'#\\\'#g" | tr '\n' '`' | sed "s/\`/\\\n/g" | sed -e "a\\ + ', + " | tr '\n' ' ' >> levels/levels.js + echo "" >> levels/levels.js # dummy newline for style +done +echo "};" >> levels/levels.js diff --git a/deploy.sh.example b/deploy.sh.example new file mode 100644 index 0000000000000000000000000000000000000000..559a05d20ded746abeeb03c1ece58688e14c06a4 --- /dev/null +++ b/deploy.sh.example @@ -0,0 +1,3 @@ +cd $2 +ncftpput -R -v -u [username] ftp.[domain].com [untrusted_root_path]$1 . +cd .. diff --git a/favicon.ico b/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..dcd42105598e542fabb28fb0137e02a08580d6d6 Binary files /dev/null and b/favicon.ico differ diff --git a/images/mute-off.png b/images/mute-off.png new file mode 100644 index 0000000000000000000000000000000000000000..a23ba306bae935bc58171aa80e8a02c1b84ae858 Binary files /dev/null and b/images/mute-off.png differ diff --git a/images/mute-on.png b/images/mute-on.png new file mode 100644 index 0000000000000000000000000000000000000000..893aff40d5517beb70beb530253679fb40f9c044 Binary files /dev/null and b/images/mute-on.png differ diff --git a/images/static.gif b/images/static.gif new file mode 100644 index 0000000000000000000000000000000000000000..b3f5efb05b350d132007f6dc3961de81915a55a7 Binary files /dev/null and b/images/static.gif differ diff --git a/index.html b/index.html index 58275de3b1c343a98420342baa076b9baaafa157..6fa76698e05a0e7df51d83c4b936b7d286874795 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,124 @@ - - - - My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

+ + Untrusted - a user javascript adventure game + + + + + + + + + + + + + + + + + + + + + + Fork me on GitHub +
+
+ + + + +
+ +
+
+
+
+
+
+ + + + + +
+
+
$EDITOR
+ +
- +
x
+
+
+ +
+ Interested in using Untrusted commercially? + licensing@untrustedgame.com +
+ +
+ Send some beer money our way? +
+ + + + +
+
+
+ +
+
+ + + + + diff --git a/lib/codemirror-3.1/demo/resize.html b/lib/codemirror-3.1/demo/resize.html new file mode 100644 index 0000000000000000000000000000000000000000..ddd4e5669547beebe55112ae3f75102412b84472 --- /dev/null +++ b/lib/codemirror-3.1/demo/resize.html @@ -0,0 +1,46 @@ + + + + + CodeMirror: Autoresize Demo + + + + + + + + +

CodeMirror: Autoresize demo

+ +
+ +

By setting a few CSS properties, CodeMirror can be made to +automatically resize to fit its content.

+ + + + + diff --git a/lib/codemirror-3.1/demo/runmode.html b/lib/codemirror-3.1/demo/runmode.html new file mode 100644 index 0000000000000000000000000000000000000000..dba808ba7a66cefedac922d5804d56c89c40e4e2 --- /dev/null +++ b/lib/codemirror-3.1/demo/runmode.html @@ -0,0 +1,50 @@ + + + + + CodeMirror: Mode Runner Demo + + + + + + + +

CodeMirror: Mode Runner Demo

+ +
+ +

+
+    
+
+    

Running a CodeMirror mode outside of the editor. + The CodeMirror.runMode function, defined + in lib/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).
+
+ + + diff --git a/lib/codemirror-3.1/demo/search.html b/lib/codemirror-3.1/demo/search.html new file mode 100644 index 0000000000000000000000000000000000000000..d72107156cb7ac808dbdbac9bb068c0b160d5c68 --- /dev/null +++ b/lib/codemirror-3.1/demo/search.html @@ -0,0 +1,85 @@ + + + + + CodeMirror: Search/Replace Demo + + + + + + + + + + + + +

CodeMirror: Search/Replace Demo

+ +
+ + + +

Demonstration of primitive search/replace functionality. The + keybindings (which can be overridden by 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
+
+

Searching is enabled by + including addon/search/search.js + and addon/search/searchcursor.js. + For good-looking input dialogs, you also want to include + addon/dialog/dialog.js + and addon/dialog/dialog.css.

+ + diff --git a/lib/codemirror-3.1/demo/theme.html b/lib/codemirror-3.1/demo/theme.html new file mode 100644 index 0000000000000000000000000000000000000000..42a1b0cde7554f9ee77628f8678fc8850f710329 --- /dev/null +++ b/lib/codemirror-3.1/demo/theme.html @@ -0,0 +1,85 @@ + + + + + CodeMirror: Theme Demo + + + + + + + + + + + + + + + + + + + + + + + +

CodeMirror: Theme demo

+ +
+ +

Select a theme: +

+ + + + diff --git a/lib/codemirror-3.1/demo/variableheight.html b/lib/codemirror-3.1/demo/variableheight.html new file mode 100644 index 0000000000000000000000000000000000000000..b00f7e4542d4e30539795c2f631c6113e2f3b138 --- /dev/null +++ b/lib/codemirror-3.1/demo/variableheight.html @@ -0,0 +1,52 @@ + + + + + CodeMirror: Variable Height Demo + + + + + + + + + +

CodeMirror: Variable Height Demo

+ +
+ + + diff --git a/lib/codemirror-3.1/demo/vim.html b/lib/codemirror-3.1/demo/vim.html new file mode 100644 index 0000000000000000000000000000000000000000..c5835d40dafacc74be875c59b9d7852c9c650760 --- /dev/null +++ b/lib/codemirror-3.1/demo/vim.html @@ -0,0 +1,65 @@ + + + + + CodeMirror: Vim bindings demo + + + + + + + + + + + + +

CodeMirror: Vim bindings demo

+ +
+ +
+ +

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

+ + + + + diff --git a/lib/codemirror-3.1/demo/visibletabs.html b/lib/codemirror-3.1/demo/visibletabs.html new file mode 100644 index 0000000000000000000000000000000000000000..ddc12fb46aa824701fd1c834f33060f5e0057c9d --- /dev/null +++ b/lib/codemirror-3.1/demo/visibletabs.html @@ -0,0 +1,53 @@ + + + + + CodeMirror: Visible tabs demo + + + + + + + + +

CodeMirror: Visible tabs demo

+ +
+ +

Tabs inside the editor are spans with the +class cm-tab, and can be styled. + + + + + diff --git a/lib/codemirror-3.1/demo/widget.html b/lib/codemirror-3.1/demo/widget.html new file mode 100644 index 0000000000000000000000000000000000000000..a3b27a9e4774f5182bd47607fe1f4e589171f7f6 --- /dev/null +++ b/lib/codemirror-3.1/demo/widget.html @@ -0,0 +1,74 @@ + + + + + CodeMirror: Inline Widget Demo + + + + + + + + + +

CodeMirror: 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.

+ + diff --git a/lib/codemirror-3.1/demo/xmlcomplete.html b/lib/codemirror-3.1/demo/xmlcomplete.html new file mode 100644 index 0000000000000000000000000000000000000000..28a50638f7fa12a7db5c0772e6c05eee428b6f1e --- /dev/null +++ b/lib/codemirror-3.1/demo/xmlcomplete.html @@ -0,0 +1,81 @@ + + + + + CodeMirror: XML Autocomplete Demo + + + + + + + + + + + +

CodeMirror: XML Autocomplete demo

+ +
+ +

Type '<' or space inside tag or + press ctrl-space to activate autocompletion. See + the code (here + and here) to figure out how + it works.

+ + + + diff --git a/lib/codemirror-3.1/doc/baboon.png b/lib/codemirror-3.1/doc/baboon.png new file mode 100644 index 0000000000000000000000000000000000000000..55d97f70b817ff2b78ebb409bf34a5147fe40d07 Binary files /dev/null and b/lib/codemirror-3.1/doc/baboon.png differ diff --git a/lib/codemirror-3.1/doc/baboon_vector.svg b/lib/codemirror-3.1/doc/baboon_vector.svg new file mode 100644 index 0000000000000000000000000000000000000000..dc1667af91371787b979f9155061ff5d954f3ece --- /dev/null +++ b/lib/codemirror-3.1/doc/baboon_vector.svg @@ -0,0 +1,153 @@ + + + +image/svg+xml \ No newline at end of file diff --git a/lib/codemirror-3.1/doc/compress.html b/lib/codemirror-3.1/doc/compress.html new file mode 100644 index 0000000000000000000000000000000000000000..7f3bc7f7ab05c94c760a32b2aea98d008982ceac --- /dev/null +++ b/lib/codemirror-3.1/doc/compress.html @@ -0,0 +1,194 @@ + + + + + CodeMirror: Compression Helper + + + + + +

{ } CodeMirror

+ +
+ +
+/* Script compression
+   helper */
+
+
+ +

To optimize loading CodeMirror, especially when including a + bunch of different modes, it is recommended that you combine and + minify (and preferably also gzip) the scripts. This page makes + those first two steps very easy. Simply select the version and + scripts you need in the form below, and + click Compress to download the minified script + file.

+ +
+ +

Version:

+ +

+ +

+ with UglifyJS +

+ +

Custom code to add to the compressed file:

+
+ + + + + diff --git a/lib/codemirror-3.1/doc/docs.css b/lib/codemirror-3.1/doc/docs.css new file mode 100644 index 0000000000000000000000000000000000000000..170cd412449fc460aa4489aab3e0362238960b51 --- /dev/null +++ b/lib/codemirror-3.1/doc/docs.css @@ -0,0 +1,167 @@ +body { + font-family: Droid Sans, Arial, sans-serif; + line-height: 1.5; + max-width: 64.3em; + margin: 3em auto; + padding: 0 1em; +} + +h1 { + letter-spacing: -3px; + font-size: 3.23em; + font-weight: bold; + margin: 0; +} + +h2 { + font-size: 1.23em; + font-weight: bold; + margin: .5em 0; + letter-spacing: -1px; +} + +h3 { + font-size: 1.1em; + font-weight: bold; + margin: .4em 0; +} + +pre { + background-color: #eee; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: 1em; +} + +pre.code { + margin: 0 1em; +} + +.grey { + background-color: #eee; + border-radius: 6px; + margin-bottom: 1.65em; + margin-top: 0.825em; + padding: 0.825em 1.65em; + position: relative; +} + +img.logo { + position: absolute; + right: -1em; + bottom: 4px; + max-width: 23.6875em; /* Scale image down with text to prevent clipping */ +} + +.grey > pre { + background:none; + border-radius:0; + padding:0; + margin:0; + font-size:2.2em; + line-height:1.2em; +} + +a:link, a:visited, .quasilink { + color: #df0019; + cursor: pointer; + text-decoration: none; +} + +a:hover, .quasilink:hover { + color: #800004; +} + +h1 a:link, h1 a:visited, h1 a:hover { + color: black; +} + +ul { + margin: 0; + padding-left: 1.2em; +} + +a.download { + color: white; + background-color: #df0019; + width: 100%; + display: block; + text-align: center; + font-size: 1.23em; + font-weight: bold; + text-decoration: none; + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + border-radius: 6px; + padding: .5em 0; + margin-bottom: 1em; +} + +a.download:hover { + background-color: #bb0010; +} + +.rel { + margin-bottom: 0; +} + +.rel-note { + color: #777; + font-size: .9em; + margin-top: .1em; +} + +.logo-braces { + color: #df0019; + position: relative; + top: -4px; +} + +.blk { + float: left; +} + +.left { + margin-right: 20.68em; + max-width: 37em; + padding-right: 6.53em; + padding-bottom: 1em; +} + +.left1 { + width: 15.24em; + padding-right: 6.45em; +} + +.left2 { + max-width: 15.24em; +} + +.right { + width: 20.68em; + margin-left: -20.68em; +} + +.leftbig { + width: 42.44em; + padding-right: 6.53em; +} + +.rightsmall { + width: 15.24em; +} + +.clear:after { + visibility: hidden; + display: block; + font-size: 0; + content: " "; + clear: both; + height: 0; +} +.clear { display: inline-block; } +/* start commented backslash hack \*/ +* html .clear { height: 1%; } +.clear { display: block; } +/* close commented backslash hack */ diff --git a/lib/codemirror-3.1/doc/internals.html b/lib/codemirror-3.1/doc/internals.html new file mode 100644 index 0000000000000000000000000000000000000000..9139528f3de75ca48a8f5b04a71511894ff42d9b --- /dev/null +++ b/lib/codemirror-3.1/doc/internals.html @@ -0,0 +1,505 @@ + + + + + CodeMirror: Internals + + + + + + +

{ } CodeMirror

+ +
+ +
+/* (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.

+ +
+ +
 
+ + diff --git a/lib/codemirror-3.1/doc/manual.html b/lib/codemirror-3.1/doc/manual.html new file mode 100644 index 0000000000000000000000000000000000000000..0071d39a4f48f0f9143ecb95b4f5f1a59f408a74 --- /dev/null +++ b/lib/codemirror-3.1/doc/manual.html @@ -0,0 +1,1796 @@ + + + + + CodeMirror: User Manual + + + + + + + + + + + + + + +

{ } CodeMirror

+ +
+ +
+/* User manual and
+   reference guide */
+
+
+ +
+ +

Overview

+ +

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 add-ons included in the distribution, + and + the CodeMirror + UI project, 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. + (See the compression helper for an + easy way to combine scripts.) For example:

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

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.

+ +

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 or Doc)
+
The starting value of the editor. Can be a string, or + a document object.
+ +
mode (string or 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.
+ +
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.
+ +
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 keymap to use. The default + is "default", which is the only keymap defined + in codemirror.js itself. Extra keymaps are found in + the keymap directory. See + the section on keymaps for more + information.
+ +
extraKeys (object)
+
Can be used to specify extra keybindings for the editor, + alongside the ones defined + by keyMap. Should be + either null, or a valid keymap value.
+ +
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)
+
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)
+
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).
+ +
readOnly (boolean)
+
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.
+ +
undoDepth (integer)
+
The maximum number of undo levels that the editor stores. + Defaults to 40.
+ +
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.
+
+ +

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.
+ +
onDragEvent (function)
+
When given, this will be called when the editor is handling + a dragenter, dragover, + or drop event. It will be passed the editor instance + and the event object as arguments. The callback can choose to + handle the event itself, in which case it should + return true to indicate that CodeMirror should not + do anything further.
+ +
onKeyEvent (function)
+
This provides a rather low-level hook into CodeMirror's key + handling. If provided, this function will be called on + every keydown, keyup, + and keypress event that CodeMirror captures. It + will be passed two arguments, the editor instance and the key + event. This key event is pretty much the raw key event, except + that a stop() method is always added to it. You + could feed it to, for example, jQuery.Event to + further normalize it.
This function can inspect the key + event, and handle it if it wants to. It may return true to tell + CodeMirror to ignore the event. Be wary that, on some browsers, + stopping a keydown does not stop + the keypress from firing, whereas on others it + does. If you respond to an event, you should probably inspect + its type property and only do something when it + is keydown (or keypress for actions + that need character data).
+ +
cursorBlinkRate (number)
+
Half-period in milliseconds used for cursor blinking. The default blink + rate is 530ms.
+ +
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
+ +
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.
+ +
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.
+
+ +

Events

+ +

A CodeMirror instance emits a number of events, which allow + client code to react to various situations. These are registered + with the on method (and + removed with the off + method). These are the events that fire on the instance object. + The name of the event is followed by the arguments that will be + passed to the handler. The instance argument always + refers to the editor instance.

+ +
+
"change" (instance, changeObj)
+
Fires every time the content of the editor is changed. + The changeObj is a {from, to, text, + next} 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). If multiple changes happened + during a single operation, the object will have + a next property pointing to another change object + (which may point to another, etc).
+ +
"beforeChange" (instance, change)
+
This event is fired before a change is applied, and its + handler may choose to modify or cancel the change. + The change object + has from, to, and text + properties, as with + the "change" event, but + never a next property, since this is fired for each + individual change, and not batched per operation. It also + has update(from, to, text) + and cancel() methods, which may be used to modify + or cancel the 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)
+
Will be fired when the cursor or selection moves, or any + change is made to the editor content.
+ +
"beforeSelectionChange" (instance, selection)
+
This event is fired before the selection is moved. Its + handler may modify the resulting selection head and anchor. + The selection parameter is an object + with head and anchor properties + holding {line, ch} objects, which the handler can + read and update. 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, from, to)
+
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.
+ +
"gutterClick" (instance, line, gutter, clickEvent)
+
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.
+ +
"focus", "blur" (instance)
+
These fire whenever the editor is focused or unfocused.
+ +
"scroll" (instance)
+
Fires when the editor is scrolled.
+ +
"update" (instance)
+
Will be fired whenever CodeMirror updates its DOM display.
+
+ +

It is also possible to register events on + other objects. Use CodeMirror.on(handle, "eventName", + func) to register handlers on objects that don't have their + own on method. Document objects (instances + of CodeMirror.Doc) emit the + following events:

+ +
+
"change" (doc, changeObj)
+
Fired whenever a change occurs to the + document. changeObj has a similar type as the + object passed to the + editor's "change" + event, but it never has a next property, because + document change events are not batched (whereas editor change + events are).
+ +
"beforeChange" (doc, change)
+
See the description of the + same event on editor instances.
+ +
"cursorActivity" (doc)
+
Fired whenever the cursor or selection in this document + changes.
+ +
"beforeSelectionChange" (doc, selection)
+
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" ()
+
Fires when the line's text content is changed in any way + (but the line is not deleted outright).
+
+ +

Marked range handles, as returned + by markText + and setBookmark, emit the + following events:

+ +
+
"clear" ()
+
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.
+
"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, 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.
+
+ +

Keymaps

+ +

Keymaps are ways to associate keys with functionality. A keymap + is an object mapping strings that identify the keys to functions + that implement their functionality.

+ +

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- (in that order!) to specify a modifier. So + for example, Shift-Ctrl-Space would be a valid key + identifier.

+ +

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.

+ +

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

+ +

The values of properties in keymaps can be either functions of + a single argument (the CodeMirror instance), strings, or + false. Such strings refer to properties of the + CodeMirror.commands object, which defines a number of + common commands that are used by the default keybindings, and maps + them to functions. 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" (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.

+ +

Keymaps 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 keymap or an array of + keymaps.

+ +

When a keymap contains a nofallthrough property + set to true, keys matched against that map will be + ignored if they don't match any of the bindings in the map (no + further child maps will be tried, and the default effect of + inserting a character will not occur).

+ +

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.
+ +
CodeMirror-scroll
+
Whether the editor scrolls (overflow: auto + + fixed height). By default, it does. Setting + the CodeMirror class to have height: + auto and giving this class overflow-x: auto; + overflow-y: hidden; will cause the editor + to resize to fit its + content.
+ +
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 add-ons) 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.

+ +

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.

+ +

Content manipulation methods

+ +
+
doc.getValue() → 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(string)
+
Set the editor content.
+ +
doc.getRange(from, to) → 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(string, from, to)
+
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.
+ +
doc.getLine(n) → string
+
Get the content of line n.
+
doc.setLine(n, text)
+
Set the content of line n.
+
doc.removeLine(n)
+
Remove the given line from the document.
+ +
doc.lineCount() → number
+
Get the number of lines in the editor.
+
doc.firstLine() → number
+
doc.lastLine() → number
+
Get the first and last lines of the editor. This will + usually be zero and doc.lineCount() - 1 respectively, + but for linked sub-views, + or documents instantiated with a non-zero + first line, it might return other values.
+ +
doc.getLineHandle(num) → lineHandle
+
Fetches the line handle for the given line number.
+
doc.getLineNumber(handle) → 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) | doc.eachLine(start, end, f)
+
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.
+
doc.isClean() → boolean
+
Returns whether the document is currently clean (not + modified since initialization or the last call + to markClean).
+
+ +

Cursor and selection methods

+ +
+
doc.getSelection() → string
+
Get the currently selected code.
+
doc.replaceSelection(string)
+
Replace the selection with the given string.
+ +
doc.getCursor(start) → object
+
start is a an optional string indicating which + end of the selection to return. It may + be "start", "end", "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.somethingSelected() → boolean
+
Return true if any text is selected.
+
doc.setCursor(pos)
+
Set the cursor position. You can either pass a + single {line, ch} object, or the line and the + character as two separate parameters.
+
doc.setSelection(anchor, head)
+
Set the selection range. anchor + and head should be {line, ch} + objects. head defaults to anchor when + not given.
+
doc.extendSelection(pos, pos2)
+
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. pos2 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).
+
doc.setExtending(bool)
+
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.
+ +
cm.findPosH(start, amount, unit, visually) → object
+
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, amount, unit) → object
+
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.
+
+ +

Configuration methods

+ +
+
cm.setOption(option, value)
+
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) → value
+
Retrieves the current value of the given option for this + editor instance.
+ +
cm.addKeyMap(map)
+
Attach an additional keymap to the editor. This is mostly + useful for add-ons that need to register some key handlers + without trampling on + the extraKeys + option. Maps added in this way have a lower precedence + than extraKeys, a higher precedence than the + base keyMap, and + between them, the maps added earlier have a higher precedence + than those added later.
+
cm.removeKeyMap(map)
+
Disable a keymap added + with addKeyMap. Either + pass in the keymap object itself, or a string, which will be + compared against the name property of the active + keymaps.
+ +
cm.addOverlay(mode, options)
+
Enable a highlighting overlay. This is a stateless mini-mode + that can be used to add extra highlighting. For example, + the search add-on 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 option parameter is optional. If given it + should be an object. Currently, only the opaque + option is recognized. This 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.
+
cm.removeOverlay(mode)
+
Pass this the exact argument passed for + the mode parameter + to addOverlay to remove + an overlay again.
+ +
cm.on(type, func)
+
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, func)
+
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, mode, + firstLineNumber) constructor. The last two arguments are + optional and can be used to set a mode for the document and make + it start at a line number other than 0, respectively.

+ +
+
cm.getDoc() → doc
+
Retrieve the currently active document from an editor.
+
doc.getEditor() → editor
+
Retrieve the editor associated with a document. May + return null.
+ +
cm.swapDoc(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) → 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) → 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, 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 (mode spec)
+
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)
+
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)
+
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.historySize() → object
+
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-serializeable) representation of the undo history.
+
doc.setHistory(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, to, options) → object
+
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. A + the "clear" event + fired on the range handle can be used to be notified when this + happens.
+
replacedWith (dom node)
+
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).
+
readOnly
+
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).
+
startStyle
Can be used to specify + an extra CSS class to be applied to the leftmost span that + is part of the marker.
+
endStyle
Equivalent + to startStyle, but for the rightmost span.
+
shared
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 constuctor 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 getOptions(copyWidget), which returns an + object representing the options for the marker. + If copyWidget is given an true, it will clone the + value of + the replacedWith + option, if any.
+ +
doc.setBookmark(pos, options) → object
+
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
Can be used to display a DOM + node at the current location of the bookmark (analogous to + the replacedWith + option to markText).
+
insertLeft
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.
+
+ +
doc.findMarksAt(pos) → array
+
Returns an array of all the bookmarks and marked ranges + present at the given position.
+
doc.getAllMarks() → array
+
Returns an array containing all marked ranges in the document.
+
+ +

Widget, gutter, and decoration methods

+ +
+
cm.setGutterMarker(line, gutterID, value) → 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.
+ +
cm.clearGutter(gutterID)
+
Remove all gutter markers in + the gutter with the given ID.
+ +
cm.addLineClass(line, where, class) → 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), 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.
+ +
cm.removeLineClass(line, where, class) → 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.
+ +
cm.lineInfo(line) → 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, node, scrollIntoView)
+
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).
+ +
cm.addLineWidget(line, node, options) → object
+
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.
+
showIfHidden (boolean)
+
When true, will cause the widget to be rendered even if + the line it is associated with is hidden.
+
+ 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, height)
+
Programatically set the size of the editor (overriding the + applicable CSS + rules). width and height 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, y)
+
Scroll the editor to a given (pixel) position. Both + arguments may be left as null + or undefined to have no effect.
+
cm.getScrollInfo()
+
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(pos)
+
Scrolls the given element into view. pos may be + either a {line, ch} position, referring to a given + character, null, to refer to the cursor, or + a {left, top, right, bottom} object, in + editor-local coordinates.
+ +
cm.cursorCoords(where, mode) → object
+
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. 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, mode) → object
+
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) → pos
+
Given an {left, top} object (in page coordinates), + returns the {line, ch} position that corresponds to + it.
+
cm.defaultTextHeight() → number
+
Returns the line height of the default font for the editor.
+ +
cm.getViewport() → object
+
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.
+
+ +

Mode, state, and token-related methods

+ +

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

+ +
+
doc.getMode() → object
+
Gets the 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.getTokenAt(pos) → 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.
+
+ +
cm.getStateAfter(line) → state
+
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.
+
+ +

Miscellaneous methods

+ +
+
cm.operation(func) → result
+
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.indentLine(line, dir)
+
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.
+
+ +
doc.posFromIndex(index) → object
+
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) → number
+
The reverse of posFromIndex.
+ +
cm.focus()
+
Give the editor focus.
+ +
cm.getInputField() → textarea
+
Returns the hidden textarea used to read input.
+
cm.getWrapperElement() → node
+
Returns the DOM node that represents the editor, and + controls its size. Remove this from your tree to delete an + editor instance.
+
cm.getScrollerElement() → node
+
Returns the DOM node that is responsible for the scrolling + of the editor.
+
cm.getGutterElement() → node
+
Fetches the DOM node that contains the editor gutters.
+
+ +

Static properties

+ +

The CodeMirror object itself provides + several useful properties. Firstly, its version + property contains a string that indicates the version of the + library. For releases, this simply + contains "major.minor" (for + example "2.33". For beta versions, " B" + (space, capital B) is added at the end of the string, for + development snapshots, " +" (space, plus) is + added.

+ +

The CodeMirror.fromTextArea + 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. 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).
+ +
cm.getTextArea() → textarea
+
Returns the textarea that the instance was based on.
+
+ +

If you want to define extra methods in terms + of the CodeMirror API, it is possible to + use CodeMirror.defineExtension(name, value). This + will cause the given value (usually a method) to be added to all + CodeMirror instances created from then on.

+ +

Similarly, CodeMirror.defineOption(name, + default, updateFunc) 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.

+ +

If your extention 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.

+ +

Add-ons

+ +

The addon directory in the distribution contains a + number of reusable components that implement extra editor + functionality. In brief, they are:

+ +
+
dialog/dialog.js
+
Provides a very simple way to query users for text input. + Adds an openDialog method to CodeMirror instances, + which can be called with an HTML fragment that provides the + prompt (should include an input tag), and a + callback function that is called when text has been entered. + Depends on addon/dialog/dialog.css.
+
search/searchcursor.js
+
Adds the getSearchCursor(query, start, caseFold) → + cursor method to CodeMirror instances, which can be used + to implement search/replace functionality. query + can be a regular expression or a string (only strings will match + across lines—if they contain newlines). 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. caseFold is only + relevant when matching a string. It will cause the search to be + case-insensitive. A search cursor has the following methods: +
+
findNext(), 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(), to() → object
+
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)
+
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.
+
edit/matchbrackets.js
+
Defines an option matchBrackets which, when set + to true, 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.
+
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) + to customize it. Demo + here.
+
fold/foldcode.js
+
Helps with code folding. + See the demo for an example. + Call CodeMirror.newFoldFunction with a range-finder + helper function to create a function that will, when applied to + a CodeMirror instance and a line number, attempt to fold or + unfold the block starting at the given line. A range-finder is a + language-specific function that also takes an instance and a + line number, and returns an range to be folded, or null if + no block is started on that line. This file + provides CodeMirror.braceRangeFinder, which finds + blocks in brace languages (JavaScript, C, Java, + etc), CodeMirror.indentRangeFinder, for languages + where indentation determines block structure (Python, Haskell), + and CodeMirror.tagRangeFinder, for XML-style + languages.
+
fold/collapserange.js
+
Another approach to + folding. See demo. + Allows the user to select a range to fold by clicking in the + gutter.
+
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 avaible for + running stand-alone + (without including all of CodeMirror) and + for running under + node.js.
+
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]} + 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. 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 CodeMirror.showHint, which takes a + CodeMirror instance and a hinting function, and pops up a widget + that allows the user to select a completion. Hinting functions + are function that take an editor instance, and return + a {list, from, to} object, where list + is an array of strings (the completions), and from + and to give the start and end of the token that is + being completed. Depends + on addon/hint/show-hint.css. See the other files in + the addon/hint for + hint sources for various languages. Check + out the demo for an + example.
+
match-highlighter.js
+
Adds a highlightSelectionMatches option that + can be enabled to highlight all instances of a currently + selected word. + Demo here.
+
lint/lint.js
+
Defines an interface component for showing linting warnings, + with pluggable warning sources + (see json-lint.js + and javascript-lint.js + in the same directory). Defines a lintWith option + that can be set to a warning source (for + example CodeMirror.javascriptValidator). 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 active line the class CodeMirror-activeline, + and adds a background with the class CodeMirror-activeline-background. + is enabled. See the demo.
+
edit/closetag.js
+
Provides utility functions for adding automatic tag closing + to XML modes. See + the demo.
+
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.
+
edit/continuecomment.js
+
Adds a command + called newlineAndIndentContinueComment that you can + bind Enter to in order to have the editor prefix + new lines inside C-like block comments with an asterisk.
+
+ +

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.

+ +

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.

+ +

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() → character
+
Returns the next character in the stream without advancing + it. Will return an null at the end of the + line.
+
next() → character
+
Returns the next character in the stream and advances it. + Also returns null when no more characters are + available.
+ +
eat(match) → character
+
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) → 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(ch) → boolean
+
Skips to the next occurrence of the given character, if + found on the current line (doesn't advance the stream if the + character does not occur on the line). Returns true if the + character was found.
+
match(pattern, consume, caseFold) → boolean
+
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)
+
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.
+
+ +

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.

+ +

Finally, a mode may define + an electricChars property, which should hold a string + containing all the characters that should trigger the behaviour + described for + the electricChars + option.

+ +

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 methods, 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 autoformatter + and 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.

+ +

Sometimes, it is useful to add or override mode + object properties from external code. + The CodeMirror.extendMode 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.

+ +
+ +
 
+ + + + + diff --git a/lib/codemirror-3.1/doc/modes.html b/lib/codemirror-3.1/doc/modes.html new file mode 100644 index 0000000000000000000000000000000000000000..7d273cbb7547f25782b8b7bb9e420afa2bad79e1 --- /dev/null +++ b/lib/codemirror-3.1/doc/modes.html @@ -0,0 +1,89 @@ + + + + + CodeMirror: Mode list + + + + + +

{ } CodeMirror

+ +
+ +
+/* Full list of
+   modes */
+
+
+ +

Every mode in the distribution. The list on the front-page leaves +out some of the more obscure ones.

+ +
+ +
+ + + diff --git a/lib/codemirror-3.1/doc/oldrelease.html b/lib/codemirror-3.1/doc/oldrelease.html new file mode 100644 index 0000000000000000000000000000000000000000..01711d1b8a3865872f5dc0418bf30e4285384db0 --- /dev/null +++ b/lib/codemirror-3.1/doc/oldrelease.html @@ -0,0 +1,476 @@ + + + + + CodeMirror + + + + + + +

{ } CodeMirror

+ +
+ +
+/* Old release
+   history */
+
+
+ +

19-09-2012: Version 2.34:

+ + + +

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

+ + + +

23-08-2012: Version 2.33:

+ + + +

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:

+ + + +

23-05-2012: Version 2.25:

+ + + +

23-04-2012: Version 2.24:

+ + + +

26-03-2012: Version 2.23:

+ + + +

27-02-2012: Version 2.22:

+ + + +

27-01-2012: Version 2.21:

+ + + +

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:

+ + +

27-10-2011: Version 2.16:

+ + +

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:

+ + +

04-07-2011: Version 2.11:

+ + +

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:

+ + +

26-05-2011: Version 2.01:

+ + +

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

28-03-2011: Version 1.0:

+ + +

22-02-2011: Version 2.0 beta 2:

+

Somewhat more mature API, lots of bugs shaken out. + +

17-02-2011: Version 0.94:

+ + +

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:

+ + +

17-12-2010: Version 0.92:

+ + +

11-11-2010: Version 0.91:

+ + +

02-10-2010: Version 0.9:

+ + +

22-07-2010: Version 0.8:

+ + +

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

+ + diff --git a/lib/codemirror-3.1/doc/realworld.html b/lib/codemirror-3.1/doc/realworld.html new file mode 100644 index 0000000000000000000000000000000000000000..6388a4034e6693313996a4736cf3f81d414ef027 --- /dev/null +++ b/lib/codemirror-3.1/doc/realworld.html @@ -0,0 +1,95 @@ + + + + + CodeMirror: Real-world uses + + + + + +

{ } CodeMirror

+ +
+ +
+/* Real world uses,
+   full list */
+
+
+ +

Contact me if you'd like + your project to be added to this list.

+ + + + + diff --git a/lib/codemirror-3.1/doc/reporting.html b/lib/codemirror-3.1/doc/reporting.html new file mode 100644 index 0000000000000000000000000000000000000000..a616512530473e72c69ffdfd888c45b9d3cf3d6d --- /dev/null +++ b/lib/codemirror-3.1/doc/reporting.html @@ -0,0 +1,60 @@ + + + + + CodeMirror: Reporting Bugs + + + + + + +

{ } CodeMirror

+ +
+ +
+/* 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. + +
  3. 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.
  4. + +
  5. 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.
  6. + +
  7. 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 make + the problem occur. We can not fix something that we can not + observe.
  8. + +
  9. 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.
  10. +
+ +
+ + + diff --git a/lib/codemirror-3.1/doc/upgrade_v2.2.html b/lib/codemirror-3.1/doc/upgrade_v2.2.html new file mode 100644 index 0000000000000000000000000000000000000000..7e4d840043077d575ce642ecff50d80348ee84bd --- /dev/null +++ b/lib/codemirror-3.1/doc/upgrade_v2.2.html @@ -0,0 +1,98 @@ + + + + + CodeMirror: Upgrading to v2.2 + + + + + +

{ } CodeMirror

+ +
+ +
+/* 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.

+ +
+ + + diff --git a/lib/codemirror-3.1/doc/upgrade_v3.html b/lib/codemirror-3.1/doc/upgrade_v3.html new file mode 100644 index 0000000000000000000000000000000000000000..7e8a6b61ae378cbe4112860beebfb3186fe6091a --- /dev/null +++ b/lib/codemirror-3.1/doc/upgrade_v3.html @@ -0,0 +1,227 @@ + + + + + CodeMirror: Upgrading to v3 + + + + + + + + + + + + + +

{ } CodeMirror

+ +
+ +
+/* 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.
  • +
+ +
+ + + + diff --git a/lib/codemirror-3.1/index.html b/lib/codemirror-3.1/index.html new file mode 100644 index 0000000000000000000000000000000000000000..700a16a6b2730da0dc3a44f8a33a65681c665e0c --- /dev/null +++ b/lib/codemirror-3.1/index.html @@ -0,0 +1,462 @@ + + + + + CodeMirror + + + + + + +

{ } CodeMirror

+ +
+ +
+/* In-browser code editing
+   made bearable */
+
+
+ +
+ +

CodeMirror is a JavaScript component that + provides a code editor in the browser. When a mode is available for + the language you are coding in, it will color your code, and + optionally help with indentation.

+ +

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

+ +
+ +

Usage demos:

+ + + +

Real-world uses:

+ + + +
+ +

Getting the code

+ +

All of CodeMirror is released under a MIT-style license. To get it, you can download + the latest + release or the current development + snapshot as zip files. To create a custom minified script file, + you can use the compression API.

+ +

We use git for version control. + The main repository can be fetched in this way:

+ +
git clone http://marijnhaverbeke.nl/git/codemirror
+ +

CodeMirror can also be found on GitHub at marijnh/CodeMirror. + If you plan to hack on the code and contribute patches, the best way + to do it is to create a GitHub fork, and send pull requests.

+ +

Documentation

+ +

The manual is your first stop for + learning how to use this library. It starts with a quick explanation + of how to use the editor, and then describes the API in detail.

+ +

For those who want to learn more about the code, there is + a series of + posts on CodeMirror on my blog, and the + old overview of the editor + internals. + The source code + itself is, for the most part, also very readable.

+ +

Support and bug reports

+ +

Community discussion, questions, and informal bug reporting is + done on + the CodeMirror + Google group. There is a separate + group, CodeMirror-announce, + which is lower-volume, and is only used for major announcements—new + versions and such. These will be cross-posted to both groups, so you + don't need to subscribe to both.

+ +

Though bug reports through e-mail are responded to, the preferred + way to report bugs is to use + the GitHub + issue tracker. Before reporting a + bug, read these pointers. Also, + the issue tracker is for bugs, not requests for help.

+ +

When none of these seem fitting, you can + simply e-mail the maintainer + directly.

+ +

Supported browsers

+ +

The following desktop browsers are able to run CodeMirror:

+ +
    +
  • Firefox 3 or higher
  • +
  • Chrome, any version
  • +
  • Safari 5.2 or higher
  • +
  • Opera 9 or higher (with some key-handling problems on OS X)
  • +
  • Internet Explorer 8 or higher in standards mode
    + (Not quirks mode. But quasi-standards mode with a + transitional doctype is also flaky. <!doctype + html> is recommended.)
  • +
  • Internet Explorer 7 (standards mode) is usable, but buggy. It + has a z-index + bug that prevents CodeMirror from working properly.
  • +
+ +

I am not actively testing against every new browser release, and + vendors have a habit of introducing bugs all the time, so I am + relying on the community to tell me when something breaks. + See here for information on how to contact + me.

+ +

Mobile browsers mostly kind of work, but, because of limitations + and their fundamentally different UI assumptions, show a lot of + quirks that are hard to work around.

+ +

Commercial support

+ +

CodeMirror is developed and maintained by me, Marijn Haverbeke, + in my own time. If your company is getting value out of CodeMirror, + please consider purchasing a support contract.

+ +
    +
  • You'll be funding further work on CodeMirror.
  • +
  • You ensure that you get a quick response when you have a + problem, even when I am otherwise busy.
  • +
+ +

CodeMirror support contracts exist in two + forms—basic at €100 per month, + and premium at €500 per + month. Contact me for further + information.

+ +
+ +
+ + Download the latest release + +

Support CodeMirror

+ + + + + +

Reading material

+ + + +

Releases

+ +

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:

+ + + +

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.
  • +
+ +

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 2.36:

+ + + +

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

+ + + +

22-10-2012: Version 2.35:

+ +
    +
  • New (sub) mode: TypeScript.
  • +
  • Don't overwrite (insert key) when pasting.
  • +
  • Fix several bugs in markText/undo interaction.
  • +
  • Better indentation of JavaScript code without semicolons.
  • +
  • Add defineInitHook function.
  • +
  • Full list of patches.
  • +
+ +

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.
  • +
+ +

Older releases...

+ +
+ +
 
+ +
+ + +
+ + + diff --git a/lib/codemirror-3.1/keymap/emacs.js b/lib/codemirror-3.1/keymap/emacs.js new file mode 100644 index 0000000000000000000000000000000000000000..fab3ab9fe6a53965035045ffc197fe6d677cc458 --- /dev/null +++ b/lib/codemirror-3.1/keymap/emacs.js @@ -0,0 +1,30 @@ +// TODO number prefixes +(function() { + // Really primitive kill-ring implementation. + var killRing = []; + function addToRing(str) { + killRing.push(str); + if (killRing.length > 50) killRing.shift(); + } + function getFromRing() { return killRing[killRing.length - 1] || ""; } + function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); } + + CodeMirror.keyMap.emacs = { + "Ctrl-X": function(cm) {cm.setOption("keyMap", "emacs-Ctrl-X");}, + "Ctrl-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");}, + "Ctrl-Alt-W": function(cm) {addToRing(cm.getSelection()); cm.replaceSelection("");}, + "Alt-W": function(cm) {addToRing(cm.getSelection());}, + "Ctrl-Y": function(cm) {cm.replaceSelection(getFromRing());}, + "Alt-Y": function(cm) {cm.replaceSelection(popFromRing());}, + "Ctrl-/": "undo", "Shift-Ctrl--": "undo", "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd", + "Ctrl-S": "findNext", "Ctrl-R": "findPrev", "Ctrl-G": "clearSearch", "Shift-Alt-5": "replace", + "Ctrl-Z": "undo", "Cmd-Z": "undo", "Alt-/": "autocomplete", "Alt-V": "goPageUp", + "Ctrl-J": "newlineAndIndent", "Enter": false, "Tab": "indentAuto", + fallthrough: ["basic", "emacsy"] + }; + + CodeMirror.keyMap["emacs-Ctrl-X"] = { + "Ctrl-S": "save", "Ctrl-W": "save", "S": "saveAll", "F": "open", "U": "undo", "K": "close", + auto: "emacs", nofallthrough: true + }; +})(); diff --git a/lib/codemirror-3.1/keymap/vim.js b/lib/codemirror-3.1/keymap/vim.js new file mode 100644 index 0000000000000000000000000000000000000000..e0e18cc5b4dd6d3960a513de2fbf44206c27ce5a --- /dev/null +++ b/lib/codemirror-3.1/keymap/vim.js @@ -0,0 +1,2589 @@ +/** + * Supported keybindings: + * + * Motion: + * h, j, k, l + * gj, gk + * e, E, w, W, b, B, ge, gE + * f, F, t, T + * $, ^, 0 + * gg, G + * % + * ', ` + * + * Operator: + * d, y, c + * dd, yy, cc + * g~, g~g~ + * >, <, >>, << + * + * Operator-Motion: + * x, X, D, Y, C, ~ + * + * Action: + * a, i, s, A, I, S, o, O + * zz, z., z, zt, zb, z- + * J + * u, Ctrl-r + * m + * r + * + * Modes: + * ESC - leave insert mode, visual mode, and clear input state. + * Ctrl-[, Ctrl-c - same as ESC. + * + * Registers: unamed, -, 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. + * + * 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 instanstiation + * 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. + */ + +(function() { + 'use strict'; + + var defaultKeymap = [ + // Key to key mapping. This goes first to make it possible to override + // existing mappings. + { keys: ['Left'], type: 'keyToKey', toKeys: ['h'] }, + { keys: ['Right'], type: 'keyToKey', toKeys: ['l'] }, + { keys: ['Up'], type: 'keyToKey', toKeys: ['k'] }, + { keys: ['Down'], type: 'keyToKey', toKeys: ['j'] }, + { keys: ['Space'], type: 'keyToKey', toKeys: ['l'] }, + { keys: ['Backspace'], type: 'keyToKey', toKeys: ['h'] }, + { keys: ['Ctrl-Space'], type: 'keyToKey', toKeys: ['W'] }, + { keys: ['Ctrl-Backspace'], type: 'keyToKey', toKeys: ['B'] }, + { keys: ['Shift-Space'], type: 'keyToKey', toKeys: ['w'] }, + { keys: ['Shift-Backspace'], type: 'keyToKey', toKeys: ['b'] }, + { keys: ['Ctrl-n'], type: 'keyToKey', toKeys: ['j'] }, + { keys: ['Ctrl-p'], type: 'keyToKey', toKeys: ['k'] }, + { keys: ['Ctrl-['], type: 'keyToKey', toKeys: ['Esc'] }, + { keys: ['Ctrl-c'], type: 'keyToKey', toKeys: ['Esc'] }, + { keys: ['s'], type: 'keyToKey', toKeys: ['c', 'l'] }, + { keys: ['S'], type: 'keyToKey', toKeys: ['c', 'c'] }, + { keys: ['Home'], type: 'keyToKey', toKeys: ['0'] }, + { keys: ['End'], type: 'keyToKey', toKeys: ['$'] }, + { keys: ['PageUp'], type: 'keyToKey', toKeys: ['Ctrl-b'] }, + { keys: ['PageDown'], type: 'keyToKey', toKeys: ['Ctrl-f'] }, + // Motions + { 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: ['g','j'], type: 'motion', + motion: 'moveByDisplayLines', + motionArgs: { forward: true, linewise: true }}, + { keys: ['g','k'], type: 'motion', + motion: 'moveByDisplayLines', + motionArgs: { forward: false, linewise: true }}, + { 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: ['g', 'e'], type: 'motion', + motion: 'moveByWords', + motionArgs: { forward: false, wordEnd: true, inclusive: true }}, + { keys: ['g', 'E'], type: 'motion', + motion: 'moveByWords', + motionArgs: { forward: false, wordEnd: true, bigWord: true, + inclusive: true }}, + { keys: ['{'], type: 'motion', motion: 'moveByParagraph', + motionArgs: { forward: false }}, + { keys: ['}'], type: 'motion', motion: 'moveByParagraph', + motionArgs: { forward: true }}, + { keys: ['Ctrl-f'], type: 'motion', + motion: 'moveByPage', motionArgs: { forward: true }}, + { keys: ['Ctrl-b'], type: 'motion', + motion: 'moveByPage', motionArgs: { forward: false }}, + { keys: ['g', 'g'], type: 'motion', + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: false, explicitRepeat: true, linewise: true }}, + { keys: ['G'], type: 'motion', + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: true, explicitRepeat: true, linewise: true }}, + { keys: ['0'], type: 'motion', motion: 'moveToStartOfLine' }, + { keys: ['^'], type: 'motion', + motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: ['$'], type: 'motion', + motion: 'moveToEol', + motionArgs: { inclusive: true }}, + { keys: ['%'], type: 'motion', + motion: 'moveToMatchedSymbol', + motionArgs: { inclusive: true }}, + { keys: ['f', 'character'], type: 'motion', + motion: 'moveToCharacter', + motionArgs: { forward: true , inclusive: true }}, + { keys: ['F', 'character'], type: 'motion', + motion: 'moveToCharacter', + motionArgs: { forward: false }}, + { keys: ['t', 'character'], type: 'motion', + motion: 'moveTillCharacter', + motionArgs: { forward: true, inclusive: true }}, + { keys: ['T', 'character'], type: 'motion', + motion: 'moveTillCharacter', + motionArgs: { forward: false }}, + { keys: ['\'', 'character'], type: 'motion', motion: 'goToMark' }, + { keys: ['`', 'character'], type: 'motion', motion: 'goToMark' }, + { keys: ['|'], type: 'motion', + motion: 'moveToColumn', + motionArgs: { }}, + // Operators + { keys: ['d'], type: 'operator', operator: 'delete' }, + { keys: ['y'], type: 'operator', operator: 'yank' }, + { keys: ['c'], type: 'operator', operator: 'change', + operatorArgs: { enterInsertMode: true } }, + { keys: ['>'], type: 'operator', operator: 'indent', + operatorArgs: { indentRight: true }}, + { keys: ['<'], type: 'operator', operator: 'indent', + operatorArgs: { indentRight: false }}, + { keys: ['g', '~'], type: 'operator', operator: 'swapcase' }, + { keys: ['n'], type: 'motion', motion: 'findNext' }, + { keys: ['N'], type: 'motion', motion: 'findPrev' }, + // 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 }, + operatorMotionArgs: { visualLine: true }}, + { keys: ['Y'], type: 'operatorMotion', operator: 'yank', + motion: 'moveToEol', motionArgs: { inclusive: true }, + operatorMotionArgs: { visualLine: true }}, + { keys: ['C'], type: 'operatorMotion', + operator: 'change', operatorArgs: { enterInsertMode: true }, + motion: 'moveToEol', motionArgs: { inclusive: true }, + operatorMotionArgs: { visualLine: true }}, + { keys: ['~'], type: 'operatorMotion', operator: 'swapcase', + motion: 'moveByCharacters', motionArgs: { forward: true }}, + // Actions + { keys: ['a'], type: 'action', action: 'enterInsertMode', + actionArgs: { insertAt: 'charAfter' }}, + { keys: ['A'], type: 'action', action: 'enterInsertMode', + actionArgs: { insertAt: 'eol' }}, + { keys: ['i'], type: 'action', action: 'enterInsertMode' }, + { keys: ['I'], type: 'action', action: 'enterInsertMode', + motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: ['o'], type: 'action', action: 'newLineAndEnterInsertMode', + actionArgs: { after: true }}, + { keys: ['O'], type: 'action', action: 'newLineAndEnterInsertMode', + actionArgs: { after: false }}, + { keys: ['v'], type: 'action', action: 'toggleVisualMode' }, + { keys: ['V'], type: 'action', action: 'toggleVisualMode', + actionArgs: { linewise: true }}, + { keys: ['J'], type: 'action', action: 'joinLines' }, + { keys: ['p'], type: 'action', action: 'paste', + actionArgs: { after: true }}, + { keys: ['P'], type: 'action', action: 'paste', + actionArgs: { after: false }}, + { keys: ['r', 'character'], type: 'action', action: 'replace' }, + { keys: ['u'], type: 'action', action: 'undo' }, + { keys: ['Ctrl-r'], type: 'action', action: 'redo' }, + { keys: ['m', 'character'], type: 'action', action: 'setMark' }, + { keys: ['\"', 'character'], type: 'action', action: 'setRegister' }, + { keys: ['z', 'z'], type: 'action', action: 'scrollToCursor', + actionArgs: { position: 'center' }}, + { keys: ['z', '.'], type: 'action', action: 'scrollToCursor', + actionArgs: { position: 'center' }, + motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: ['z', 't'], type: 'action', action: 'scrollToCursor', + actionArgs: { position: 'top' }}, + { keys: ['z', 'Enter'], type: 'action', action: 'scrollToCursor', + actionArgs: { position: 'top' }, + motion: 'moveToFirstNonWhiteSpaceCharacter' }, + { keys: ['z', '-'], type: 'action', action: 'scrollToCursor', + actionArgs: { position: 'bottom' }}, + { keys: ['z', 'b'], type: 'action', action: 'scrollToCursor', + actionArgs: { position: 'bottom' }, + motion: 'moveToFirstNonWhiteSpaceCharacter' }, + // Text object motions + { keys: ['a', 'character'], type: 'motion', + motion: 'textObjectManipulation' }, + { keys: ['i', 'character'], type: 'motion', + motion: 'textObjectManipulation', + motionArgs: { textObjectInner: true }}, + // Search + { keys: ['/'], type: 'search', + searchArgs: { forward: true, querySrc: 'prompt' }}, + { keys: ['?'], type: 'search', + searchArgs: { forward: false, querySrc: 'prompt' }}, + { keys: ['*'], type: 'search', + searchArgs: { forward: true, querySrc: 'wordUnderCursor' }}, + { keys: ['#'], type: 'search', + searchArgs: { forward: false, querySrc: 'wordUnderCursor' }}, + // Ex command + { keys: [':'], type: 'ex' } + ]; + + var Vim = function() { + var alphabetRegex = /[A-Za-z]/; + var numberRegex = /[\d]/; + var whiteSpaceRegex = /\s/; + var wordRegexp = [(/\w/), (/[^\w\s]/)], bigWordRegexp = [(/\S/)]; + 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 SPECIAL_SYMBOLS = '~`!@#$%^&*()_-+=[{}]\\|/?.,<>:;\"\''; + var specialSymbols = SPECIAL_SYMBOLS.split(''); + var specialKeys = ['Left', 'Right', 'Up', 'Down', 'Space', 'Backspace', + 'Esc', 'Home', 'End', 'PageUp', 'PageDown', 'Enter']; + var validMarks = upperCaseAlphabet.concat(lowerCaseAlphabet).concat( + numbers).concat(['<', '>']); + var validRegisters = upperCaseAlphabet.concat(lowerCaseAlphabet).concat( + numbers).concat('-\"'.split('')); + + function isAlphabet(k) { + return alphabetRegex.test(k); + } + 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 isAlphanumeric(k) { + return (/^[\w]$/).test(k); + } + function isWhiteSpace(k) { + return whiteSpaceRegex.test(k); + } + function isWhiteSpaceString(k) { + return (/^\s*$/).test(k); + } + function inRangeInclusive(x, start, end) { + return x >= start && x <= end; + } + function inArray(val, arr) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] == val) { + return true; + } + } + return false; + } + + // Global Vim state. Call getVimGlobalState to get and initialize. + var vimGlobalState; + function getVimGlobalState() { + if (!vimGlobalState) { + vimGlobalState = { + // The current search query. + searchQuery: null, + // Whether we are searching backwards. + searchIsReversed: false, + registerController: new RegisterController({}) + }; + } + return vimGlobalState; + } + function getVimState(cm) { + if (!cm.vimState) { + // Store instance state in the CodeMirror object. + cm.vimState = { + inputState: new InputState(), + // 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: {}, + visualMode: false, + // If we are in visual line mode. No effect if visualMode is false. + visualLine: false + }; + } + return cm.vimState; + } + + 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 getVimGlobalState().registerController; + }, + // Testing hook. + clearVimGlobalState_: function() { + vimGlobalState = null; + }, + map: function(lhs, rhs) { + // Add user defined key bindings. + exCommandDispatcher.map(lhs, rhs); + }, + defineEx: function(name, prefix, func){ + if (name.indexOf(prefix) === 0) { + exCommands[name]=func; + exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'}; + }else throw new Error("(Vim.defineEx) \""+prefix+"\" is not a prefix of \""+name+"\", command not registered"); + }, + // Initializes vim state variable on the CodeMirror object. Should only be + // called lazily by handleKey or for testing. + maybeInitState: function(cm) { + getVimState(cm); + }, + // This is the outermost function called by CodeMirror, after keys have + // been mapped to their Vim equivalents. + handleKey: function(cm, key) { + var command; + var vim = getVimState(cm); + if (key == 'Esc') { + // Clear input state and get back to normal mode. + vim.inputState.reset(); + if (vim.visualMode) { + exitVisualMode(cm, vim); + } + return; + } + if (vim.visualMode && + cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) { + // The selection was cleared. Exit visual mode. + exitVisualMode(cm, vim); + } + if (!vim.visualMode && + !cursorEqual(cm.getCursor('head'), cm.getCursor('anchor'))) { + vim.visualMode = true; + vim.visualLine = false; + } + if (key != '0' || (key == '0' && vim.inputState.getRepeat() === 0)) { + // Have to special case 0 since it's both a motion and a number. + command = commandDispatcher.matchCommand(key, defaultKeymap, vim); + } + if (!command) { + if (isNumber(key)) { + // Increment count unless count is 0 and key is 0. + vim.inputState.pushRepeatDigit(key); + } + return; + } + if (command.type == 'keyToKey') { + // TODO: prevent infinite recursion. + for (var i = 0; i < command.toKeys.length; i++) { + this.handleKey(cm, command.toKeys[i]); + } + } else { + commandDispatcher.processCommand(cm, vim, command); + } + } + }; + + // Represents the current input state. + function InputState() { + this.reset(); + } + InputState.prototype.reset = function() { + 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 unamed 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; + }; + + /* + * 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) { + this.clear(); + if (text) { + this.set(text, linewise); + } + } + Register.prototype = { + set: function(text, linewise) { + this.text = text; + this.linewise = !!linewise; + }, + append: function(text, linewise) { + // if this register has ever been set to linewise, use linewise. + if (linewise || this.linewise) { + this.text += '\n' + text; + this.linewise = true; + } else { + this.text += text; + } + }, + clear: function() { + this.text = ''; + this.linewise = false; + }, + toString: function() { return this.text; } + }; + + /* + * 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.unamedRegister = registers['\"'] = new Register(); + } + RegisterController.prototype = { + pushText: function(registerName, operator, text, linewise) { + // 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); + 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.unamedRegister.set(text, linewise); + return; + } + + // If we've gotten to this point, we've actually specified a register + var append = isUpperCase(registerName); + if (append) { + register.append(text, linewise); + // The unamed register always has the same value as the last used + // register. + this.unamedRegister.append(text, linewise); + } else { + register.set(text, linewise); + this.unamedRegister.set(text, linewise); + } + }, + // Gets the register named @name. If one of @name doesn't already exist, + // create it. If @name is invalid, return the unamedRegister. + getRegister: function(name) { + if (!this.isValidRegister(name)) { + return this.unamedRegister; + } + 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)); + } + } + }; + + var commandDispatcher = { + matchCommand: function(key, keyMap, vim) { + var inputState = vim.inputState; + var keys = inputState.keyBuffer.concat(key); + for (var i = 0; i < keyMap.length; i++) { + var command = keyMap[i]; + if (matchKeysPartial(keys, command.keys)) { + if (keys.length < command.keys.length) { + // Matches part of a multi-key command. Buffer and wait for next + // stroke. + inputState.keyBuffer.push(key); + return null; + } else { + if (inputState.operator && command.type == 'action') { + // Ignore matched action commands after an operator. Operators + // only operate on motions. This check is really for text + // objects since aW, a[ etcs conflicts with a. + continue; + } + // Matches whole comand. Return the command. + if (command.keys[keys.length - 1] == 'character') { + inputState.selectedCharacter = keys[keys.length - 1]; + } + inputState.keyBuffer = []; + return command; + } + } + } + // Clear the buffer since there are no partial matches. + inputState.keyBuffer = []; + return null; + }, + processCommand: function(cm, vim, command) { + 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. + inputState.reset(); + } + } + 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; + inputState.reset(); + vim.lastMotion = null, + actions[command.action](cm, actionArgs, vim); + }, + processSearch: function(cm, vim, command) { + if (!cm.getSearchCursor) { + // Search depends on SearchCursor. + return; + } + var forward = command.searchArgs.forward; + getSearchState(cm).setReversed(!forward); + var promptPrefix = (forward) ? '/' : '?'; + function handleQuery(query, ignoreCase, smartCase) { + updateSearchQuery(cm, query, ignoreCase, smartCase); + commandDispatcher.processMotion(cm, vim, { + type: 'motion', + motion: 'findNext' + }); + } + function onPromptClose(query) { + handleQuery(query, true /** ignoreCase */, true /** smartCase */); + } + switch (command.searchArgs.querySrc) { + case 'prompt': + showPrompt(cm, onPromptClose, promptPrefix, searchPromptDesc); + 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 + 1); + if (isKeyword) { + query = '\\b' + query + '\\b'; + } else { + query = escapeRegex(query); + } + cm.setCursor(word.start); + handleQuery(query, true /** ignoreCase */, false /** smartCase */); + break; + } + }, + processEx: function(cm, vim, command) { + function onPromptClose(input) { + exCommandDispatcher.processCommand(cm, input); + } + if (command.type == 'keyToEx') { + // Handle user defined Ex to Ex mappings + exCommandDispatcher.processCommand(cm, command.exArgs.input); + } else { + if (vim.visualMode) { + showPrompt(cm, onPromptClose, ':', undefined, '\'<,\'>'); + } else { + showPrompt(cm, onPromptClose, ':'); + } + } + }, + evalInput: function(cm, vim) { + // If the motion comand 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 selectionEnd = cm.getCursor('head'); + var selectionStart = cm.getCursor('anchor'); + // The difference between cur and selection cursors are that cur is + // being operated on and ignores that there is a selection. + var curStart = copyCursor(selectionEnd); + var curOriginal = copyCursor(curStart); + var curEnd; + var repeat; + if (motionArgs.repeat !== undefined) { + // If motionArgs specifies a repeat, that takes precedence over the + // input state's repeat. Used by Ex mode and can be user defined. + repeat = inputState.motionArgs.repeat; + } 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; + inputState.reset(); + if (motion) { + var motionResult = motions[motion](cm, motionArgs, vim); + vim.lastMotion = motions[motion]; + if (!motionResult) { + return; + } + if (motionResult instanceof Array) { + curStart = motionResult[0]; + curEnd = motionResult[1]; + } else { + curEnd = motionResult; + } + // TODO: Handle null returns from motion commands better. + if (!curEnd) { + curEnd = { ch: curStart.ch, line: curStart.line }; + } + if (vim.visualMode) { + // Check if the selection crossed over itself. Will need to shift + // the start point if that happened. + if (cursorIsBefore(selectionStart, selectionEnd) && + (cursorEqual(selectionStart, curEnd) || + cursorIsBefore(curEnd, selectionStart))) { + // The end of the selection has moved from after the start to + // before the start. We will shift the start right by 1. + selectionStart.ch += 1; + } else if (cursorIsBefore(selectionEnd, selectionStart) && + (cursorEqual(selectionStart, curEnd) || + cursorIsBefore(selectionStart, curEnd))) { + // The opposite happened. We will shift the start left by 1. + selectionStart.ch -= 1; + } + selectionEnd = curEnd; + if (vim.visualLine) { + if (cursorIsBefore(selectionStart, selectionEnd)) { + selectionStart.ch = 0; + selectionEnd.ch = lineLength(cm, selectionEnd.line); + } else { + selectionEnd.ch = 0; + selectionStart.ch = lineLength(cm, selectionStart.line); + } + } + cm.setSelection(selectionStart, selectionEnd); + updateMark(cm, vim, '<', + cursorIsBefore(selectionStart, selectionEnd) ? selectionStart + : selectionEnd); + updateMark(cm, vim, '>', + cursorIsBefore(selectionStart, selectionEnd) ? selectionEnd + : selectionStart); + } else if (!operator) { + curEnd = clipCursorToContent(cm, curEnd); + cm.setCursor(curEnd.line, curEnd.ch); + } + } + + if (operator) { + var inverted = false; + vim.lastMotion = null; + operatorArgs.repeat = repeat; // Indent in visual mode needs this. + if (vim.visualMode) { + curStart = selectionStart; + curEnd = selectionEnd; + motionArgs.inclusive = true; + } + // Swap start and end if motion was backward. + if (cursorIsBefore(curEnd, curStart)) { + var tmp = curStart; + curStart = curEnd; + curEnd = tmp; + inverted = true; + } + if (motionArgs.inclusive && !(vim.visualMode && inverted)) { + // Move the selection end one to the right to include the last + // character. + curEnd.ch++; + } + var linewise = motionArgs.linewise || + (vim.visualMode && vim.visualLine); + if (linewise) { + // Expand selection to entire line. + expandSelectionToLine(cm, curStart, curEnd); + } else if (motionArgs.forward) { + // Clip to trailing newlines only if we the motion goes forward. + clipToLine(cm, curStart, curEnd); + } + operatorArgs.registerName = registerName; + // Keep track of linewise as it affects how paste and change behave. + operatorArgs.linewise = linewise; + operators[operator](cm, operatorArgs, vim, curStart, + curEnd, curOriginal); + if (vim.visualMode) { + exitVisualMode(cm, vim); + } + if (operatorArgs.enterInsertMode) { + actions.enterInsertMode(cm); + } + } + } + }; + + /** + * 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 = { + expandToLine: function(cm, motionArgs) { + // Expands forward to end of line, and then to next line if repeat is + // >1. Does not handle backward motion! + var cur = cm.getCursor(); + return { line: cur.line + motionArgs.repeat - 1, ch: Infinity }; + }, + findNext: function(cm, motionArgs, vim) { + return findNext(cm, false /** prev */, motionArgs.repeat); + }, + findPrev: function(cm, motionArgs, vim) { + return findNext(cm, true /** prev */, motionArgs.repeat); + }, + goToMark: function(cm, motionArgs, vim) { + var mark = vim.marks[motionArgs.selectedCharacter]; + if (mark) { + return mark.find(); + } + return null; + }, + moveByCharacters: function(cm, motionArgs) { + var cur = cm.getCursor(); + var repeat = motionArgs.repeat; + var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat; + return { line: cur.line, ch: ch }; + }, + moveByLines: function(cm, motionArgs, vim) { + var cur = cm.getCursor(); + 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.moveToColumn: + case this.moveToEol: + endCh = vim.lastHPos; + break; + default: + vim.lastHPos = endCh; + } + var repeat = motionArgs.repeat; + var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat; + if (line < cm.firstLine() || line > cm.lastLine() ) { + return null; + } + vim.lastHSPos = cm.charCoords({line:line, ch:endCh},"div").left; + return { line: line, ch: endCh }; + }, + moveByDisplayLines: function(cm, motionArgs, vim) { + var cur = cm.getCursor(); + switch (vim.lastMotion) { + case this.moveByDisplayLines: + 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)return null; + vim.lastHPos = res.ch; + return res; + }, + moveByPage: function(cm, 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 = cm.getCursor(); + var repeat = motionArgs.repeat; + cm.moveV((motionArgs.forward ? repeat : -repeat), 'page'); + var curEnd = cm.getCursor(); + cm.setCursor(curStart); + return curEnd; + }, + moveByParagraph: function(cm, motionArgs) { + var line = cm.getCursor().line; + var repeat = motionArgs.repeat; + var inc = motionArgs.forward ? 1 : -1; + for (var i = 0; i < repeat; i++) { + if ((!motionArgs.forward && line === cm.firstLine() ) || + (motionArgs.forward && line == cm.lastLine())) { + break; + } + line += inc; + while (line !== cm.firstLine() && line != cm.lastLine() && cm.getLine(line)) { + line += inc; + } + } + return { line: line, ch: 0 }; + }, + moveByWords: function(cm, motionArgs) { + return moveToWord(cm, motionArgs.repeat, !!motionArgs.forward, + !!motionArgs.wordEnd, !!motionArgs.bigWord); + }, + moveTillCharacter: function(cm, motionArgs) { + var repeat = motionArgs.repeat; + var curEnd = moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter); + var increment = motionArgs.forward ? -1 : 1; + curEnd.ch += increment; + return curEnd; + }, + moveToCharacter: function(cm, motionArgs) { + var repeat = motionArgs.repeat; + return moveToCharacter(cm, repeat, motionArgs.forward, + motionArgs.selectedCharacter); + }, + moveToColumn: function(cm, 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(cm.getCursor(),"div").left; + return moveToColumn(cm, repeat); + }, + moveToEol: function(cm, motionArgs, vim) { + var cur = cm.getCursor(); + vim.lastHPos = Infinity; + var retval={ line: cur.line + motionArgs.repeat - 1, ch: Infinity } + var end=cm.clipPos(retval); + end.ch--; + vim.lastHSPos = cm.charCoords(end,"div").left; + return retval; + }, + moveToFirstNonWhiteSpaceCharacter: function(cm) { + // Go to the start of the line where the text begins, or the end for + // whitespace-only lines + var cursor = cm.getCursor(); + var line = cm.getLine(cursor.line); + return { line: cursor.line, + ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)) }; + }, + moveToMatchedSymbol: function(cm, motionArgs) { + var cursor = cm.getCursor(); + var symbol = cm.getLine(cursor.line).charAt(cursor.ch); + if (isMatchableSymbol(symbol)) { + return findMatchedSymbol(cm, cm.getCursor(), motionArgs.symbol); + } else { + return cursor; + } + }, + moveToStartOfLine: function(cm) { + var cursor = cm.getCursor(); + return { line: cursor.line, ch: 0 }; + }, + moveToLineOrEdgeOfDocument: function(cm, motionArgs) { + var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine(); + if (motionArgs.repeatIsExplicit) { + lineNum = motionArgs.repeat - cm.getOption('firstLineNumber'); + } + return { line: lineNum, + ch: findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)) }; + }, + textObjectManipulation: function(cm, motionArgs) { + var character = motionArgs.selectedCharacter; + // 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; + if (!textObjects[character]) { + // No text object defined for this, don't move. + return null; + } + var tmp = textObjects[character](cm, inclusive); + var start = tmp.start; + var end = tmp.end; + return [start, end]; + } + }; + + var operators = { + change: function(cm, operatorArgs, vim, curStart, curEnd) { + getVimGlobalState().registerController.pushText( + operatorArgs.registerName, 'change', cm.getRange(curStart, curEnd), + operatorArgs.linewise); + if (operatorArgs.linewise) { + // Delete starting at the first nonwhitespace character of the first + // line, instead of from the start of the first line. This way we get + // an indent when we get into insert mode. This behavior isn't quite + // correct because we should treat this as a completely new line, and + // indent should be whatever codemirror thinks is the right indent. + // But cm.indentLine doesn't seem work on empty lines. + // TODO: Fix the above. + curStart.ch = + findFirstNonWhiteSpaceCharacter(cm.getLine(curStart.line)); + // Insert an additional newline so that insert mode can start there. + // curEnd should be on the first character of the new line. + cm.replaceRange('\n', curStart, curEnd); + } else { + cm.replaceRange('', curStart, curEnd); + } + cm.setCursor(curStart); + }, + // delete is a javascript keyword. + 'delete': function(cm, operatorArgs, vim, curStart, curEnd) { + getVimGlobalState().registerController.pushText( + operatorArgs.registerName, 'delete', cm.getRange(curStart, curEnd), + operatorArgs.linewise); + cm.replaceRange('', curStart, curEnd); + if (operatorArgs.linewise) { + cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm)); + } else { + cm.setCursor(curStart); + } + }, + indent: function(cm, operatorArgs, vim, curStart, curEnd) { + var startLine = curStart.line; + var endLine = curEnd.line; + // In visual mode, n> shifts the selection right n times, instead of + // shifting n lines right once. + var repeat = (vim.visualMode) ? operatorArgs.repeat : 1; + if (operatorArgs.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, operatorArgs.indentRight); + } + } + cm.setCursor(curStart); + cm.setCursor(motions.moveToFirstNonWhiteSpaceCharacter(cm)); + }, + swapcase: function(cm, operatorArgs, vim, curStart, curEnd, curOriginal) { + var toSwap = cm.getRange(curStart, curEnd); + var swapped = ''; + for (var i = 0; i < toSwap.length; i++) { + var character = toSwap.charAt(i); + swapped += isUpperCase(character) ? character.toLowerCase() : + character.toUpperCase(); + } + cm.replaceRange(swapped, curStart, curEnd); + cm.setCursor(curOriginal); + }, + yank: function(cm, operatorArgs, vim, curStart, curEnd, curOriginal) { + getVimGlobalState().registerController.pushText( + operatorArgs.registerName, 'yank', + cm.getRange(curStart, curEnd), operatorArgs.linewise); + cm.setCursor(curOriginal); + } + }; + + var actions = { + scrollToCursor: function(cm, actionArgs) { + var lineNum = cm.getCursor().line; + var heightProp = window.getComputedStyle(cm.getScrollerElement()). + getPropertyValue('height'); + var height = parseInt(heightProp); + var y = cm.charCoords({line: lineNum, ch: 0}, "local").top; + var halfHeight = parseInt(height) / 2; + switch (actionArgs.position) { + case 'center': y = y - (height / 2) + 10; + break; + case 'bottom': y = y - height; + break; + case 'top': break; + } + cm.scrollTo(null, y); + // The calculations are slightly off, use scrollIntoView to nudge the + // view into the right place. + cm.scrollIntoView(); + }, + enterInsertMode: function(cm, actionArgs) { + var insertAt = (actionArgs) ? actionArgs.insertAt : null; + if (insertAt == 'eol') { + var cursor = cm.getCursor(); + cursor = { line: cursor.line, ch: lineLength(cm, cursor.line) }; + cm.setCursor(cursor); + } else if (insertAt == 'charAfter') { + cm.setCursor(offsetCursor(cm.getCursor(), 0, 1)); + } + cm.setOption('keyMap', 'vim-insert'); + }, + toggleVisualMode: function(cm, actionArgs, vim) { + var repeat = actionArgs.repeat; + var curStart = cm.getCursor(); + var curEnd; + // 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) { + vim.visualMode = true; + vim.visualLine = !!actionArgs.linewise; + if (vim.visualLine) { + curStart.ch = 0; + curEnd = clipCursorToContent(cm, { + line: curStart.line + repeat - 1, + ch: lineLength(cm, curStart.line) + }, true /** includeLineBreak */); + } else { + curEnd = clipCursorToContent(cm, { + line: curStart.line, + ch: curStart.ch + repeat + }, true /** includeLineBreak */); + } + // Make the initial selection. + if (!actionArgs.repeatIsExplicit && !vim.visualLine) { + // This is a strange case. Here the implicit repeat is 1. The + // following commands lets the cursor hover over the 1 character + // selection. + cm.setCursor(curEnd); + cm.setSelection(curEnd, curStart); + } else { + cm.setSelection(curStart, curEnd); + } + } else { + curStart = cm.getCursor('anchor'); + curEnd = cm.getCursor('head'); + if (!vim.visualLine && actionArgs.linewise) { + // Shift-V pressed in characterwise visual mode. Switch to linewise + // visual mode instead of exiting visual mode. + vim.visualLine = true; + curStart.ch = cursorIsBefore(curStart, curEnd) ? 0 : + lineLength(cm, curStart.line); + curEnd.ch = cursorIsBefore(curStart, curEnd) ? + lineLength(cm, curEnd.line) : 0; + cm.setSelection(curStart, curEnd); + } else if (vim.visualLine && !actionArgs.linewise) { + // v pressed in linewise visual mode. Switch to characterwise visual + // mode instead of exiting visual mode. + vim.visualLine = false; + } else { + exitVisualMode(cm, vim); + } + } + updateMark(cm, vim, '<', cursorIsBefore(curStart, curEnd) ? curStart + : curEnd); + updateMark(cm, vim, '>', cursorIsBefore(curStart, curEnd) ? curEnd + : curStart); + }, + joinLines: function(cm, actionArgs, vim) { + var curStart, curEnd; + if (vim.visualMode) { + curStart = cm.getCursor('anchor'); + curEnd = cm.getCursor('head'); + 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, { line: curStart.line + repeat - 1, + ch: Infinity }); + } + var finalCh = 0; + cm.operation(function() { + for (var i = curStart.line; i < curEnd.line; i++) { + finalCh = lineLength(cm, curStart.line); + var tmp = { line: curStart.line + 1, + ch: lineLength(cm, curStart.line + 1) }; + var text = cm.getRange(curStart, tmp); + text = text.replace(/\n\s*/g, ' '); + cm.replaceRange(text, curStart, tmp); + } + var curFinalPos = { line: curStart.line, ch: finalCh }; + cm.setCursor(curFinalPos); + }); + }, + newLineAndEnterInsertMode: function(cm, actionArgs) { + var insertAt = cm.getCursor(); + if (insertAt.line === cm.firstLine() && !actionArgs.after) { + // Special case for inserting newline before start of document. + cm.replaceRange('\n', { line: cm.firstLine(), ch: 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); + }, + paste: function(cm, actionArgs, vim) { + var cur = cm.getCursor(); + var register = getVimGlobalState().registerController.getRegister( + actionArgs.registerName); + if (!register.text) { + return; + } + for (var text = '', i = 0; i < actionArgs.repeat; i++) { + text += register.text; + } + var linewise = register.linewise; + if (linewise) { + 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 { + cur.ch += actionArgs.after ? 1 : 0; + } + cm.replaceRange(text, cur); + // Now fine tune the cursor to where we want it. + var curPosFinal; + var idx; + if (linewise && actionArgs.after) { + curPosFinal = { line: cur.line + 1, + ch: findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)) }; + } else if (linewise && !actionArgs.after) { + curPosFinal = { line: cur.line, + ch: 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); + } + cm.setCursor(curPosFinal); + }, + undo: function(cm, actionArgs) { + repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)(); + }, + 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) { + var replaceWith = actionArgs.selectedCharacter; + var curStart = cm.getCursor(); + var line = cm.getLine(curStart.line); + var replaceTo = curStart.ch + actionArgs.repeat; + if (replaceTo > line.length) { + return; + } + var curEnd = { line: curStart.line, ch: replaceTo }; + var replaceWithStr = ''; + for (var i = 0; i < curEnd.ch - curStart.ch; i++) { + replaceWithStr += replaceWith; + } + cm.replaceRange(replaceWithStr, curStart, curEnd); + cm.setCursor(offsetCursor(curEnd, 0, -1)); + } + }; + + var textObjects = { + // TODO: lots of possible exceptions that can be thrown here. Try da( + // outside of a () block. + // TODO: implement text objects for the reverse like }. Should just be + // an additional mapping after moving to the defaultKeyMap. + 'w': function(cm, inclusive) { + return expandWordUnderCursor(cm, inclusive, true /** forward */, + false /** bigWord */); + }, + 'W': function(cm, inclusive) { + return expandWordUnderCursor(cm, inclusive, + true /** forward */, true /** bigWord */); + }, + '{': function(cm, inclusive) { + return selectCompanionObject(cm, '}', inclusive); + }, + '(': function(cm, inclusive) { + return selectCompanionObject(cm, ')', inclusive); + }, + '[': function(cm, inclusive) { + return selectCompanionObject(cm, ']', inclusive); + }, + '\'': function(cm, inclusive) { + return findBeginningAndEnd(cm, "'", inclusive); + }, + '\"': function(cm, inclusive) { + return findBeginningAndEnd(cm, '"', inclusive); + } + }; + + /* + * 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 { line: line, ch: ch }; + } + // Merge arguments in place, for overriding arguments. + function mergeArgs(to, from) { + for (var prop in from) { + if (from.hasOwnProperty(prop)) { + to[prop] = from[prop]; + } + } + } + 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) { + return { line: cur.line + offsetLine, ch: cur.ch + offsetCh }; + } + function arrayEq(a1, a2) { + if (a1.length != a2.length) { + return false; + } + for (var i = 0; i < a1.length; i++) { + if (a1[i] != a2[i]) { + return false; + } + } + return true; + } + function matchKeysPartial(pressed, mapped) { + for (var i = 0; i < pressed.length; i++) { + // 'character' means any character. For mark, register commads, etc. + if (pressed[i] != mapped[i] && mapped[i] != 'character') { + return false; + } + } + return true; + } + function arrayIsSubsetFromBeginning(small, big) { + for (var i = 0; i < small.length; i++) { + if (small[i] != big[i]) { + return false; + } + } + return true; + } + function repeatFn(cm, fn, repeat) { + return function() { + for (var i = 0; i < repeat; i++) { + fn(cm); + } + }; + } + function copyCursor(cur) { + return { line: cur.line, ch: 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; + } else if (cur1.line == cur2.line && cur1.ch < cur2.ch) { + return true; + } + return false; + } + function lineLength(cm, lineNum) { + return cm.getLine(lineNum).length; + } + function reverse(s){ + return s.split("").reverse().join(""); + } + function trim(s) { + if (s.trim) { + return s.trim(); + } else { + return s.replace(/^\s+|\s+$/g, ''); + } + } + function escapeRegex(s) { + return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, "\\$1"); + } + + function exitVisualMode(cm, vim) { + vim.visualMode = false; + vim.visualLine = false; + var selectionStart = cm.getCursor('anchor'); + var selectionEnd = cm.getCursor('head'); + if (!cursorEqual(selectionStart, selectionEnd)) { + // Clear the selection and set the cursor only if the selection has not + // already been cleared. Otherwise we risk moving the cursor somewhere + // it's not supposed to be. + cm.setCursor(clipCursorToContent(cm, selectionEnd)); + } + } + + // 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); + var lines = selection.split('\n'); + if (lines.length > 1 && isWhiteSpaceString(lines.pop())) { + curEnd.line--; + curEnd.ch = lineLength(cm, curEnd.line); + } + } + + // 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 = cm.getCursor(); + 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 textAfterIdx = line.substring(idx); + var firstMatchedChar; + if (noSymbol) { + firstMatchedChar = textAfterIdx.search(/\w/); + } else { + firstMatchedChar = textAfterIdx.search(/\S/); + } + if (firstMatchedChar == -1) { + return null; + } + idx += firstMatchedChar; + textAfterIdx = line.substring(idx); + var textBeforeIdx = line.substring(0, idx); + + var matchRegex; + // Greedy matchers for the "word" we are trying to expand. + if (bigWord) { + matchRegex = /^\S+/; + } else { + if ((/\w/).test(line.charAt(idx))) { + matchRegex = /^\w+/; + } else { + matchRegex = /^[^\w\s]+/; + } + } + + var wordAfterRegex = matchRegex.exec(textAfterIdx); + var wordStart = idx; + var wordEnd = idx + wordAfterRegex[0].length - 1; + // TODO: Find a better way to do this. It will be slow on very long lines. + var wordBeforeRegex = matchRegex.exec(reverse(textBeforeIdx)); + if (wordBeforeRegex) { + wordStart -= wordBeforeRegex[0].length; + } + + if (inclusive) { + wordEnd++; + } + + return { start: { line: cur.line, ch: wordStart }, + end: { line: cur.line, ch: wordEnd }}; + } + + /* + * 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. + * @return {Object{from:number, to:number, line: number}} The boundaries of + * the word, or null if there are no more words. + */ + // TODO: Treat empty lines (with no whitespace) as words. + function findWord(cm, cur, forward, bigWord) { + var lineNum = cur.line; + var pos = cur.ch; + var line = cm.getLine(lineNum); + var dir = forward ? 1 : -1; + var regexps = bigWord ? bigWordRegexp : wordRegexp; + + while (true) { + 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 < regexps.length && !foundWord; ++i) { + if (regexps[i].test(line.charAt(pos))) { + wordStart = pos; + // Advance to end of word. + while (pos != stop && regexps[i].test(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; + } + // Should never get here. + throw 'The impossible happened.'; + } + + /** + * @param {CodeMirror} cm CodeMirror object. + * @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, repeat, forward, wordEnd, bigWord) { + var cur = cm.getCursor(); + for (var i = 0; i < repeat; i++) { + var startCh = cur.ch, startLine = cur.line, word; + var movedToNextWord = false; + while (!movedToNextWord) { + // Search and advance. + word = findWord(cm, cur, forward, bigWord); + movedToNextWord = true; + if (word) { + // Move to the word we just found. If by moving to the word we end + // up in the same spot, then move an extra character and search + // again. + cur.line = word.line; + if (forward && wordEnd) { + // 'e' + cur.ch = word.to - 1; + } else if (forward && !wordEnd) { + // 'w' + if (inRangeInclusive(cur.ch, word.from, word.to) && + word.line == startLine) { + // Still on the same word. Go to the next one. + movedToNextWord = false; + cur.ch = word.to - 1; + } else { + cur.ch = word.from; + } + } else if (!forward && wordEnd) { + // 'ge' + if (inRangeInclusive(cur.ch, word.from, word.to) && + word.line == startLine) { + // still on the same word. Go to the next one. + movedToNextWord = false; + cur.ch = word.from; + } else { + cur.ch = word.to; + } + } else if (!forward && !wordEnd) { + // 'b' + cur.ch = word.from; + } + } else { + // No more words to be found. Move to the end. + if (forward) { + return { line: cur.line, ch: lineLength(cm, cur.line) }; + } else { + return { line: cur.line, ch: 0 }; + } + } + } + } + return cur; + } + + 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 cur; + } + start = idx; + } + return { line: cm.getCursor().line, ch: 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, { line: line, ch: 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 findMatchedSymbol(cm, cur, symb) { + var line = cur.line; + symb = symb ? symb : cm.getLine(line).charAt(cur.ch); + + // Are we at the opening or closing char + var forwards = inArray(symb, ['(', '[', '{']); + + var reverseSymb = ({ + '(': ')', ')': '(', + '[': ']', ']': '[', + '{': '}', '}': '{'})[symb]; + + // Couldn't find a matching symbol, abort + if (!reverseSymb) { + return cur; + } + + // set our increment to move forward (+1) or backwards (-1) + // depending on which bracket we're matching + var increment = ({'(': 1, '{': 1, '[': 1})[symb] || -1; + var depth = 1, nextCh = symb, index = cur.ch, lineText = cm.getLine(line); + // Simple search for closing paren--just count openings and closings till + // we find our match + // TODO: use info from CodeMirror to ignore closing brackets in comments + // and quotes, etc. + while (nextCh && depth > 0) { + index += increment; + nextCh = lineText.charAt(index); + if (!nextCh) { + line += increment; + lineText = cm.getLine(line) || ''; + if (increment > 0) { + index = 0; + } else { + var lineLen = lineText.length; + index = (lineLen > 0) ? (lineLen-1) : 0; + } + nextCh = lineText.charAt(index); + } + if (nextCh === symb) { + depth++; + } else if (nextCh === reverseSymb) { + depth--; + } + } + + if (nextCh) { + return { line: line, ch: index }; + } + return cur; + } + + function selectCompanionObject(cm, revSymb, inclusive) { + var cur = cm.getCursor(); + + var end = findMatchedSymbol(cm, cur, revSymb); + var start = findMatchedSymbol(cm, end); + start.ch += inclusive ? 1 : 0; + end.ch += inclusive ? 0 : 1; + + return { start: start, end: end }; + } + + function regexLastIndexOf(string, pattern, startIndex) { + for (var i = !startIndex ? string.length : startIndex; + i >= 0; --i) { + if (pattern.test(string.charAt(i))) { + return i; + } + } + return -1; + } + + // 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, symb, inclusive) { + var cur = cm.getCursor(); + 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: { line: cur.line, ch: start }, + end: { line: cur.line, ch: end } + }; + } + + // Search functions + function SearchState() { + // Highlighted text that match the query. + this.marked = null; + } + SearchState.prototype = { + getQuery: function() { + return getVimGlobalState().query; + }, + setQuery: function(query) { + getVimGlobalState().query = query; + }, + getMarked: function() { + return this.marked; + }, + setMarked: function(marked) { + this.marked = marked; + }, + getOverlay: function() { + return this.searchOverlay; + }, + setOverlay: function(overlay) { + this.searchOverlay = overlay; + }, + isReversed: function() { + return getVimGlobalState().isReversed; + }, + setReversed: function(reversed) { + getVimGlobalState().isReversed = reversed; + } + }; + function getSearchState(cm) { + var vim = getVimState(cm); + return vim.searchState_ || (vim.searchState_ = new SearchState()); + } + function dialog(cm, text, shortText, callback, initialValue) { + if (cm.openDialog) { + cm.openDialog(text, callback, { bottom: true, value: initialValue }); + } + else { + callback(prompt(shortText, "")); + } + } + function findUnescapedSlashes(str) { + var escapeNextChar = false; + var slashes = []; + for (var i = 0; i < str.length; i++) { + var c = str.charAt(i); + if (!escapeNextChar && c == '/') { + slashes.push(i); + } + escapeNextChar = (c == '\\'); + } + return slashes; + } + /** + * 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(cm, query, ignoreCase, smartCase) { + // 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 (smartCase) { + ignoreCase = (/^[^A-Z]*$/).test(regexPart); + } + try { + var regexp = new RegExp(regexPart, + (ignoreCase || forceIgnoreCase) ? 'i' : undefined); + return regexp; + } catch (e) { + showConfirm(cm, 'Invalid regex: ' + regexPart); + } + } + function showConfirm(cm, text) { + if (cm.openConfirm) { + cm.openConfirm('' + text + + ' ', function() {}, + {bottom: true}); + } else { + alert(text); + } + } + function makePrompt(prefix, desc) { + var raw = ''; + if (prefix) { + raw += '' + prefix + ''; + } + raw += ' ' + + ''; + if (desc) { + raw += ''; + raw += desc; + raw += ''; + } + return raw; + } + var searchPromptDesc = '(Javascript regexp)'; + function showPrompt(cm, onPromptClose, prefix, desc, initialValue) { + var shortText = (prefix || '') + ' ' + (desc || ''); + dialog(cm, makePrompt(prefix, desc), shortText, onPromptClose, + initialValue); + } + 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); + } + function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) { + cm.operation(function() { + var state = getSearchState(cm); + if (!rawQuery) { + return; + } + var query = parseQuery(cm, rawQuery, !!ignoreCase, !!smartCase); + if (!query) { + return; + } + if (regexEqual(query, state.getQuery())) { + return; + } + clearSearchHighlight(cm); + highlightSearchMatches(cm, query); + state.setQuery(query); + }); + } + function searchOverlay(query) { + return { + token: function(stream) { + var match = stream.match(query, false); + if (match) { + 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) { + if (cm.addOverlay) { + var overlay = getSearchState(cm).getOverlay(); + if (!overlay || query != overlay.query) { + if (overlay) { + cm.removeOverlay(overlay); + } + overlay = searchOverlay(query); + cm.addOverlay(overlay); + getSearchState(cm).setOverlay(overlay); + } + } else { + // TODO: Highlight only text inside the viewport. Highlighting everything + // is inefficient and expensive. + if (cm.lineCount() < 2000) { // This is too expensive on big documents. + var marked = []; + for (var cursor = cm.getSearchCursor(query); + cursor.findNext();) { + marked.push(cm.markText(cursor.from(), cursor.to(), + { className: 'cm-searching' })); + } + getSearchState(cm).setMarked(marked); + } + } + } + function findNext(cm, prev, repeat) { + return cm.operation(function() { + var state = getSearchState(cm); + var query = state.getQuery(); + if (!query) { + return; + } + if (!state.getMarked()) { + highlightSearchMatches(cm, query); + } + var pos = cm.getCursor(); + // If search is initiated with ? instead of /, negate direction. + prev = (state.isReversed()) ? !prev : prev; + if (!prev) { + pos.ch += 1; + } + var cursor = cm.getSearchCursor(query, pos); + for (var i = 0; i < repeat; i++) { + if (!cursor.find(prev)) { + // SearchCursor may have returned null because it hit EOF, wrap + // around and try again. + cursor = cm.getSearchCursor(query, + (prev) ? { line: cm.lastLine() } : {line: cm.firstLine(), ch: 0} ); + if (!cursor.find(prev)) { + return; + } + } + } + return cursor.from(); + });} + function clearSearchHighlight(cm) { + if (cm.addOverlay) { + cm.removeOverlay(getSearchState(cm).getOverlay()); + getSearchState(cm).setOverlay(null); + } else { + cm.operation(function() { + var state = getSearchState(cm); + if (!state.getQuery()) { + return; + } + var marked = state.getMarked(); + if (!marked) { + return; + } + for (var i = 0; i < marked.length; ++i) { + marked[i].clear(); + } + state.setMarked(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; + } + } + } + + // Ex command handling + // 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: 'map', type: 'builtIn' }, + { name: 'write', shortName: 'w', type: 'builtIn' }, + { name: 'undo', shortName: 'u', type: 'builtIn' }, + { name: 'redo', shortName: 'red', type: 'builtIn' }, + { name: 'substitute', shortName: 's', type: 'builtIn'}, + { name: 'nohlsearch', shortName: 'noh', type: 'builtIn'} + ]; + Vim.ExCommandDispatcher = function() { + this.buildCommandMap_(); + }; + Vim.ExCommandDispatcher.prototype = { + processCommand: function(cm, input) { + var inputStream = new CodeMirror.StringStream(input); + var params = {}; + params.input = input; + try { + this.parseInput_(cm, inputStream, params); + } catch(e) { + showConfirm(cm, e); + return; + } + var commandName; + if (!params.commandName) { + // If only a line range is defined, move to the line. + if (params.line !== undefined) { + commandName = 'move'; + } + } else { + var command = this.matchCommand_(params.commandName); + if (command) { + commandName = command.name; + this.parseCommandArgs_(inputStream, params, command); + if (command.type == 'exToKey') { + // Handle Ex to Key mapping. + for (var i = 0; i < command.toKeys.length; i++) { + vim.handleKey(cm, command.toKeys[i]); + } + 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; + } + exCommands[commandName](cm, params); + }, + 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) { + return parseInt(numberMatch[1], 10) - 1; + } + switch (inputStream.next()) { + case '.': + return cm.getCursor().line; + case '$': + return cm.lastLine(); + case '\'': + var mark = getVimState(cm).marks[inputStream.next()]; + if (mark && mark.find()) { + return mark.find().line; + } else { + throw "Mark not set"; + } + break; + default: + inputStream.backUp(1); + return cm.getCursor().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) { + if (lhs != ':' && lhs.charAt(0) == ':') { + 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) + }; + } else { + // Ex to key mapping + this.commandMap_[commandName] = { + name: commandName, + type: 'exToKey', + toKeys: parseKeyString(rhs) + }; + } + } else { + if (rhs != ':' && rhs.charAt(0) == ':') { + // Key to Ex mapping. + defaultKeymap.unshift({ + keys: parseKeyString(lhs), + type: 'keyToEx', + exArgs: { input: rhs.substring(1) }}); + } else { + // Key to key mapping + defaultKeymap.unshift({ + keys: parseKeyString(lhs), + type: 'keyToKey', + toKeys: parseKeyString(rhs) + }); + } + } + } + }; + + // Converts a key string sequence of the form abd into Vim's + // keymap representation. + function parseKeyString(str) { + var idx = 0; + var keys = []; + while (idx < str.length) { + if (str.charAt(idx) != '<') { + keys.push(str.charAt(idx)); + idx++; + continue; + } + // Vim key notation here means desktop Vim key-notation. + // See :help key-notation in desktop Vim. + var vimKeyNotationStart = ++idx; + while (str.charAt(idx++) != '>') {} + var vimKeyNotation = str.substring(vimKeyNotationStart, idx - 1); + var mod=''; + var match = (/^C-(.+)$/).exec(vimKeyNotation); + if (match) { + mod='Ctrl-'; + vimKeyNotation=match[1]; + } + var key; + switch (vimKeyNotation) { + case 'BS': + key = 'Backspace'; + break; + case 'CR': + key = 'Enter'; + break; + case 'Del': + key = 'Delete'; + break; + default: + key = vimKeyNotation; + break; + } + keys.push(mod + key); + } + return keys; + } + + var exCommands = { + map: function(cm, params) { + var mapArgs = params.args; + if (!mapArgs || mapArgs.length < 2) { + if (cm) { + showConfirm(cm, 'Invalid mapping: ' + params.input); + } + return; + } + exCommandDispatcher.map(mapArgs[0], mapArgs[1], cm); + }, + move: function(cm, params) { + commandDispatcher.processMotion(cm, getVimState(cm), { + motion: 'moveToLineOrEdgeOfDocument', + motionArgs: { forward: false, explicitRepeat: true, + linewise: true, repeat: params.line+1 }}); + }, + substitute: function(cm, params) { + var argString = params.argString; + var slashes = findUnescapedSlashes(argString); + if (slashes[0] !== 0) { + showConfirm(cm, 'Substitutions should be of the form ' + + ':s/pattern/replace/'); + return; + } + var regexPart = argString.substring(slashes[0] + 1, slashes[1]); + var replacePart = ''; + var flagsPart; + var count; + if (slashes[1]) { + replacePart = argString.substring(slashes[1] + 1, slashes[2]); + } + if (slashes[2]) { + // After the 3rd slash, we can have flags followed by a space followed + // by count. + var trailing = argString.substring(slashes[2] + 1).split(' '); + flagsPart = trailing[0]; + count = parseInt(trailing[1]); + } + if (flagsPart) { + regexPart = regexPart + '/' + flagsPart; + } + if (regexPart) { + // If regex part is empty, then use the previous query. Otherwise use + // the regex part as the new query. + updateSearchQuery(cm, regexPart, true /** ignoreCase */, + true /** smartCase */); + } + var state = getSearchState(cm); + var query = state.getQuery(); + var lineStart = params.line || cm.firstLine(); + var lineEnd = params.lineEnd || lineStart; + if (count) { + lineStart = lineEnd; + lineEnd = lineStart + count - 1; + } + var startPos = clipCursorToContent(cm, { line: lineStart, ch: 0 }); + function doReplace() { + for (var cursor = cm.getSearchCursor(query, startPos); + cursor.findNext() && + isInRange(cursor.from(), lineStart, lineEnd);) { + var text = cm.getRange(cursor.from(), cursor.to()); + var newText = text.replace(query, replacePart); + cursor.replace(newText); + } + var vim = getVimState(cm); + if (vim.visualMode) { + exitVisualMode(cm, vim); + } + } + if (cm.compoundChange) { + // Only exists in v2 + cm.compoundChange(doReplace); + } else { + cm.operation(doReplace); + } + }, + 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 { + // Saves to text area if no save command is defined. + cm.save(); + } + }, + nohlsearch: function(cm) { + clearSearchHighlight(cm); + } + }; + + var exCommandDispatcher = new Vim.ExCommandDispatcher(); + + // Register Vim with CodeMirror + function buildVimKeyMap() { + /** + * Handle the raw key event from CodeMirror. Translate the + * Shift + key modifier to the resulting letter, while preserving other + * modifers. + */ + // TODO: Figure out a way to catch capslock. + function handleKeyEvent_(cm, key, modifier) { + if (isUpperCase(key)) { + // Convert to lower case if shift is not the modifier since the key + // we get from CodeMirror is always upper case. + if (modifier == 'Shift') { + modifier = null; + } + else { + key = key.toLowerCase(); + } + } + if (modifier) { + // Vim will parse modifier+key combination as a single key. + key = modifier + '-' + key; + } + vim.handleKey(cm, key); + } + + // Closure to bind CodeMirror, key, modifier. + function keyMapper(key, modifier) { + return function(cm) { + handleKeyEvent_(cm, key, modifier); + }; + } + + var modifiers = ['Shift', 'Ctrl']; + var keyMap = { + 'nofallthrough': true, + 'style': 'fat-cursor' + }; + function bindKeys(keys, modifier) { + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (!modifier && inArray(key, specialSymbols)) { + // Wrap special symbols with '' because that's how CodeMirror binds + // them. + key = "'" + key + "'"; + } + if (modifier) { + keyMap[modifier + '-' + key] = keyMapper(keys[i], modifier); + } else { + keyMap[key] = keyMapper(keys[i]); + } + } + } + bindKeys(upperCaseAlphabet); + bindKeys(upperCaseAlphabet, 'Shift'); + bindKeys(upperCaseAlphabet, 'Ctrl'); + bindKeys(specialSymbols); + bindKeys(specialSymbols, 'Ctrl'); + bindKeys(numbers); + bindKeys(numbers, 'Ctrl'); + bindKeys(specialKeys); + bindKeys(specialKeys, 'Ctrl'); + return keyMap; + } + CodeMirror.keyMap.vim = buildVimKeyMap(); + + function exitInsertMode(cm) { + cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1, true); + cm.setOption('keyMap', 'vim'); + } + + CodeMirror.keyMap['vim-insert'] = { + // TODO: override navigation keys so that Esc will cancel automatic + // indentation from o, O, i_ + 'Esc': exitInsertMode, + 'Ctrl-[': exitInsertMode, + 'Ctrl-C': exitInsertMode, + 'Ctrl-N': 'autocomplete', + 'Ctrl-P': 'autocomplete', + 'Enter': function(cm) { + var fn = CodeMirror.commands.newlineAndIndentContinueComment || + CodeMirror.commands.newlineAndIndent; + fn(cm); + }, + fallthrough: ['default'] + }; + + return vimApi; + }; + // Initialize Vim and make it available as an API. + var vim = Vim(); + CodeMirror.Vim = vim; +} +)(); diff --git a/lib/codemirror-3.1/lib/codemirror.css b/lib/codemirror-3.1/lib/codemirror.css new file mode 100644 index 0000000000000000000000000000000000000000..c7a8ae70478fc8f253524bb64c0094766f191c1b --- /dev/null +++ b/lib/codemirror-3.1/lib/codemirror.css @@ -0,0 +1,346 @@ +/* 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; } diff --git a/lib/codemirror-3.1/lib/codemirror.js b/lib/codemirror-3.1/lib/codemirror.js new file mode 100644 index 0000000000000000000000000000000000000000..f225674421246cff474c5aa88b71c751c7c18373 --- /dev/null +++ b/lib/codemirror-3.1/lib/codemirror.js @@ -0,0 +1,9657 @@ +// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +// This is CodeMirror (http://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}; +var sel_mouse = {origin: "*mouse"}; +var 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; +var 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) } + +// 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, from, to, marker) { + var line = getLine(doc, lineNo) + 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 = emitter._handlers || (emitter._handlers = {}) + map[type] = (map[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 = emitter._handlers, arr = map && map[type] + if (arr) { + var index = indexOf(arr, f) + if (index > -1) + { map[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 + try {range = te.ownerDocument.selection.createRange()} + catch(e) {} + if (!range || range.parentElement() != te) { return false } + return range.compareEndPoints("StartToEnd", range) != 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 +} + +var modes = {}; +var 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 = {}; +var 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: (ie || webkit) && 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, title, css) { + 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 (title) { token.title = title } + return builder.content.appendChild(token) + } + builder.content.appendChild(content) +} + +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, title, css) { + 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, title, css) } + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css) + 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, title, collapsed + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = "" + 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) } + if (m.title && !title) { title = m.title } + 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 : "", title, css) + } + 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, 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.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) { + 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 merged = collapsedSpanAtEnd(lineObj) + var mergedPos = merged && merged.find(0, true) + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) + { lineN = lineNo(lineObj = mergedPos.to.line) } + else + { return found } + } +} + +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, 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 = 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, 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; 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) + + 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 <= 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, 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. + var index = findFirst(function (i) { + var 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) + 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, 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 = doc.sel.ranges[i] + if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue } + var 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 +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, 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.from(), sTo = range.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], height = (void 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 + } + 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]) } } + } + } +} + +// 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) { + 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) { + var range = cm.curOp.scrollToPos + if (range) { + cm.curOp.scrollToPos = null + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to) + scrollToCoordsRange(cm, from, to, range.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") + 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 = 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) +}; + +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: null, // 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 + 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 = 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. +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) + } +} + +var wheelSamples = 0; +var 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(ranges, primIndex) { + 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] + if (cmp(prev.to(), cur.from()) >= 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(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) { + 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) { + var result = [] + for (var i = start; i < end; ++i) + { result.push(new Line(text[i], spansFor(i), estimateHeight)) } + 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)) + 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) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + 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(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(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(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 = 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(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) { 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) { + if (doc.cm && doc.cm.state.suppressEdits && !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 { 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) { + if (!to) { to = from } + if (cmp(to, from) < 0) { var assign; + (assign = [to, from], from = assign[0], to = assign[1], assign) } + 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 chunkSize() { return this.lines.length }, + + // Remove the n lines at offset 'at'. + removeInner: function removeInner(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 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: function insertInner(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 iterN(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 chunkSize() { return this.size }, + + removeInner: function removeInner(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 collapse(lines) { + var this$1 = this; + + for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines) } + }, + + insertInner: function insertInner(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 maybeSpill() { + 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 iterN(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 } + 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 + }) + 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.title || marker.startStyle || marker.endStyle || marker.css) + { 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 = 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) { + 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(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(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 = sel.ranges[i] + changes[i] = {from: range.from(), to: range.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 = 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 == 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() { + 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 = 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 + }) + return clipPos(this, Pos(lineNo, 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") + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror + if (cm) { f(cm) } + } +} + +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 + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) + { return } + // 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, handle, context) { + map = getKeyMap(map) + var 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 (var i = 0; i < map.fallthrough.length; i++) { + var 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. +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; +var 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) { onContextMenu(cm, 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(document, "mouseup", dragEnd) + off(document, "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 () {document.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(document, "mouseup", dragEnd) + on(document, "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 = 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(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}) + } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { + setSelection(doc, normalizeSelection(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(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}) + cm.scrollIntoView(pos) + } else { + var oldRange = ourRange + var range = rangeForUnit(cm, pos, behavior.unit) + var 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) + } + var ranges$1 = startSel.ranges.slice(0) + ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)) + setSelection(doc, normalizeSelection(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(document, "mousemove", move) + off(document, "mouseup", up) + doc.history.lastSelOrigin = null + } + + var move = operation(cm, function (e) { + if (!e_button(e)) { done(e) } + else { extend(e) } + }) + var up = operation(cm, done) + cm.state.selectingText = up + on(document, "mousemove", move) + on(document, "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) { + var anchor = range.anchor; + var head = range.head; + var anchorLine = getLine(cm.doc, anchor.line) + if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range } + var order = getOrder(anchorLine) + if (!order) { return range } + var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index] + if (part.from != anchor.ch && part.to != anchor.ch) { return range } + var 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) + 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 : 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 } + 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("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("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) +} + +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) } + 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. + if (!captureRightClick) { 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 + // 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 = sel.ranges[i$1] + var 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 (lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) + { from = to = Pos(from.line, 0) } + } + updateInput = cm.curOp.updateInput + 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) + 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 = sel.ranges[i] + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue } + var mode = cm.getModeAt(range.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.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) } + } +} + +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) { + field.setAttribute("autocorrect", "off") + field.setAttribute("autocapitalize", "off") + 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, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)) + }, + removeKeyMap: function(map) { + var maps = this.state.keyMaps + for (var 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) { + 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 = ranges[i] + if (!range.empty()) { + var from = range.from(), to = range.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.head.line > end) { + indentLine(this$1, range.head.line, how, true) + end = range.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 = 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) { + 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) { + if (this$1.display.shift || this$1.doc.extend || range.empty()) + { return findPosH(this$1.doc, range.head, dir, unit, this$1.options.rtlMoveVisually) } + else + { return dir < 0 ? range.from() : range.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) { + var 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) { + 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) { + if (collapse) + { return dir < 0 ? range.from() : range.to() } + var headPos = cursorCoords(this$1, range.head, "div") + if (range.goalColumn != null) { headPos.left = range.goalColumn } + goals.push(headPos.left) + var pos = findPosV(this$1, headPos, dir, unit) + if (unit == "page" && range == 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, 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) { + 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 = this.display.viewFrom + this.doc.iter(lineNo, 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, "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() { + 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 + }), + + 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) + + 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.showPrimarySelection = function () { + var sel = window.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 = 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 + } + + 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 = window.getSelection() + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset +}; + +ContentEditableInput.prototype.selectionInEditor = function () { + var sel = window.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 = window.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 = window.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) { 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() + function recognizeMarker(id) { return function (marker) { return marker.id == id; } } + function close() { + if (closing) { + text += lineSep + closing = false + } + } + function addText(str) { + if (str) { + close() + text += str + } + } + function walk(node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text") + if (cmText != null) { + addText(cmText || node.textContent.replace(/\u200b/g, "")) + return + } + var markerID = node.getAttribute("cm-marker"), range + if (markerID) { + var 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 } + var isBlock = /^(pre|div|p)$/i.test(node.nodeName) + if (isBlock) { close() } + for (var i = 0; i < node.childNodes.length; i++) + { walk(node.childNodes[i]) } + if (isBlock) { closing = true } + } else if (node.nodeType == 3) { + addText(node.nodeValue) + } + } + for (;;) { + walk(from) + if (from == to) { break } + from = from.nextSibling + } + 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 = i < 0 ? measure.map : maps[i] + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2] + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]) + var ch = map[j] + offset + if (offset < 0 || curNode != textNode) { ch = map[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 + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea() + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild + display.wrapper.insertBefore(div, 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.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 + 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 + input.wrapper.style.cssText = "position: absolute" + var wrapperBox = input.wrapper.getBoundingClientRect() + 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 = true + 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() { + 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) + +// INPUT HANDLING + +CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput} + +// MODE DEFINITION AND QUERYING + +// 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.34.0" + +return CodeMirror; + +}))); \ No newline at end of file diff --git a/lib/codemirror-3.1/mode/apl/apl.js b/lib/codemirror-3.1/mode/apl/apl.js new file mode 100644 index 0000000000000000000000000000000000000000..5c23af85da1eb102879160677a9c0f38c6c76fbd --- /dev/null +++ b/lib/codemirror-3.1/mode/apl/apl.js @@ -0,0 +1,160 @@ +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, word; + 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\$_]/); + word = stream.current(); + state.prev = true; + return "keyword"; + } + }; +}); + +CodeMirror.defineMIME("text/apl", "apl"); diff --git a/lib/codemirror-3.1/mode/apl/index.html b/lib/codemirror-3.1/mode/apl/index.html new file mode 100644 index 0000000000000000000000000000000000000000..119ff17f19ce09b19c0188b52a2fe4113ce380c9 --- /dev/null +++ b/lib/codemirror-3.1/mode/apl/index.html @@ -0,0 +1,61 @@ + + + + + CodeMirror: APL mode + + + + + + + + +

CodeMirror: 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)

+ + diff --git a/lib/codemirror-3.1/mode/asterisk/asterisk.js b/lib/codemirror-3.1/mode/asterisk/asterisk.js new file mode 100644 index 0000000000000000000000000000000000000000..d491857e925643d4b0b73429ba83da7aed621f9f --- /dev/null +++ b/lib/codemirror-3.1/mode/asterisk/asterisk.js @@ -0,0 +1,183 @@ +/* + * ===================================================================================== + * + * 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. + * + * ===================================================================================== + */ + +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 = ''; + 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 = ''; + var ch = ''; + 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; + ch = 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"); diff --git a/lib/codemirror-3.1/mode/asterisk/index.html b/lib/codemirror-3.1/mode/asterisk/index.html new file mode 100644 index 0000000000000000000000000000000000000000..0a796a0119bd1da3501685bfa05e05c72f896c6e --- /dev/null +++ b/lib/codemirror-3.1/mode/asterisk/index.html @@ -0,0 +1,142 @@ + + + + + CodeMirror: Asterisk dialplan mode + + + + + + + +

CodeMirror: Asterisk dialplan mode

+
+ + +

MIME types defined: text/x-asterisk.

+ + + diff --git a/lib/codemirror-3.1/mode/clike/clike.js b/lib/codemirror-3.1/mode/clike/clike.js new file mode 100644 index 0000000000000000000000000000000000000000..1b350aeb8c23e229c012f55853cfbbffa99e0f4e --- /dev/null +++ b/lib/codemirror-3.1/mode/clike/clike.js @@ -0,0 +1,302 @@ +CodeMirror.defineMode("clike", function(config, parserConfig) { + var indentUnit = config.indentUnit, + statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, + dontAlignCalls = parserConfig.dontAlignCalls, + 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 == "'") { + 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(); + 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 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 (dontAlignCalls && ctx.type == ")" && !closing) return ctx.indented + statementIndentUnit; + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indented + (closing ? 0 : indentUnit); + }, + + electricChars: "{}" + }; +}); + +(function() { + function words(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + var cKeywords = "auto if break int case long char register continue return default short do sizeof " + + "double static else struct entry switch extern typedef float union for unsigned " + + "goto while enum void const signed volatile"; + + function cppHook(stream, state) { + if (!state.startOfLine) return false; + for (;;) { + if (stream.skipTo("\\")) { + stream.next(); + if (stream.eol()) { + state.tokenize = cppHook; + break; + } + } else { + stream.skipToEnd(); + state.tokenize = null; + break; + } + } + return "meta"; + } + + // 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"; + } + + function mimes(ms, mode) { + for (var i = 0; i < ms.length; ++i) CodeMirror.defineMIME(ms[i], mode); + } + + mimes(["text/x-csrc", "text/x-c", "text/x-chdr"], { + name: "clike", + keywords: words(cKeywords), + blockKeywords: words("case do else for if switch while struct"), + atoms: words("null"), + hooks: {"#": cppHook} + }); + mimes(["text/x-c++src", "text/x-c++hdr"], { + name: "clike", + keywords: words(cKeywords + " asm dynamic_cast namespace reinterpret_cast try bool explicit new " + + "static_cast typeid catch operator template typename class friend private " + + "this using const_cast inline public throw virtual delete mutable protected " + + "wchar_t"), + blockKeywords: words("catch class do else finally for if struct switch try while"), + atoms: words("true false null"), + hooks: {"#": cppHook} + }); + CodeMirror.defineMIME("text/x-java", { + name: "clike", + keywords: words("abstract assert boolean break byte case catch char class const continue default " + + "do double else enum extends final finally float for goto if implements import " + + "instanceof int interface long native new package private protected public " + + "return short static strictfp super switch synchronized this throw throws transient " + + "try void volatile while"), + blockKeywords: words("catch class do else finally for if switch try while"), + atoms: words("true false null"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + CodeMirror.defineMIME("text/x-csharp", { + name: "clike", + keywords: words("abstract as 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"), + blockKeywords: words("catch class do else finally for foreach if struct switch try while"), + builtin: words("Boolean Byte Char DateTime DateTimeOffset Decimal Double" + + " Guid Int16 Int32 Int64 Object SByte Single String TimeSpan UInt16 UInt32" + + " UInt64 bool byte char decimal double short int long object" + + " sbyte float string ushort uint ulong"), + atoms: words("true false null"), + hooks: { + "@": function(stream, state) { + if (stream.eat('"')) { + state.tokenize = tokenAtString; + return tokenAtString(stream, state); + } + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); + CodeMirror.defineMIME("text/x-scala", { + name: "clike", + keywords: words( + + /* scala */ + "abstract case catch class def do else extends false final finally for forSome if " + + "implicit import lazy match new null object override package private protected return " + + "sealed super this throw trait try trye type val var while with yield _ : = => <- <: " + + "<% >: # @ " + + + /* package scala */ + "assert assume require print println printf readLine readBoolean readByte readShort " + + "readChar readInt readLong readFloat readDouble " + + + "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + + "Enumeration Equiv Error Exception Fractional Function IndexedSeq 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" + + + ), + blockKeywords: words("catch class do else finally for forSome if match switch try while"), + atoms: words("true false null"), + hooks: { + "@": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "meta"; + } + } + }); +}()); diff --git a/lib/codemirror-3.1/mode/clike/index.html b/lib/codemirror-3.1/mode/clike/index.html new file mode 100644 index 0000000000000000000000000000000000000000..5f90394d958f92ef93115a93c39249e718a5b609 --- /dev/null +++ b/lib/codemirror-3.1/mode/clike/index.html @@ -0,0 +1,103 @@ + + + + + CodeMirror: C-like mode + + + + + + + + +

CodeMirror: C-like 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 code), text/x-c++src (C++ + code), text/x-java (Java + code), text/x-csharp (C#).

+ + diff --git a/lib/codemirror-3.1/mode/clike/scala.html b/lib/codemirror-3.1/mode/clike/scala.html new file mode 100644 index 0000000000000000000000000000000000000000..f3c7eea498ab41eae04721d859269d7ec64dc20d --- /dev/null +++ b/lib/codemirror-3.1/mode/clike/scala.html @@ -0,0 +1,767 @@ + + + + + CodeMirror: C-like mode + + + + + + + + + +
+ +
+ + + + diff --git a/lib/codemirror-3.1/mode/clojure/clojure.js b/lib/codemirror-3.1/mode/clojure/clojure.js new file mode 100644 index 0000000000000000000000000000000000000000..5d90edb8a52a98f888455f6b19091c69ed97cb48 --- /dev/null +++ b/lib/codemirror-3.1/mode/clojure/clojure.js @@ -0,0 +1,206 @@ +/** + * Author: Hans Engel + * Branched from CodeMirror's Scheme mode (by Koh Zi Han, based on implementation by Koh Zi Chun) + */ +CodeMirror.defineMode("clojure", function () { + var BUILTIN = "builtin", COMMENT = "comment", STRING = "string", + ATOM = "atom", NUMBER = "number", BRACKET = "bracket", KEYWORD = "keyword"; + 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 atoms = makeKeywords("true false nil"); + + var keywords = makeKeywords( + "defn defn- def def- defonce defmulti defmethod defmacro defstruct deftype defprotocol defrecord defproject deftest slice defalias defhinted defmacro- defn-memo defnk defnk defonce- defunbound defunbound- defvar defvar- let letfn do case cond condp for loop recur when when-not when-let when-first if if-let if-not . .. -> ->> doto and or dosync doseq dotimes dorun doall load import unimport ns in-ns refer try catch finally throw with-open with-local-vars binding gen-class gen-and-load-class gen-and-save-class handler-case handle"); + + var builtins = makeKeywords( + "* *1 *2 *3 *agent* *allow-unresolved-vars* *assert *clojure-version* *command-line-args* *compile-files* *compile-path* *e *err* *file* *flush-on-newline* *in* *macro-meta* *math-context* *ns* *out* *print-dup* *print-length* *print-level* *print-meta* *print-readably* *read-eval* *source-path* *use-context-classloader* *warn-on-reflection* + - / < <= = == > >= accessor aclone agent agent-errors aget alength alias all-ns alter alter-meta! alter-var-root amap ancestors and apply areduce array-map 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 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 booleans bound-fn bound-fn* butlast byte byte-array bytes case cast 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 concat cond condp conj conj! cons constantly construct-proxy contains? count counted? create-ns create-struct cycle dec decimal? declare definline defmacro defmethod defmulti defn defn- defonce defstruct delay delay? deliver deref derive descendants destructure disj disj! dissoc dissoc! distinct distinct? doall doc dorun doseq dosync dotimes doto double double-array doubles drop drop-last drop-while empty empty? ensure enumeration-seq eval even? every? extend extend-protocol extend-type extends? extenders false? ffirst file-seq filter find find-doc find-ns find-var first float float-array float? floats flush fn fn? fnext for force format 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 hash hash-map hash-set identical? identity if-let if-not ifn? import in-ns inc init-proxy instance? int int-array integer? interleave intern interpose into into-array ints io! isa? iterate iterator-seq juxt 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? mapcat max max-key memfn memoize merge merge-with meta method-sig methods min min-key mod name namespace 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 num number? odd? or parents partial partition pcalls peek persistent! pmap pop pop! pop-thread-bindings pos? pr pr-str prefer-method prefers primitives-classnames print print-ctor print-doc print-dup print-method print-namespace-doc print-simple print-special-doc 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 quot rand rand-int range ratio? rational? rationalize re-find re-groups re-matcher re-matches re-pattern re-seq read read-line read-string reify reduce ref ref-history-count ref-max-history ref-min-history ref-set refer refer-clojure release-pending-sends rem remove remove-method remove-ns repeat repeatedly replace replicate require reset! reset-meta! resolve rest resultset-seq reverse reversible? rseq rsubseq satisfies? second select-keys send send-off seq seq? seque sequence sequential? set set-validator! set? short short-array shorts shutdown-agents slurp some sort sort-by sorted-map sorted-map-by sorted-set sorted-set-by sorted? special-form-anchor special-symbol? split-at split-with str stream? string? struct struct-map subs subseq subvec supers swap! symbol symbol? sync syntax-symbol-anchor take take-last take-nth take-while test the-ns time to-array to-array-2d trampoline transient tree-seq true? type unchecked-add unchecked-dec unchecked-divide unchecked-inc unchecked-multiply unchecked-negate unchecked-remainder unchecked-subtract underive unquote unquote-splicing update-in update-proxy use val vals var-get var-set var? vary-meta vec vector vector? when when-first when-let when-not while with-bindings with-bindings* with-in-str with-loading-context with-local-vars with-meta with-open with-out-str with-precision xml-seq"); + + var indentKeys = makeKeywords( + // Built-ins + "ns fn def defn defmethod bound-fn if if-not case condp when while when-not when-first do future comment doto locking proxy with-open with-precision reify deftype defrecord defprotocol extend extend-protocol extend-type try catch " + + + // Binding forms + "let letfn binding loop for doseq dotimes when-let if-let " + + + // Data structures + "defstruct struct-map assoc " + + + // clojure.test + "testing deftest " + + + // contrib + "handler-case handle dotrace deftrace"); + + var tests = { + digit: /\d/, + digit_or_colon: /[\d:]/, + hex: /[0-9a-f]/i, + sign: /[+-]/, + exponent: /e/i, + keyword_char: /[^\s\(\[\;\)\]]/, + basic: /[\w\$_\-]/, + lang_keyword: /[\w*+!\-_?:\/]/ + }; + + 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; + } + + 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 = 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 string mode + break; + default: // default parsing mode + var ch = stream.next(); + + if (ch == "\"") { + state.mode = "string"; + returnType = STRING; + } else if (ch == "'" && !( tests.digit_or_colon.test(stream.peek()) )) { + returnType = ATOM; + } else if (ch == ";") { // comment + stream.skipToEnd(); // rest of the line is a comment + returnType = COMMENT; + } else if (isNumber(ch,stream)){ + returnType = NUMBER; + } else if (ch == "(" || ch == "[" || ch == "{" ) { + var keyWord = '', indentTemp = stream.column(), letter; + /** + Either + (indent-word .. + (non-indent-word .. + (;something else, bracket, etc. + */ + + if (ch == "(") while ((letter = stream.eat(tests.keyword_char)) != null) { + keyWord += letter; + } + + if (keyWord.length > 0 && (indentKeys.propertyIsEnumerable(keyWord) || + /^(?:def|with)/.test(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 + + returnType = BRACKET; + } else if (ch == ")" || ch == "]" || ch == "}") { + returnType = BRACKET; + if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : (ch == "]" ? "[" :"{"))) { + popStack(state); + } + } else if ( ch == ":" ) { + stream.eatWhile(tests.lang_keyword); + return ATOM; + } else { + stream.eatWhile(tests.basic); + + if (keywords && keywords.propertyIsEnumerable(stream.current())) { + returnType = KEYWORD; + } else if (builtins && builtins.propertyIsEnumerable(stream.current())) { + returnType = BUILTIN; + } else if (atoms && atoms.propertyIsEnumerable(stream.current())) { + 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-clojure", "clojure"); diff --git a/lib/codemirror-3.1/mode/clojure/index.html b/lib/codemirror-3.1/mode/clojure/index.html new file mode 100644 index 0000000000000000000000000000000000000000..bce0473530db036d84f2ee1379c6a656a349f3c1 --- /dev/null +++ b/lib/codemirror-3.1/mode/clojure/index.html @@ -0,0 +1,67 @@ + + + + + CodeMirror: Clojure mode + + + + + + + +

CodeMirror: Clojure mode

+
+ + +

MIME types defined: text/x-clojure.

+ + + diff --git a/lib/codemirror-3.1/mode/coffeescript/LICENSE b/lib/codemirror-3.1/mode/coffeescript/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..977e284e0f2bc785c3ec89030af88796b99ed1af --- /dev/null +++ b/lib/codemirror-3.1/mode/coffeescript/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2011 Jeff Pickhardt +Modified from the Python CodeMirror mode, Copyright (c) 2010 Timothy Farrell + +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. \ No newline at end of file diff --git a/lib/codemirror-3.1/mode/coffeescript/coffeescript.js b/lib/codemirror-3.1/mode/coffeescript/coffeescript.js new file mode 100644 index 0000000000000000000000000000000000000000..4d925037cee93424360944e6f55b8d43b4c2ec1b --- /dev/null +++ b/lib/codemirror-3.1/mode/coffeescript/coffeescript.js @@ -0,0 +1,346 @@ +/** + * Link to the project's GitHub page: + * https://github.com/pickhardt/coffeescript-codemirror-mode + */ +CodeMirror.defineMode('coffeescript', function(conf) { + var ERRORCLASS = 'error'; + + 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 identifiers = new RegExp("^[_A-Za-z$][_A-Za-z$0-9]*"); + var properties = new RegExp("^(@|this\.)[_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']; + + var keywords = wordRegexp(indentKeywords.concat(commonKeywords)); + + indentKeywords = wordRegexp(indentKeywords); + + + var stringPrefixes = new RegExp("^('{3}|\"{3}|['\"])"); + var regexPrefixes = new RegExp("^(/{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()) { + var scopeOffset = state.scopes[0].offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) { + 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(), '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(), 'string-2'); + return state.tokenize(stream, state); + } else { + stream.backUp(1); + } + } + + // Handle operators and delimiters + if (stream.match(tripleDelimiters) || stream.match(doubleDelimiters)) { + return 'punctuation'; + } + if (stream.match(doubleOperators) + || stream.match(singleOperators) + || stream.match(wordOperators)) { + return 'operator'; + } + if (stream.match(singleDelimiters)) { + return 'punctuation'; + } + + if (stream.match(constants)) { + return 'atom'; + } + + if (stream.match(keywords)) { + return 'keyword'; + } + + if (stream.match(identifiers)) { + return 'variable'; + } + + if (stream.match(properties)) { + return 'property'; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function tokenFactory(delimiter, outclass) { + var singleline = delimiter.length == 1; + 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 (conf.mode.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 indentUnit = 0; + if (type === 'coffee') { + for (var i = 0; i < state.scopes.length; i++) { + if (state.scopes[i].type === 'coffee') { + indentUnit = state.scopes[i].offset + conf.indentUnit; + break; + } + } + } else { + indentUnit = stream.column() + stream.current().length; + } + state.scopes.unshift({ + offset: indentUnit, + type: type + }); + } + + function dedent(stream, state) { + if (state.scopes.length == 1) return; + if (state.scopes[0].type === 'coffee') { + var _indent = stream.indentation(); + var _indent_index = -1; + for (var i = 0; i < state.scopes.length; ++i) { + if (_indent === state.scopes[i].offset) { + _indent_index = i; + break; + } + } + if (_indent_index === -1) { + return true; + } + while (state.scopes[0].offset !== _indent) { + state.scopes.shift(); + } + return false; + } else { + state.scopes.shift(); + return false; + } + } + + 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 === 'variable') { + return 'variable'; + } else { + return ERRORCLASS; + } + } + + // Handle scope changes. + if (current === 'return') { + state.dedent += 1; + } + if (((current === '->' || current === '=>') && + !state.lambda && + state.scopes[0].type == 'coffee' && + stream.peek() === '') + || 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) { + if (dedent(stream, state)) { + return ERRORCLASS; + } + } + if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'coffee') { + if (state.scopes.length > 1) state.scopes.shift(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset:basecolumn || 0, type:'coffee'}], + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var style = tokenLexer(stream, state); + + state.lastToken = {style:style, content: stream.current()}; + + if (stream.eol() && stream.lambda) { + state.lambda = false; + } + + return style; + }, + + indent: function(state) { + if (state.tokenize != tokenBase) { + return 0; + } + + return state.scopes[0].offset; + } + + }; + return external; +}); + +CodeMirror.defineMIME('text/x-coffeescript', 'coffeescript'); diff --git a/lib/codemirror-3.1/mode/coffeescript/index.html b/lib/codemirror-3.1/mode/coffeescript/index.html new file mode 100644 index 0000000000000000000000000000000000000000..ee72b8d2f22bcb41923d0177fad7d91134f4d6f8 --- /dev/null +++ b/lib/codemirror-3.1/mode/coffeescript/index.html @@ -0,0 +1,728 @@ + + + + + CodeMirror: CoffeeScript mode + + + + + + + +

CodeMirror: CoffeeScript mode

+
+ + +

MIME types defined: text/x-coffeescript.

+ +

The CoffeeScript mode was written by Jeff Pickhardt (license).

+ + + diff --git a/lib/codemirror-3.1/mode/commonlisp/commonlisp.js b/lib/codemirror-3.1/mode/commonlisp/commonlisp.js new file mode 100644 index 0000000000000000000000000000000000000000..eeba759668f3fbc4e605607d16c5babf8d59109d --- /dev/null +++ b/lib/codemirror-3.1/mode/commonlisp/commonlisp.js @@ -0,0 +1,101 @@ +CodeMirror.defineMode("commonlisp", function (config) { + 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 return "error"; + } else { + var name = readSym(stream); + if (name == ".") return null; + type = "symbol"; + if (name == "nil" || name == "t") return "atom"; + if (name.charAt(0) == ":") 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}, 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(); + } + } + 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; + } + }; +}); + +CodeMirror.defineMIME("text/x-common-lisp", "commonlisp"); diff --git a/lib/codemirror-3.1/mode/commonlisp/index.html b/lib/codemirror-3.1/mode/commonlisp/index.html new file mode 100644 index 0000000000000000000000000000000000000000..f9766a844ce5948e91966c5f13346533f8632134 --- /dev/null +++ b/lib/codemirror-3.1/mode/commonlisp/index.html @@ -0,0 +1,165 @@ + + + + + CodeMirror: Common Lisp mode + + + + + + + +

CodeMirror: Common Lisp mode

+
+ + +

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

+ + + diff --git a/lib/codemirror-3.1/mode/css/css.js b/lib/codemirror-3.1/mode/css/css.js new file mode 100644 index 0000000000000000000000000000000000000000..37ef76c941eeccd9054c81e42e9f4a56b03addcb --- /dev/null +++ b/lib/codemirror-3.1/mode/css/css.js @@ -0,0 +1,465 @@ +CodeMirror.defineMode("css", function(config) { + var indentUnit = config.indentUnit, type; + + var atMediaTypes = keySet([ + "all", "aural", "braille", "handheld", "print", "projection", "screen", + "tty", "tv", "embossed" + ]); + + var atMediaFeatures = keySet([ + "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 = keySet([ + "align-content", "align-items", "align-self", "alignment-adjust", + "alignment-baseline", "anchor-point", "animation", "animation-delay", + "animation-direction", "animation-duration", "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", "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-cell", "grid-column", "grid-column-align", + "grid-column-sizing", "grid-column-span", "grid-columns", "grid-flow", + "grid-row", "grid-row-align", "grid-row-sizing", "grid-row-span", + "grid-rows", "grid-template", "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", "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", "rendering-intent", + "resize", "rest", "rest-after", "rest-before", "richness", "right", + "rotation", "rotation-point", "ruby-align", "ruby-overhang", + "ruby-position", "ruby-span", "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-shadow", + "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", "word-break", + "word-spacing", "word-wrap", "z-index" + ]); + + var colorKeywords = keySet([ + "black", "silver", "gray", "white", "maroon", "red", "purple", "fuchsia", + "green", "lime", "olive", "yellow", "navy", "blue", "teal", "aqua" + ]); + + var valueKeywords = keySet([ + "above", "absolute", "activeborder", "activecaption", "afar", + "after-white-space", "ahead", "alias", "all", "all-scroll", "alternate", + "always", "amharic", "amharic-abegede", "antialiased", "appworkspace", + "arabic-indic", "armenian", "asterisks", "auto", "avoid", "background", + "backwards", "baseline", "below", "bidi-override", "binary", "bengali", + "blink", "block", "block-axis", "bold", "bolder", "border", "border-box", + "both", "bottom", "break-all", "break-word", "button", "button-bevel", + "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "cambodian", + "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret", + "cell", "center", "checkbox", "circle", "cjk-earthly-branch", + "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote", + "col-resize", "collapse", "compact", "condensed", "contain", "content", + "content-box", "context-menu", "continuous", "copy", "cover", "crop", + "cross", "crosshair", "currentcolor", "cursive", "dashed", "decimal", + "decimal-leading-zero", "default", "default-button", "destination-atop", + "destination-in", "destination-out", "destination-over", "devanagari", + "disc", "discard", "document", "dot-dash", "dot-dot-dash", "dotted", + "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out", + "element", "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", "ew-resize", "expanded", "extra-condensed", + "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "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-table", "inset", "inside", "intrinsic", "invert", + "italic", "justify", "kannada", "katakana", "katakana-iroha", "khmer", + "landscape", "lao", "large", "larger", "left", "level", "lighter", + "line-through", "linear", "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", + "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", "navy", "ne-resize", "nesw-resize", "no-close-quote", "no-drop", + "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap", + "ns-resize", "nw-resize", "nwse-resize", "oblique", "octal", "open-quote", + "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset", + "outside", "overlay", "overline", "padding", "padding-box", "painted", + "paused", "persian", "plus-darker", "plus-lighter", "pointer", "portrait", + "pre", "pre-line", "pre-wrap", "preserve-3d", "progress", "push-button", + "radio", "read-only", "read-write", "read-write-plaintext-only", "relative", + "repeat", "repeat-x", "repeat-y", "reset", "reverse", "rgb", "rgba", + "ridge", "right", "round", "row-resize", "rtl", "run-in", "running", + "s-resize", "sans-serif", "scroll", "scrollbar", "se-resize", "searchfield", + "searchfield-cancel-button", "searchfield-decoration", + "searchfield-results-button", "searchfield-results-decoration", + "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama", + "single", "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", "square", + "square-button", "start", "static", "status-bar", "stretch", "stroke", + "sub", "subpixel-antialiased", "super", "sw-resize", "table", + "table-caption", "table-cell", "table-column", "table-column-group", + "table-footer-group", "table-header-group", "table-row", "table-row-group", + "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", + "transparent", "ultra-condensed", "ultra-expanded", "underline", "up", + "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal", + "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url", + "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted", + "visibleStroke", "visual", "w-resize", "wait", "wave", "white", "wider", + "window", "windowframe", "windowtext", "x-large", "x-small", "xor", + "xx-large", "xx-small", "yellow" + ]); + + function keySet(array) { var keys = {}; for (var i = 0; i < array.length; ++i) keys[array[i]] = true; return keys; } + function ret(style, tp) {type = tp; return style;} + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == "@") {stream.eatWhile(/[\w\\\-]/); return ret("def", 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.eatWhile(/[\w\\\-]/); + return ret("atom", "hash"); + } + 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 (ch === "-") { + if (/\d/.test(stream.peek())) { + stream.eatWhile(/[\w.%]/); + return ret("number", "unit"); + } else if (stream.match(/^[^-]+-/)) { + 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 (ch == ":") { + return ret("operator", ch); + } + else if (/[;{}\[\]\(\)]/.test(ch)) { + return ret(null, ch); + } + else if (ch == "u" && stream.match("rl(")) { + stream.backUp(1); + state.tokenize = tokenParenthesized; + return ret("property", "variable"); + } + else { + stream.eatWhile(/[\w\\\-]/); + return ret("property", "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, nonInclusive) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) + break; + escaped = !escaped && ch == "\\"; + } + if (!escaped) { + if (nonInclusive) stream.backUp(1); + state.tokenize = tokenBase; + } + return ret("string", "string"); + }; + } + + function tokenParenthesized(stream, state) { + stream.next(); // Must be '(' + if (!stream.match(/\s*[\"\']/, false)) + state.tokenize = tokenString(")", true); + else + state.tokenize = tokenBase; + return ret(null, "("); + } + + return { + startState: function(base) { + return {tokenize: tokenBase, + baseIndent: base || 0, + stack: []}; + }, + + token: function(stream, state) { + + // Use these terms when applicable (see http://www.xanthir.com/blog/b4E50) + // + // rule** or **ruleset: + // A selector + braces combo, or an at-rule. + // + // declaration block: + // A sequence of declarations. + // + // declaration: + // A property + colon + value combo. + // + // property value: + // The entire value of a property. + // + // component value: + // A single piece of a property value. Like the 5px in + // text-shadow: 0 0 5px blue;. Can also refer to things that are + // multiple terms, like the 1-4 terms that make up the background-size + // portion of the background shorthand. + // + // term: + // The basic unit of author-facing CSS, like a single number (5), + // dimension (5px), string ("foo"), or function. Officially defined + // by the CSS 2.1 grammar (look for the 'term' production) + // + // + // simple selector: + // A single atomic selector, like a type selector, an attr selector, a + // class selector, etc. + // + // compound selector: + // One or more simple selectors without a combinator. div.example is + // compound, div > .example is not. + // + // complex selector: + // One or more compound selectors chained with combinators. + // + // combinator: + // The parts of selectors that express relationships. There are four + // currently - the space (descendant combinator), the greater-than + // bracket (child combinator), the plus sign (next sibling combinator), + // and the tilda (following sibling combinator). + // + // sequence of selectors: + // One or more of the named type of selector chained with commas. + + if (state.tokenize == tokenBase && stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + + // Changing style returned based on context + var context = state.stack[state.stack.length-1]; + if (style == "property") { + if (context == "propertyValue"){ + if (valueKeywords[stream.current()]) { + style = "string-2"; + } else if (colorKeywords[stream.current()]) { + style = "keyword"; + } else { + style = "variable-2"; + } + } else if (context == "rule") { + if (!propertyKeywords[stream.current()]) { + style += " error"; + } + } else if (!context || context == "@media{") { + style = "tag"; + } else if (context == "@media") { + if (atMediaTypes[stream.current()]) { + style = "attribute"; // Known attribute + } else if (/^(only|not)$/i.test(stream.current())) { + style = "keyword"; + } else if (stream.current().toLowerCase() == "and") { + style = "error"; // "and" is only allowed in @mediaType + } else if (atMediaFeatures[stream.current()]) { + style = "error"; // Known property, should be in @mediaType( + } else { + // Unknown, expecting keyword or attribute, assuming attribute + style = "attribute error"; + } + } else if (context == "@mediaType") { + if (atMediaTypes[stream.current()]) { + style = "attribute"; + } else if (stream.current().toLowerCase() == "and") { + style = "operator"; + } else if (/^(only|not)$/i.test(stream.current())) { + style = "error"; // Only allowed in @media + } else if (atMediaFeatures[stream.current()]) { + style = "error"; // Known property, should be in parentheses + } else { + // Unknown attribute or property, but expecting property (preceded + // by "and"). Should be in parentheses + style = "error"; + } + } else if (context == "@mediaType(") { + if (propertyKeywords[stream.current()]) { + // do nothing, remains "property" + } else if (atMediaTypes[stream.current()]) { + style = "error"; // Known property, should be in parentheses + } else if (stream.current().toLowerCase() == "and") { + style = "operator"; + } else if (/^(only|not)$/i.test(stream.current())) { + style = "error"; // Only allowed in @media + } else { + style += " error"; + } + } else { + style = "error"; + } + } else if (style == "atom") { + if(!context || context == "@media{") { + style = "builtin"; + } else if (context == "propertyValue") { + if (!/^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/.test(stream.current())) { + style += " error"; + } + } else { + style = "error"; + } + } else if (context == "@media" && type == "{") { + style = "error"; + } + + // Push/pop context stack + if (type == "{") { + if (context == "@media" || context == "@mediaType") { + state.stack.pop(); + state.stack[state.stack.length-1] = "@media{"; + } + else state.stack.push("rule"); + } + else if (type == "}") { + state.stack.pop(); + if (context == "propertyValue") state.stack.pop(); + } + else if (type == "@media") state.stack.push("@media"); + else if (context == "@media" && /\b(keyword|attribute)\b/.test(style)) + state.stack.push("@mediaType"); + else if (context == "@mediaType" && stream.current() == ",") state.stack.pop(); + else if (context == "@mediaType" && type == "(") state.stack.push("@mediaType("); + else if (context == "@mediaType(" && type == ")") state.stack.pop(); + else if (context == "rule" && type == ":") state.stack.push("propertyValue"); + else if (context == "propertyValue" && type == ";") state.stack.pop(); + return style; + }, + + indent: function(state, textAfter) { + var n = state.stack.length; + if (/^\}/.test(textAfter)) + n -= state.stack[state.stack.length-1] == "propertyValue" ? 2 : 1; + return state.baseIndent + n * indentUnit; + }, + + electricChars: "}" + }; +}); + +CodeMirror.defineMIME("text/css", "css"); diff --git a/lib/codemirror-3.1/mode/css/index.html b/lib/codemirror-3.1/mode/css/index.html new file mode 100644 index 0000000000000000000000000000000000000000..ae2c3bfcee37e8021ea405c814cbea0a45495981 --- /dev/null +++ b/lib/codemirror-3.1/mode/css/index.html @@ -0,0 +1,58 @@ + + + + + CodeMirror: CSS mode + + + + + + + +

CodeMirror: CSS mode

+
+ + +

MIME types defined: text/css.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/lib/codemirror-3.1/mode/css/test.js b/lib/codemirror-3.1/mode/css/test.js new file mode 100644 index 0000000000000000000000000000000000000000..4336ddabdf7d5091e7efd6779f094860aa37dfbd --- /dev/null +++ b/lib/codemirror-3.1/mode/css/test.js @@ -0,0 +1,106 @@ +(function() { + var mode = CodeMirror.getMode({tabSize: 4}, "css"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 2)); } + + // Requires at least one media query + MT("atMediaEmpty", + "[def @media] [error {] }"); + + MT("atMediaMultiple", + "[def @media] [keyword not] [attribute screen] [operator and] ([property color]), [keyword not] [attribute print] [operator and] ([property color]) { }"); + + MT("atMediaCheckStack", + "[def @media] [attribute screen] { } [tag foo] { }"); + + MT("atMediaCheckStack", + "[def @media] [attribute screen] ([property color]) { } [tag foo] { }"); + + MT("atMediaCheckStackInvalidAttribute", + "[def @media] [attribute&error foobarhello] { } [tag foo] { }"); + + // Error, because "and" is only allowed immediately preceding a media expression + MT("atMediaInvalidAttribute", + "[def @media] [attribute&error foobarhello] { }"); + + // Error, because "and" is only allowed immediately preceding a media expression + MT("atMediaInvalidAnd", + "[def @media] [error and] [attribute screen] { }"); + + // Error, because "not" is only allowed as the first item in each media query + MT("atMediaInvalidNot", + "[def @media] [attribute screen] [error not] ([error not]) { }"); + + // Error, because "only" is only allowed as the first item in each media query + MT("atMediaInvalidOnly", + "[def @media] [attribute screen] [error only] ([error only]) { }"); + + // Error, because "foobarhello" is neither a known type or property, but + // property was expected (after "and"), and it should be in parenthese. + MT("atMediaUnknownType", + "[def @media] [attribute screen] [operator and] [error foobarhello] { }"); + + // Error, because "color" is not a known type, but is a known property, and + // should be in parentheses. + MT("atMediaInvalidType", + "[def @media] [attribute screen] [operator and] [error color] { }"); + + // Error, because "print" is not a known property, but is a known type, + // and should not be in parenthese. + MT("atMediaInvalidProperty", + "[def @media] [attribute screen] [operator and] ([error print]) { }"); + + // Soft error, because "foobarhello" is not a known property or type. + MT("atMediaUnknownProperty", + "[def @media] [attribute screen] [operator and] ([property&error foobarhello]) { }"); + + MT("tagSelector", + "[tag foo] { }"); + + MT("classSelector", + "[qualifier .foo-bar_hello] { }"); + + MT("idSelector", + "[builtin #foo] { [error #foo] }"); + + MT("tagSelectorUnclosed", + "[tag foo] { [property margin][operator :] [number 0] } [tag bar] { }"); + + MT("tagStringNoQuotes", + "[tag foo] { [property font-family][operator :] [variable-2 hello] [variable-2 world]; }"); + + MT("tagStringDouble", + "[tag foo] { [property font-family][operator :] [string \"hello world\"]; }"); + + MT("tagStringSingle", + "[tag foo] { [property font-family][operator :] [string 'hello world']; }"); + + MT("tagColorKeyword", + "[tag foo] { [property color][operator :] [keyword black]; }"); + + MT("tagColorHex3", + "[tag foo] { [property background][operator :] [atom #fff]; }"); + + MT("tagColorHex6", + "[tag foo] { [property background][operator :] [atom #ffffff]; }"); + + MT("tagColorHex4", + "[tag foo] { [property background][operator :] [atom&error #ffff]; }"); + + MT("tagColorHexInvalid", + "[tag foo] { [property background][operator :] [atom&error #ffg]; }"); + + MT("tagNegativeNumber", + "[tag foo] { [property margin][operator :] [number -5px]; }"); + + MT("tagPositiveNumber", + "[tag foo] { [property padding][operator :] [number 5px]; }"); + + MT("tagVendor", + "[tag foo] { [meta -foo-][property box-sizing][operator :] [meta -foo-][string-2 border-box]; }"); + + MT("tagBogusProperty", + "[tag foo] { [property&error barhelloworld][operator :] [number 0]; }"); + + MT("tagTwoProperties", + "[tag foo] { [property margin][operator :] [number 0]; [property padding][operator :] [number 0]; }"); +})(); diff --git a/lib/codemirror-3.1/mode/d/d.js b/lib/codemirror-3.1/mode/d/d.js new file mode 100644 index 0000000000000000000000000000000000000000..ab345f1a0d9947e1db94a4f8fc4c1d4d832eaed7 --- /dev/null +++ b/lib/codemirror-3.1/mode/d/d.js @@ -0,0 +1,205 @@ +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 = tokenComment; + 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\$_]/); + 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: "{}" + }; +}); + +(function() { + 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"; + } + } + }); +}()); diff --git a/lib/codemirror-3.1/mode/d/index.html b/lib/codemirror-3.1/mode/d/index.html new file mode 100644 index 0000000000000000000000000000000000000000..13332727ad6185a642c6b56b284dc5a84f22dbe2 --- /dev/null +++ b/lib/codemirror-3.1/mode/d/index.html @@ -0,0 +1,262 @@ + + + + + CodeMirror: D mode + + + + + + + + +

CodeMirror: D mode

+ +
+ + + +

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

+ +

MIME types defined: text/x-d + .

+ + diff --git a/lib/codemirror-3.1/mode/diff/diff.js b/lib/codemirror-3.1/mode/diff/diff.js new file mode 100644 index 0000000000000000000000000000000000000000..9a0d90ea55da8c4edf4c364ced87a4d5cb4fcae9 --- /dev/null +++ b/lib/codemirror-3.1/mode/diff/diff.js @@ -0,0 +1,32 @@ +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"); diff --git a/lib/codemirror-3.1/mode/diff/index.html b/lib/codemirror-3.1/mode/diff/index.html new file mode 100644 index 0000000000000000000000000000000000000000..556025204df0c99f5ca3ba54622d2cb9ea5c2fa0 --- /dev/null +++ b/lib/codemirror-3.1/mode/diff/index.html @@ -0,0 +1,105 @@ + + + + + CodeMirror: Diff mode + + + + + + + +

CodeMirror: Diff mode

+
+ + +

MIME types defined: text/x-diff.

+ + + diff --git a/lib/codemirror-3.1/mode/ecl/ecl.js b/lib/codemirror-3.1/mode/ecl/ecl.js new file mode 100644 index 0000000000000000000000000000000000000000..3ee7a681de40a1cb685e43ce657e16a3328f7b3c --- /dev/null +++ b/lib/codemirror-3.1/mode/ecl/ecl.js @@ -0,0 +1,192 @@ +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 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 == "'") { + 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 || 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) { + 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"); diff --git a/lib/codemirror-3.1/mode/ecl/index.html b/lib/codemirror-3.1/mode/ecl/index.html new file mode 100644 index 0000000000000000000000000000000000000000..0ba88c39956320ff384b6da6bb26b1181d0fe2e5 --- /dev/null +++ b/lib/codemirror-3.1/mode/ecl/index.html @@ -0,0 +1,39 @@ + + + + CodeMirror: ECL mode + + + + + + + +

CodeMirror: ECL mode

+
+ + +

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

+

MIME types defined: text/x-ecl.

+ + + diff --git a/lib/codemirror-3.1/mode/erlang/erlang.js b/lib/codemirror-3.1/mode/erlang/erlang.js new file mode 100644 index 0000000000000000000000000000000000000000..accf24e6703443aeb345b758759374857030d7b6 --- /dev/null +++ b/lib/codemirror-3.1/mode/erlang/erlang.js @@ -0,0 +1,463 @@ +// block; "begin", "case", "fun", "if", "receive", "try": closed by "end" +// block internal; "after", "catch", "of" +// guard; "when", closed by "->" +// "->" opens a clause, closed by ";" or "." +// "<<" opens a binary, closed by ">>" +// "," appears in arglists, lists, tuples and terminates lines of code +// "." resets indentation to 0 +// obsolete; "cond", "let", "query" + +CodeMirror.defineMIME("text/x-erlang", "erlang"); + +CodeMirror.defineMode("erlang", function(cmCfg) { + + function rval(state,stream,type) { + // distinguish between "." as terminator and record field operator + if (type == "record") { + state.context = "record"; + }else{ + state.context = false; + } + + // remember last significant bit on last line for indenting + if (type != "whitespace" && type != "comment") { + state.lastToken = stream.current(); + } + // erlang -> CodeMirror tag + switch (type) { + case "atom": return "atom"; + case "attribute": return "attribute"; + case "builtin": return "builtin"; + case "comment": return "comment"; + 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 "operator": return "operator"; + case "record": return "bracket"; + case "string": return "string"; + case "type": return "def"; + case "variable": return "variable"; + case "error": return "error"; + case "separator": return null; + case "open_paren": return null; + case "close_paren": return null; + default: return null; + } + } + + var typeWords = [ + "-type", "-spec", "-export_type", "-opaque"]; + + var keywordWords = [ + "after","begin","catch","case","cond","end","fun","if", + "let","of","query","receive","try","when"]; + + var separatorWords = [ + "->",";",":",".",","]; + + var operatorWords = [ + "and","andalso","band","bnot","bor","bsl","bsr","bxor", + "div","not","or","orelse","rem","xor"]; + + var symbolWords = [ + "+","-","*","/",">",">=","<","=<","=:=","==","=/=","/=","||","<-"]; + + var openParenWords = [ + "<<","(","[","{"]; + + 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"]; + + // ignored for indenting purposes + var ignoreWords = [ + ",", ":", "catch", "after", "of", "cond", "let", "query"]; + + + var smallRE = /[a-z_]/; + var largeRE = /[A-Z_]/; + var digitRE = /[0-9]/; + var octitRE = /[0-7]/; + var anumRE = /[a-z_A-Z0-9]/; + var symbolRE = /[\+\-\*\/<>=\|:]/; + var openParenRE = /[<\(\[\{]/; + var closeParenRE = /[>\)\]\}]/; + var sepRE = /[\->\.,:;]/; + + function isMember(element,list) { + return (-1 < list.indexOf(element)); + } + + function isPrev(stream,string) { + var start = stream.start; + var len = string.length; + if (len <= start) { + var word = stream.string.slice(start-len,start); + return word == string; + }else{ + return false; + } + } + + function tokenize(stream, state) { + if (stream.eatSpace()) { + return rval(state,stream,"whitespace"); + } + + // attributes and type specs + if ((peekToken(state).token == "" || peekToken(state).token == ".") && + stream.peek() == '-') { + stream.next(); + if (stream.eat(smallRE) && stream.eatWhile(anumRE)) { + if (isMember(stream.current(),typeWords)) { + return rval(state,stream,"type"); + }else{ + return rval(state,stream,"attribute"); + } + } + stream.backUp(1); + } + + var ch = stream.next(); + + // comment + if (ch == '%') { + stream.skipToEnd(); + return rval(state,stream,"comment"); + } + + // macro + if (ch == '?') { + stream.eatWhile(anumRE); + return rval(state,stream,"macro"); + } + + // record + if ( ch == "#") { + stream.eatWhile(anumRE); + return rval(state,stream,"record"); + } + + // char + if ( ch == "$") { + if (stream.next() == "\\") { + if (!stream.eatWhile(octitRE)) { + stream.next(); + } + } + return rval(state,stream,"string"); + } + + // quoted atom + if (ch == '\'') { + if (singleQuote(stream)) { + return rval(state,stream,"atom"); + }else{ + return rval(state,stream,"error"); + } + } + + // string + if (ch == '"') { + if (doubleQuote(stream)) { + return rval(state,stream,"string"); + }else{ + return rval(state,stream,"error"); + } + } + + // variable + if (largeRE.test(ch)) { + stream.eatWhile(anumRE); + return rval(state,stream,"variable"); + } + + // atom/keyword/BIF/function + if (smallRE.test(ch)) { + stream.eatWhile(anumRE); + + if (stream.peek() == "/") { + stream.next(); + if (stream.eatWhile(digitRE)) { + return rval(state,stream,"fun"); // f/0 style fun + }else{ + stream.backUp(1); + return rval(state,stream,"atom"); + } + } + + var w = stream.current(); + + if (isMember(w,keywordWords)) { + pushToken(state,stream); + return rval(state,stream,"keyword"); + } + if (stream.peek() == "(") { + // 'put' and 'erlang:put' are bifs, 'foo:put' is not + if (isMember(w,bifWords) && + (!isPrev(stream,":") || isPrev(stream,"erlang:"))) { + return rval(state,stream,"builtin"); + }else{ + return rval(state,stream,"function"); + } + } + if (isMember(w,guardWords)) { + return rval(state,stream,"guard"); + } + if (isMember(w,operatorWords)) { + return rval(state,stream,"operator"); + } + if (stream.peek() == ":") { + if (w == "erlang") { + return rval(state,stream,"builtin"); + } else { + return rval(state,stream,"function"); + } + } + return rval(state,stream,"atom"); + } + + // number + if (digitRE.test(ch)) { + stream.eatWhile(digitRE); + if (stream.eat('#')) { + stream.eatWhile(digitRE); // 16#10 style integer + } else { + if (stream.eat('.')) { // float + stream.eatWhile(digitRE); + } + if (stream.eat(/[eE]/)) { + stream.eat(/[-+]/); // float with exponent + stream.eatWhile(digitRE); + } + } + return rval(state,stream,"number"); // normal integer + } + + // open parens + if (nongreedy(stream,openParenRE,openParenWords)) { + pushToken(state,stream); + return rval(state,stream,"open_paren"); + } + + // close parens + if (nongreedy(stream,closeParenRE,closeParenWords)) { + pushToken(state,stream); + return rval(state,stream,"close_paren"); + } + + // separators + if (greedy(stream,sepRE,separatorWords)) { + // distinguish between "." as terminator and record field operator + if (state.context == false) { + pushToken(state,stream); + } + return rval(state,stream,"separator"); + } + + // operators + if (greedy(stream,symbolRE,symbolWords)) { + return rval(state,stream,"operator"); + } + + return rval(state,stream,null); + } + + 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 (isMember(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 (isMember(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 Token(stream) { + this.token = stream ? stream.current() : ""; + this.column = stream ? stream.column() : 0; + this.indent = stream ? stream.indentation() : 0; + } + + function myIndent(state,textAfter) { + var indent = cmCfg.indentUnit; + var outdentWords = ["after","catch"]; + var token = (peekToken(state)).token; + var wordAfter = takewhile(textAfter,/[^a-z]/); + + if (isMember(token,openParenWords)) { + return (peekToken(state)).column+token.length; + }else if (token == "." || token == ""){ + return 0; + }else if (token == "->") { + if (wordAfter == "end") { + return peekToken(state,2).column; + }else if (peekToken(state,2).token == "fun") { + return peekToken(state,2).column+indent; + }else{ + return (peekToken(state)).indent+indent; + } + }else if (isMember(wordAfter,outdentWords)) { + return (peekToken(state)).indent; + }else{ + return (peekToken(state)).column+indent; + } + } + + function takewhile(str,re) { + var m = str.match(re); + return m ? str.slice(0,m.index) : str; + } + + function popToken(state) { + return state.tokenStack.pop(); + } + + function peekToken(state,depth) { + var len = state.tokenStack.length; + var dep = (depth ? depth : 1); + if (len < dep) { + return new Token; + }else{ + return state.tokenStack[len-dep]; + } + } + + function pushToken(state,stream) { + var token = stream.current(); + var prev_token = peekToken(state).token; + if (isMember(token,ignoreWords)) { + return false; + }else if (drop_both(prev_token,token)) { + popToken(state); + return false; + }else if (drop_first(prev_token,token)) { + popToken(state); + return pushToken(state,stream); + }else{ + state.tokenStack.push(new Token(stream)); + return true; + } + } + + function drop_first(open, close) { + switch (open+" "+close) { + case "when ->": return true; + case "-> end": return true; + case "-> .": return true; + case ". .": return true; + default: return false; + } + } + + function drop_both(open, close) { + switch (open+" "+close) { + case "( )": return true; + case "[ ]": return true; + case "{ }": return true; + case "<< >>": return true; + case "begin end": return true; + case "case end": return true; + case "fun end": return true; + case "if end": return true; + case "receive end": return true; + case "try end": return true; + case "-> ;": return true; + default: return false; + } + } + + return { + startState: + function() { + return {tokenStack: [], + context: false, + lastToken: null}; + }, + + token: + function(stream, state) { + return tokenize(stream, state); + }, + + indent: + function(state, textAfter) { +// console.log(state.tokenStack); + return myIndent(state,textAfter); + } + }; +}); diff --git a/lib/codemirror-3.1/mode/erlang/index.html b/lib/codemirror-3.1/mode/erlang/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fd21521c88b43ab50071b1b92b3d8efb69028cc9 --- /dev/null +++ b/lib/codemirror-3.1/mode/erlang/index.html @@ -0,0 +1,64 @@ + + + + + CodeMirror: Erlang mode + + + + + + + + + +

CodeMirror: Erlang mode

+ +
+ + + +

MIME types defined: text/x-erlang.

+ + diff --git a/lib/codemirror-3.1/mode/gfm/gfm.js b/lib/codemirror-3.1/mode/gfm/gfm.js new file mode 100644 index 0000000000000000000000000000000000000000..1aec9f8c4335ead2c32b71470a5e72d8416c8628 --- /dev/null +++ b/lib/codemirror-3.1/mode/gfm/gfm.js @@ -0,0 +1,95 @@ +CodeMirror.defineMode("gfm", function(config) { + 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) { + // 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(stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+@)?(?:[a-f0-9]{7,40}\b)/)) { + // User/Project@SHA + // User@SHA + // SHA + return "link"; + } else if (stream.match(/^(?:[a-zA-Z0-9\-_]+\/)?(?:[a-zA-Z0-9\-_]+)?#[0-9]+\b/)) { + // User/Project#Num + // User#Num + // #Num + return "link"; + } + } + if (stream.match(/^((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\([^\s()<>]*\))+(?:\([^\s()<>]*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)) { + // 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 + return "link"; + } + stream.next(); + return null; + }, + blankLine: blankLine + }; + CodeMirror.defineMIME("gfmBase", { + name: "markdown", + underscoresBreakWords: false, + fencedCodeBlocks: true + }); + return CodeMirror.overlayMode(CodeMirror.getMode(config, "gfmBase"), gfmOverlay); +}, "markdown"); diff --git a/lib/codemirror-3.1/mode/gfm/index.html b/lib/codemirror-3.1/mode/gfm/index.html new file mode 100644 index 0000000000000000000000000000000000000000..f413db19efc27434062557d343e11be097edb7e9 --- /dev/null +++ b/lib/codemirror-3.1/mode/gfm/index.html @@ -0,0 +1,69 @@ + + + + + CodeMirror: GFM mode + + + + + + + + + + + + + + + + + +

CodeMirror: GFM mode

+ +
+ + + +

Optionally depends on other modes for properly highlighted code blocks.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/lib/codemirror-3.1/mode/gfm/test.js b/lib/codemirror-3.1/mode/gfm/test.js new file mode 100644 index 0000000000000000000000000000000000000000..cf97df66a571f2138894fd396b0f1d79d1736de6 --- /dev/null +++ b/lib/codemirror-3.1/mode/gfm/test.js @@ -0,0 +1,84 @@ +(function() { + var mode = CodeMirror.getMode({tabSize: 4}, "gfm"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("emInWordAsterisk", + "foo[em *bar*]hello"); + + MT("emInWordUnderscore", + "foo_bar_hello"); + + MT("emStrongUnderscore", + "[strong __][emstrong _foo__][em _] bar"); + + MT("fencedCodeBlocks", + "[comment ```]", + "[comment foo]", + "", + "[comment ```]", + "bar"); + + MT("fencedCodeBlockModeSwitching", + "[comment ```javascript]", + "[variable foo]", + "", + "[comment ```]", + "bar"); + + MT("SHA", + "foo [link be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] bar"); + + 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("userProjectSHA", + "foo [link bar/hello@be6a8cc1c1ecfe9489fb51e4869af15a13fc2cd2] world"); + + MT("num", + "foo [link #1] bar"); + + MT("badNum", + "foo #1bar hello"); + + MT("userNum", + "foo [link bar#1] hello"); + + MT("userProjectNum", + "foo [link bar/hello#1] world"); + + MT("vanillaLink", + "foo [link http://www.example.com/] bar"); + + MT("vanillaLinkPunctuation", + "foo [link http://www.example.com/]. bar"); + + MT("vanillaLinkExtension", + "foo [link http://www.example.com/index.html] bar"); + + MT("notALink", + "[comment ```css]", + "[tag foo] {[property color][operator :][keyword black];}", + "[comment ```][link http://www.example.com/]"); + + MT("notALink", + "[comment ``foo `bar` http://www.example.com/``] hello"); + + MT("notALink", + "[comment `foo]", + "[link http://www.example.com/]", + "[comment `foo]", + "", + "[link http://www.example.com/]"); +})(); diff --git a/lib/codemirror-3.1/mode/go/go.js b/lib/codemirror-3.1/mode/go/go.js new file mode 100644 index 0000000000000000000000000000000000000000..8b84a5ca42def13bf909dca6bb5553c7539b987e --- /dev/null +++ b/lib/codemirror-3.1/mode/go/go.js @@ -0,0 +1,165 @@ +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 + }; + + var atoms = { + "true":true, "false":true, "iota":true, "nil":true, "append":true, + "cap":true, "close":true, "complex":true, "copy":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\$_]/); + 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 && 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) { + 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 == "}") ctx = 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 0; + 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: "{}:" + }; +}); + +CodeMirror.defineMIME("text/x-go", "go"); diff --git a/lib/codemirror-3.1/mode/go/index.html b/lib/codemirror-3.1/mode/go/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8a6aafca29de358e10ae2c6c16057098ff97e7a1 --- /dev/null +++ b/lib/codemirror-3.1/mode/go/index.html @@ -0,0 +1,74 @@ + + + + + CodeMirror: Go mode + + + + + + + + + +

CodeMirror: Go mode

+ +
+ + + +

MIME type: text/x-go

+ + diff --git a/lib/codemirror-3.1/mode/groovy/groovy.js b/lib/codemirror-3.1/mode/groovy/groovy.js new file mode 100644 index 0000000000000000000000000000000000000000..92b948192efff6629365078b33eafa67ea4ae491 --- /dev/null +++ b/lib/codemirror-3.1/mode/groovy/groovy.js @@ -0,0 +1,210 @@ +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 transient " + + "try void volatile while"); + var blockKeywords = words("catch class do else finally for if switch try while enum interface def"); + 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)) { + 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"; + 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) { + return !last || last == "operator" || last == "->" || /[\.\[\{\(,;:]/.test(last) || + last == "newstatement" || last == "keyword" || last == "proplabel"; + } + + 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)) { + 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 0; + var firstChar = textAfter && textAfter.charAt(0), ctx = state.context; + if (ctx.type == "statement" && !expectExpression(state.lastToken)) 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: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-groovy", "groovy"); diff --git a/lib/codemirror-3.1/mode/groovy/index.html b/lib/codemirror-3.1/mode/groovy/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3d395957749a68c56f894cb0a551a5aa13720e8b --- /dev/null +++ b/lib/codemirror-3.1/mode/groovy/index.html @@ -0,0 +1,73 @@ + + + + + CodeMirror: Groovy mode + + + + + + + + +

CodeMirror: Groovy mode

+ +
+ + + +

MIME types defined: text/x-groovy

+ + diff --git a/lib/codemirror-3.1/mode/haskell/haskell.js b/lib/codemirror-3.1/mode/haskell/haskell.js new file mode 100644 index 0000000000000000000000000000000000000000..71235f4ee934358d87be73ad6125ce72e877fbcd --- /dev/null +++ b/lib/codemirror-3.1/mode/haskell/haskell.js @@ -0,0 +1,242 @@ +CodeMirror.defineMode("haskell", 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 = /[-!#$%&*+.\/<=>?@\\^|~:]/; + 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 "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.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"; + } + } + 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 "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")( + "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", + "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"); + + 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 (w in wellKnownWords) ? wellKnownWords[w] : t; + } + }; + +}); + +CodeMirror.defineMIME("text/x-haskell", "haskell"); diff --git a/lib/codemirror-3.1/mode/haskell/index.html b/lib/codemirror-3.1/mode/haskell/index.html new file mode 100644 index 0000000000000000000000000000000000000000..56307b8a95d53355c9fc5144e13b2cc8ac954793 --- /dev/null +++ b/lib/codemirror-3.1/mode/haskell/index.html @@ -0,0 +1,62 @@ + + + + + CodeMirror: Haskell mode + + + + + + + + + +

CodeMirror: Haskell mode

+ +
+ + + +

MIME types defined: text/x-haskell.

+ + diff --git a/lib/codemirror-3.1/mode/haxe/haxe.js b/lib/codemirror-3.1/mode/haxe/haxe.js new file mode 100644 index 0000000000000000000000000000000000000000..786fe92d06a7567c144fa2fbe7240dd0cc5ccfe0 --- /dev/null +++ b/lib/codemirror-3.1/mode/haxe/haxe.js @@ -0,0 +1,429 @@ +CodeMirror.defineMode("haxe", function(config, parserConfig) { + var indentUnit = config.indentUnit; + + // 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"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"}; + var type = kw("typedef"); + return { + "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, "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 nextUntilUnescaped(stream, end) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (next == end && !escaped) + return false; + escaped = !escaped && next == "\\"; + } + return escaped; + } + + // 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(/\//))) { + nextUntilUnescaped(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 (!nextUntilUnescaped(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 register(varname) { + var state = cx.state; + if (state.context) { + cx.marked = "def"; + for (var v = state.localVars; v; v = v.next) + if (v.name == varname) return; + state.localVars = {name: varname, next: state.localVars}; + } + } + + // 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; + } + 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) { + return function(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(arguments.callee); + }; + } + + 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 == "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(expression, "]"), 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(")"), comasep(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 == ".") return cont(importdef); + } + + function typedef (type, value) + { + if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); 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(pushlex(")"), pushcontext, forin, expression, poplex, statement, popcontext); + } + function forin(_type, value) { + if (value == "in") return cont(); + } + function functiondef(type, value) { + if (type == "variable") {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"]; + return { + 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 + }; + }, + + 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: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-haxe", "haxe"); diff --git a/lib/codemirror-3.1/mode/haxe/index.html b/lib/codemirror-3.1/mode/haxe/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1125741ad570d2a66ae8e4566be49774245572e6 --- /dev/null +++ b/lib/codemirror-3.1/mode/haxe/index.html @@ -0,0 +1,90 @@ + + + + + CodeMirror: Haxe mode + + + + + + + +

CodeMirror: Haxe mode

+ +
+ + + +

MIME types defined: text/x-haxe.

+ + diff --git a/lib/codemirror-3.1/mode/htmlembedded/htmlembedded.js b/lib/codemirror-3.1/mode/htmlembedded/htmlembedded.js new file mode 100644 index 0000000000000000000000000000000000000000..e183d6746712242d66cc42186e7eb289238069bd --- /dev/null +++ b/lib/codemirror-3.1/mode/htmlembedded/htmlembedded.js @@ -0,0 +1,73 @@ +CodeMirror.defineMode("htmlembedded", function(config, parserConfig) { + + //config settings + var scriptStartRegex = parserConfig.scriptStartRegex || /^<%/i, + scriptEndRegex = parserConfig.scriptEndRegex || /^%>/i; + + //inner modes + var scriptingMode, htmlMixedMode; + + //tokenizer when in html mode + function htmlDispatch(stream, state) { + if (stream.match(scriptStartRegex, false)) { + state.token=scriptingDispatch; + return scriptingMode.token(stream, state.scriptState); + } + else + return htmlMixedMode.token(stream, state.htmlState); + } + + //tokenizer when in scripting mode + function scriptingDispatch(stream, state) { + if (stream.match(scriptEndRegex, false)) { + state.token=htmlDispatch; + return htmlMixedMode.token(stream, state.htmlState); + } + else + return scriptingMode.token(stream, state.scriptState); + } + + + return { + startState: function() { + scriptingMode = scriptingMode || CodeMirror.getMode(config, parserConfig.scriptingModeSpec); + htmlMixedMode = htmlMixedMode || CodeMirror.getMode(config, "htmlmixed"); + return { + token : parserConfig.startOpen ? scriptingDispatch : htmlDispatch, + htmlState : CodeMirror.startState(htmlMixedMode), + scriptState : CodeMirror.startState(scriptingMode) + }; + }, + + token: function(stream, state) { + return state.token(stream, state); + }, + + indent: function(state, textAfter) { + if (state.token == htmlDispatch) + return htmlMixedMode.indent(state.htmlState, textAfter); + else if (scriptingMode.indent) + return scriptingMode.indent(state.scriptState, textAfter); + }, + + copyState: function(state) { + return { + token : state.token, + htmlState : CodeMirror.copyState(htmlMixedMode, state.htmlState), + scriptState : CodeMirror.copyState(scriptingMode, state.scriptState) + }; + }, + + electricChars: "/{}:", + + innerMode: function(state) { + if (state.token == scriptingDispatch) return {state: state.scriptState, mode: scriptingMode}; + else return {state: state.htmlState, mode: htmlMixedMode}; + } + }; +}, "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"}); diff --git a/lib/codemirror-3.1/mode/htmlembedded/index.html b/lib/codemirror-3.1/mode/htmlembedded/index.html new file mode 100644 index 0000000000000000000000000000000000000000..5a37dd637dfe12b331a269b6dc0a77cbecf1a9dd --- /dev/null +++ b/lib/codemirror-3.1/mode/htmlembedded/index.html @@ -0,0 +1,49 @@ + + + + + CodeMirror: Html Embedded Scripts mode + + + + + + + + + + + +

CodeMirror: Html Embedded Scripts mode

+ +
+ + + +

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

+ +

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

+ + diff --git a/lib/codemirror-3.1/mode/htmlmixed/htmlmixed.js b/lib/codemirror-3.1/mode/htmlmixed/htmlmixed.js new file mode 100644 index 0000000000000000000000000000000000000000..ec0c21d24ad8c198f84a06eaacc1f7e67023daca --- /dev/null +++ b/lib/codemirror-3.1/mode/htmlmixed/htmlmixed.js @@ -0,0 +1,104 @@ +CodeMirror.defineMode("htmlmixed", function(config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, {name: "xml", htmlMode: true}); + var cssMode = CodeMirror.getMode(config, "css"); + + var scriptTypes = [], scriptTypesConf = parserConfig && parserConfig.scriptTypes; + scriptTypes.push({matches: /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^$/i, + mode: CodeMirror.getMode(config, "javascript")}); + if (scriptTypesConf) for (var i = 0; i < scriptTypesConf.length; ++i) { + var conf = scriptTypesConf[i]; + scriptTypes.push({matches: conf.matches, mode: conf.mode && CodeMirror.getMode(config, conf.mode)}); + } + scriptTypes.push({matches: /./, + mode: CodeMirror.getMode(config, "text/plain")}); + + function html(stream, state) { + var tagName = state.htmlState.tagName; + var style = htmlMode.token(stream, state.htmlState); + if (tagName == "script" && /\btag\b/.test(style) && stream.current() == ">") { + // Script block: mode to change to depends on type attribute + var scriptType = stream.string.slice(Math.max(0, stream.pos - 100), stream.pos).match(/\btype\s*=\s*("[^"]+"|'[^']+'|\S+)[^<]*$/i); + scriptType = scriptType ? scriptType[1] : ""; + if (scriptType && /[\"\']/.test(scriptType.charAt(0))) scriptType = scriptType.slice(1, scriptType.length - 1); + for (var i = 0; i < scriptTypes.length; ++i) { + var tp = scriptTypes[i]; + if (typeof tp.matches == "string" ? scriptType == tp.matches : tp.matches.test(scriptType)) { + if (tp.mode) { + state.token = script; + state.localMode = tp.mode; + state.localState = tp.mode.startState && tp.mode.startState(htmlMode.indent(state.htmlState, "")); + } + break; + } + } + } else if (tagName == "style" && /\btag\b/.test(style) && stream.current() == ">") { + state.token = css; + state.localMode = cssMode; + state.localState = cssMode.startState(htmlMode.indent(state.htmlState, "")); + } + return style; + } + function maybeBackup(stream, pat, style) { + var cur = stream.current(); + var close = cur.search(pat), m; + if (close > -1) stream.backUp(cur.length - close); + else if (m = cur.match(/<\/?$/)) { + stream.backUp(cur.length); + if (!stream.match(pat, false)) stream.match(cur[0]); + } + return style; + } + function script(stream, state) { + if (stream.match(/^<\/\s*script\s*>/i, false)) { + state.token = html; + state.localState = state.localMode = null; + return html(stream, state); + } + return maybeBackup(stream, /<\/\s*script\s*>/, + state.localMode.token(stream, state.localState)); + } + function css(stream, state) { + if (stream.match(/^<\/\s*style\s*>/i, false)) { + state.token = html; + state.localState = state.localMode = null; + return html(stream, state); + } + return maybeBackup(stream, /<\/\s*style\s*>/, + cssMode.token(stream, state.localState)); + } + + return { + startState: function() { + var state = htmlMode.startState(); + return {token: html, localMode: null, localState: null, htmlState: state}; + }, + + copyState: function(state) { + if (state.localState) + var local = CodeMirror.copyState(state.localMode, state.localState); + return {token: state.token, localMode: state.localMode, localState: local, + htmlState: CodeMirror.copyState(htmlMode, state.htmlState)}; + }, + + token: function(stream, state) { + return state.token(stream, state); + }, + + indent: function(state, textAfter) { + if (!state.localMode || /^\s*<\//.test(textAfter)) + return htmlMode.indent(state.htmlState, textAfter); + else if (state.localMode.indent) + return state.localMode.indent(state.localState, textAfter); + else + return CodeMirror.Pass; + }, + + electricChars: "/{}:", + + innerMode: function(state) { + return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode}; + } + }; +}, "xml", "javascript", "css"); + +CodeMirror.defineMIME("text/html", "htmlmixed"); diff --git a/lib/codemirror-3.1/mode/htmlmixed/index.html b/lib/codemirror-3.1/mode/htmlmixed/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c56559e559c6a8ab83b60b63a94f0a897b67262c --- /dev/null +++ b/lib/codemirror-3.1/mode/htmlmixed/index.html @@ -0,0 +1,73 @@ + + + + + CodeMirror: HTML mixed mode + + + + + + + + + + + +

CodeMirror: HTML mixed mode

+
+ + +

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

+ +

It takes an optional mode configuration + option, scriptTypes, which can be used to add custom + behavior for specific <script type="..."> tags. If + given, it should hold an array of {matches, mode} + objects, where matches is a string or regexp that + matches the script type, and mode is + either null, for script types that should stay in + HTML mode, or a mode + spec corresponding to the mode that should be used for the + script.

+ +

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

+ + + diff --git a/lib/codemirror-3.1/mode/http/http.js b/lib/codemirror-3.1/mode/http/http.js new file mode 100644 index 0000000000000000000000000000000000000000..5a5163602766be8f71354f75f0f10db5b5ad2b3f --- /dev/null +++ b/lib/codemirror-3.1/mode/http/http.js @@ -0,0 +1,98 @@ +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"); diff --git a/lib/codemirror-3.1/mode/http/index.html b/lib/codemirror-3.1/mode/http/index.html new file mode 100644 index 0000000000000000000000000000000000000000..124eb84f95abd5d66e728c0b9ad7531b71b84dd4 --- /dev/null +++ b/lib/codemirror-3.1/mode/http/index.html @@ -0,0 +1,32 @@ + + + + + CodeMirror: HTTP mode + + + + + + + +

CodeMirror: HTTP mode

+ +
+ + + +

MIME types defined: message/http.

+ + diff --git a/lib/codemirror-3.1/mode/javascript/index.html b/lib/codemirror-3.1/mode/javascript/index.html new file mode 100644 index 0000000000000000000000000000000000000000..9222ddf170108f16be8bf26501fc6f99fe332a4b --- /dev/null +++ b/lib/codemirror-3.1/mode/javascript/index.html @@ -0,0 +1,88 @@ + + + + + CodeMirror: JavaScript mode + + + + + + + + + +

CodeMirror: JavaScript mode

+ +
+ + + +

+ JavaScript mode supports a two configuration + options: +

    +
  • json which will set the mode to expect JSON data rather than a JavaScript program.
  • +
  • + typescript which will activate additional syntax highlighting and some other things for TypeScript code (demo). +
  • +
+

+ +

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

+ + diff --git a/lib/codemirror-3.1/mode/javascript/javascript.js b/lib/codemirror-3.1/mode/javascript/javascript.js new file mode 100644 index 0000000000000000000000000000000000000000..d41536f77adfd01fa1443b7a65ca9de4e3cf812c --- /dev/null +++ b/lib/codemirror-3.1/mode/javascript/javascript.js @@ -0,0 +1,426 @@ +// TODO actually recognize syntax of TypeScript constructs + +CodeMirror.defineMode("javascript", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var jsonMode = parserConfig.json; + var isTS = parserConfig.typescript; + + // 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"); + var operator = kw("operator"), atom = {type: "atom", style: "atom"}; + + var jsKeywords = { + "if": A, "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, + "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, + "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 + }; + + // Extend the 'normal' keywords with the TypeScript language extensions + if (isTS) { + var type = {type: "variable", style: "variable-3"}; + var tsKeywords = { + // object-like things + "interface": kw("interface"), + "class": kw("class"), + "extends": kw("extends"), + "constructor": kw("constructor"), + + // scope modifiers + "public": kw("public"), + "private": kw("private"), + "protected": kw("protected"), + "static": kw("static"), + + "super": kw("super"), + + // types + "string": type, "number": type, "bool": type, "any": type + }; + + for (var attr in tsKeywords) { + jsKeywords[attr] = tsKeywords[attr]; + } + } + + return jsKeywords; + }(); + + var isOperatorChar = /[+\-*&%=<>!?|]/; + + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + function nextUntilUnescaped(stream, end) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (next == end && !escaped) + return false; + escaped = !escaped && next == "\\"; + } + return escaped; + } + + // 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 jsTokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"' || ch == "'") + return chain(stream, state, jsTokenString(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 (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, jsTokenComment); + } + else if (stream.eat("/")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } + else if (state.lastType == "operator" || state.lastType == "keyword c" || + /^[\[{}\(,;:]$/.test(state.lastType)) { + nextUntilUnescaped(stream, "/"); + stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla + return ret("regexp", "string-2"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + } + else if (ch == "#") { + stream.skipToEnd(); + return ret("error", "error"); + } + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", null, stream.current()); + } + else { + stream.eatWhile(/[\w\$_]/); + var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; + return (known && state.lastType != ".") ? ret(known.type, known.style, word) : + ret("variable", "variable", word); + } + } + + function jsTokenString(quote) { + return function(stream, state) { + if (!nextUntilUnescaped(stream, quote)) + state.tokenize = jsTokenBase; + return ret("string", "string"); + }; + } + + function jsTokenComment(stream, state) { + var maybeEnd = false, ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "*"); + } + return ret("comment", "comment"); + } + + // Parser + + var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": 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; + } + + 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; + + 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 register(varname) { + function inList(list) { + for (var v = list; v; v = v.next) + if (v.name == varname) return true; + return false; + } + var state = cx.state; + if (state.context) { + cx.marked = "def"; + if (inList(state.localVars)) return; + state.localVars = {name: varname, next: state.localVars}; + } else { + if (inList(state.globalVars)) return; + state.globalVars = {name: varname, next: state.globalVars}; + } + } + + // Combinators + + var defaultVars = {name: "this", next: {name: "arguments"}}; + function pushcontext() { + cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; + cx.state.localVars = defaultVars; + } + function popcontext() { + cx.state.localVars = cx.state.context.vars; + cx.state.context = cx.state.context.prev; + } + function pushlex(type, info) { + var result = function() { + var state = cx.state; + state.lexical = new JSLexical(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) { + return function(type) { + if (type == wanted) return cont(); + else if (wanted == ";") return pass(); + else return cont(arguments.callee); + }; + } + + function statement(type) { + 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("}"), block, poplex); + if (type == ";") return cont(); + 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); + return pass(pushlex("stat"), expression, expect(";"), poplex); + } + function expression(type) { + if (atomicTypes.hasOwnProperty(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(expression, "]"), 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") { + if (/\+\+|--/.test(value)) return cont(maybeoperator); + if (value == "?") return cont(expression, expect(":"), expression); + 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 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"; + else if (type == "number" || type == "string") cx.marked = type + " 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 maybetype(type) { + if (type == ":") return cont(typedef); + return pass(); + } + function typedef(type) { + if (type == "variable"){cx.marked = "variable-3"; return cont();} + return pass(); + } + function vardef1(type, value) { + if (type == "variable") { + register(value); + return isTS ? cont(maybetype, vardef2) : cont(vardef2); + } + return pass(); + } + function vardef2(type, value) { + if (value == "=") return cont(expression, vardef2); + if (type == ",") return cont(vardef1); + } + function forspec1(type) { + if (type == "var") return cont(vardef1, expect(";"), forspec2); + if (type == ";") return cont(forspec2); + if (type == "variable") return cont(formaybein); + return cont(forspec2); + } + function formaybein(_type, value) { + if (value == "in") return cont(expression); + return cont(maybeoperator, forspec2); + } + function forspec2(type, value) { + if (type == ";") return cont(forspec3); + if (value == "in") return cont(expression); + return cont(expression, expect(";"), forspec3); + } + function forspec3(type) { + if (type != ")") cont(expression); + } + function functiondef(type, value) { + if (type == "variable") {register(value); return cont(functiondef);} + if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, statement, popcontext); + } + function funarg(type, value) { + if (type == "variable") {register(value); return isTS ? cont(maybetype) : cont();} + } + + // Interface + + return { + startState: function(basecolumn) { + return { + tokenize: jsTokenBase, + lastType: null, + cc: [], + lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), + localVars: parserConfig.localVars, + globalVars: parserConfig.globalVars, + context: parserConfig.localVars && {vars: parserConfig.localVars}, + indented: 0 + }; + }, + + 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.lastType = type; + return parseJS(state, style, type, content, stream); + }, + + indent: function(state, textAfter) { + if (state.tokenize == jsTokenComment) return CodeMirror.Pass; + if (state.tokenize != jsTokenBase) 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 + (state.lastType == "operator" || state.lastType == "," ? 4 : 0); + else if (type == "form" && firstChar == "{") return lexical.indented; + else if (type == "form") return lexical.indented + indentUnit; + else if (type == "stat") + return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? indentUnit : 0); + 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: ":{}", + + jsonMode: jsonMode + }; +}); + +CodeMirror.defineMIME("text/javascript", "javascript"); +CodeMirror.defineMIME("text/ecmascript", "javascript"); +CodeMirror.defineMIME("application/javascript", "javascript"); +CodeMirror.defineMIME("application/ecmascript", "javascript"); +CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); +CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); +CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); diff --git a/lib/codemirror-3.1/mode/javascript/typescript.html b/lib/codemirror-3.1/mode/javascript/typescript.html new file mode 100644 index 0000000000000000000000000000000000000000..58315e7ac7d90db43a9082a0f5b714313c8d90e2 --- /dev/null +++ b/lib/codemirror-3.1/mode/javascript/typescript.html @@ -0,0 +1,48 @@ + + + + + CodeMirror: TypeScript mode + + + + + + + +

CodeMirror: TypeScript mode

+ +
+ + + +

This is a specialization of the JavaScript mode.

+ + diff --git a/lib/codemirror-3.1/mode/jinja2/index.html b/lib/codemirror-3.1/mode/jinja2/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7cd1da2335a245730dc5fe94ca6d74d5e9e444a5 --- /dev/null +++ b/lib/codemirror-3.1/mode/jinja2/index.html @@ -0,0 +1,38 @@ + + + + + CodeMirror: Jinja2 mode + + + + + + + +

CodeMirror: Jinja2 mode

+
+ + + diff --git a/lib/codemirror-3.1/mode/jinja2/jinja2.js b/lib/codemirror-3.1/mode/jinja2/jinja2.js new file mode 100644 index 0000000000000000000000000000000000000000..1472d398f2fc2b480991a35a12f39f57baffb860 --- /dev/null +++ b/lib/codemirror-3.1/mode/jinja2/jinja2.js @@ -0,0 +1,42 @@ +CodeMirror.defineMode("jinja2", function() { + var keywords = ["block", "endblock", "for", "endfor", "in", "true", "false", + "loop", "none", "self", "super", "if", "as", "not", "and", + "else", "import", "with", "without", "context"]; + keywords = new RegExp("^((" + keywords.join(")|(") + "))\\b"); + + function tokenBase (stream, state) { + var ch = stream.next(); + if (ch == "{") { + if (ch = stream.eat(/\{|%|#/)) { + 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 || (ch == "-" && stream.eat(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); + } + }; +}); diff --git a/lib/codemirror-3.1/mode/less/index.html b/lib/codemirror-3.1/mode/less/index.html new file mode 100644 index 0000000000000000000000000000000000000000..78c1e53074caefabd809d756252127590b5a4b00 --- /dev/null +++ b/lib/codemirror-3.1/mode/less/index.html @@ -0,0 +1,741 @@ + + + + + CodeMirror: LESS mode + + + + + + + + + +

CodeMirror: LESS mode

+
+ + +

MIME types defined: text/x-less, text/css (if not previously defined).

+ + diff --git a/lib/codemirror-3.1/mode/less/less.js b/lib/codemirror-3.1/mode/less/less.js new file mode 100644 index 0000000000000000000000000000000000000000..70cd5c937b3fbc208c8aacbb6fd8d81b33795bf5 --- /dev/null +++ b/lib/codemirror-3.1/mode/less/less.js @@ -0,0 +1,266 @@ +/* + LESS mode - http://www.lesscss.org/ + Ported to CodeMirror by Peter Kroon + Report bugs/issues here: https://github.com/marijnh/CodeMirror/issues GitHub: @peterkroon +*/ + +CodeMirror.defineMode("less", function(config) { + var indentUnit = config.indentUnit, type; + function ret(style, tp) {type = tp; return style;} + //html tags + var tags = "a abbr acronym address applet area article aside audio b base basefont bdi bdo big blockquote body br button canvas caption cite code col colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins keygen kbd label legend li link map mark menu meta meter nav noframes noscript object ol optgroup option output p param pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr track tt u ul var video wbr".split(' '); + + function inTagsArray(val){ + for(var i=0; i*\/]/.test(ch)) { + if(stream.peek() == "=" || type == "a")return ret("string", "string"); + return ret(null, "select-op"); + } + else if (/[;{}:\[\]()~\|]/.test(ch)) { + if(ch == ":"){ + stream.eatWhile(/[a-z\\\-]/); + if( selectors.test(stream.current()) ){ + return ret("tag", "tag"); + }else if(stream.peek() == ":"){//::-webkit-search-decoration + stream.next(); + stream.eatWhile(/[a-z\\\-]/); + if(stream.current().match(/\:\:\-(o|ms|moz|webkit)\-/))return ret("string", "string"); + if( selectors.test(stream.current().substring(1)) )return ret("tag", "tag"); + return ret(null, ch); + }else{ + return ret(null, ch); + } + }else if(ch == "~"){ + if(type == "r")return ret("string", "string"); + }else{ + return ret(null, ch); + } + } + else if (ch == ".") { + if(type == "(" || type == "string")return ret("string", "string"); // allow url(../image.png) + stream.eatWhile(/[\a-zA-Z0-9\-_]/); + if(stream.peek() == " ")stream.eatSpace(); + if(stream.peek() == ")")return ret("number", "unit");//rgba(0,0,0,.25); + return ret("tag", "tag"); + } + else if (ch == "#") { + //we don't eat white-space, we want the hex color and or id only + stream.eatWhile(/[A-Za-z0-9]/); + //check if there is a proper hex color length e.g. #eee || #eeeEEE + if(stream.current().length == 4 || stream.current().length == 7){ + if(stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false) != null){//is there a valid hex color value present in the current stream + //when not a valid hex value, parse as id + if(stream.current().substring(1) != stream.current().match(/[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}/,false))return ret("atom", "tag"); + //eat white-space + stream.eatSpace(); + //when hex value declaration doesn't end with [;,] but is does with a slash/cc comment treat it as an id, just like the other hex values that don't end with[;,] + if( /[\/<>.(){!$%^&*_\-\\?=+\|#'~`]/.test(stream.peek()) )return ret("atom", "tag"); + //#time { color: #aaa } + else if(stream.peek() == "}" )return ret("number", "unit"); + //we have a valid hex color value, parse as id whenever an element/class is defined after the hex(id) value e.g. #eee aaa || #eee .aaa + else if( /[a-zA-Z\\]/.test(stream.peek()) )return ret("atom", "tag"); + //when a hex value is on the end of a line, parse as id + else if(stream.eol())return ret("atom", "tag"); + //default + else return ret("number", "unit"); + }else{//when not a valid hexvalue in the current stream e.g. #footer + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "tag"); + } + }else{//when not a valid hexvalue length + stream.eatWhile(/[\w\\\-]/); + return ret("atom", "tag"); + } + } + else if (ch == "&") { + stream.eatWhile(/[\w\-]/); + return ret(null, ch); + } + else { + stream.eatWhile(/[\w\\\-_%.{]/); + if(type == "string"){ + return ret("string", "string"); + }else if(stream.current().match(/(^http$|^https$)/) != null){ + stream.eatWhile(/[\w\\\-_%.{:\/]/); + return ret("string", "string"); + }else if(stream.peek() == "<" || stream.peek() == ">"){ + return ret("tag", "tag"); + }else if( /\(/.test(stream.peek()) ){ + return ret(null, ch); + }else if (stream.peek() == "/" && state.stack[state.stack.length-1] != undefined){ // url(dir/center/image.png) + return ret("string", "string"); + }else if( stream.current().match(/\-\d|\-.\d/) ){ // match e.g.: -5px -0.4 etc... only colorize the minus sign + //commment out these 2 comment if you want the minus sign to be parsed as null -500px + //stream.backUp(stream.current().length-1); + //return ret(null, ch); //console.log( stream.current() ); + return ret("number", "unit"); + }else if( inTagsArray(stream.current().toLowerCase()) ){ // match html tags + return ret("tag", "tag"); + }else if( /\/|[\s\)]/.test(stream.peek() || stream.eol() || (stream.eatSpace() && stream.peek() == "/")) && stream.current().indexOf(".") !== -1){ + if(stream.current().substring(stream.current().length-1,stream.current().length) == "{"){ + stream.backUp(1); + return ret("tag", "tag"); + }//end if + stream.eatSpace(); + if( /[{<>.a-zA-Z\/]/.test(stream.peek()) || stream.eol() )return ret("tag", "tag"); // e.g. button.icon-plus + return ret("string", "string"); // let url(/images/logo.png) without quotes return as string + }else if( stream.eol() || stream.peek() == "[" || stream.peek() == "#" || type == "tag" ){ + if(stream.current().substring(stream.current().length-1,stream.current().length) == "{")stream.backUp(1); + return ret("tag", "tag"); + }else if(type == "compare" || type == "a" || type == "("){ + return ret("string", "string"); + }else if(type == "|" || stream.current() == "-" || type == "["){ + return ret(null, ch); + }else if(stream.peek() == ":") { + stream.next(); + var t_v = stream.peek() == ":" ? true : false; + if(!t_v){ + var old_pos = stream.pos; + var sc = stream.current().length; + stream.eatWhile(/[a-z\\\-]/); + var new_pos = stream.pos; + if(stream.current().substring(sc-1).match(selectors) != null){ + stream.backUp(new_pos-(old_pos-1)); + return ret("tag", "tag"); + } else stream.backUp(new_pos-(old_pos-1)); + }else{ + stream.backUp(1); + } + if(t_v)return ret("tag", "tag"); else return ret("variable", "variable"); + }else{ + return ret("variable", "variable"); + } + } + } + + function tokenSComment(stream, state) { // SComment = Slash comment + stream.skipToEnd(); + state.tokenize = tokenBase; + return ret("comment", "comment"); + } + + 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; + 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 = null; //"tag" + else if (!context || context == "@media{") { + style = stream.current() == "when" ? "variable" : + /[\s,|\s\)|\s]/.test(stream.peek()) ? "tag" : type; + } + } + + 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-less", "less"); +if (!CodeMirror.mimeModes.hasOwnProperty("text/css")) + CodeMirror.defineMIME("text/css", "less"); \ No newline at end of file diff --git a/lib/codemirror-3.1/mode/lua/index.html b/lib/codemirror-3.1/mode/lua/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a0a42d91c49e600570a69c9001b149bb2ebad57e --- /dev/null +++ b/lib/codemirror-3.1/mode/lua/index.html @@ -0,0 +1,74 @@ + + + + + CodeMirror: Lua mode + + + + + + + + + +

CodeMirror: 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.

+ + + diff --git a/lib/codemirror-3.1/mode/lua/lua.js b/lib/codemirror-3.1/mode/lua/lua.js new file mode 100644 index 0000000000000000000000000000000000000000..97fb2c6f96dfcf896131106b490524874bc6a507 --- /dev/null +++ b/lib/codemirror-3.1/mode/lua/lua.js @@ -0,0 +1,140 @@ +// LUA mode. Ported to CodeMirror 2 from Franciszek Wawrzak's +// CodeMirror 1 mode. +// highlights keywords, strings, comments (no leveling supported! ("[==[")), tokens, basic indenting + +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)); + } + }; +}); + +CodeMirror.defineMIME("text/x-lua", "lua"); diff --git a/lib/codemirror-3.1/mode/markdown/index.html b/lib/codemirror-3.1/mode/markdown/index.html new file mode 100644 index 0000000000000000000000000000000000000000..6f97b10e7304142accb123b011e201287aec8264 --- /dev/null +++ b/lib/codemirror-3.1/mode/markdown/index.html @@ -0,0 +1,344 @@ + + + + + CodeMirror: Markdown mode + + + + + + + + + +

CodeMirror: Markdown mode

+ + +
+ + + +

Optionally depends on the XML mode for properly highlighted inline XML blocks.

+ +

MIME types defined: text/x-markdown.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/lib/codemirror-3.1/mode/markdown/markdown.js b/lib/codemirror-3.1/mode/markdown/markdown.js new file mode 100644 index 0000000000000000000000000000000000000000..63de81e6eecf63ed6a78fa87efb35e6d77cf6a48 --- /dev/null +++ b/lib/codemirror-3.1/mode/markdown/markdown.js @@ -0,0 +1,475 @@ +CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { + + var htmlFound = CodeMirror.mimeModes.hasOwnProperty("text/html"); + var htmlMode = CodeMirror.getMode(cmCfg, htmlFound ? "text/html" : "text/plain"); + var aliases = { + html: "htmlmixed", + js: "javascript", + json: "application/json", + c: "text/x-csrc", + "c++": "text/x-c++src", + java: "text/x-java", + csharp: "text/x-csharp", + "c#": "text/x-csharp", + scala: "text/x-scala" + }; + + var getMode = (function () { + var i, modes = {}, mimes = {}, mime; + + var list = []; + for (var m in CodeMirror.modes) + if (CodeMirror.modes.propertyIsEnumerable(m)) list.push(m); + for (i = 0; i < list.length; i++) { + modes[list[i]] = list[i]; + } + var mimesList = []; + for (var m in CodeMirror.mimeModes) + if (CodeMirror.mimeModes.propertyIsEnumerable(m)) + mimesList.push({mime: m, mode: CodeMirror.mimeModes[m]}); + for (i = 0; i < mimesList.length; i++) { + mime = mimesList[i].mime; + mimes[mime] = mimesList[i].mime; + } + + for (var a in aliases) { + if (aliases[a] in modes || aliases[a] in mimes) + modes[a] = aliases[a]; + } + + return function (lang) { + return modes[lang] ? CodeMirror.getMode(cmCfg, modes[lang]) : null; + }; + }()); + + // Should underscores in words open/close em/strong? + if (modeCfg.underscoresBreakWords === undefined) + modeCfg.underscoresBreakWords = true; + + // Turn on fenced code blocks? ("```" to start/end) + if (modeCfg.fencedCodeBlocks === undefined) modeCfg.fencedCodeBlocks = false; + + var codeDepth = 0; + var prevLineHasContent = false + , thisLineHasContent = false; + + var header = 'header' + , code = 'comment' + , quote = 'quote' + , list = 'string' + , hr = 'hr' + , image = 'tag' + , linkinline = 'link' + , linkemail = 'link' + , linktext = 'link' + , linkhref = 'string' + , em = 'em' + , strong = 'strong' + , emstrong = 'emstrong'; + + var hrRE = /^([*\-=_])(?:\s*\1){2,}\s*$/ + , ulRE = /^[*\-+]\s+/ + , olRE = /^[0-9]+\.\s+/ + , headerRE = /^(?:\={1,}|-{1,})$/ + , textRE = /^[^!\[\]*_\\<>` "'(]+/; + + 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); + } + + + // Blocks + + function blankLine(state) { + // Reset linkTitle state + state.linkTitle = false; + // Reset EM state + state.em = false; + // Reset STRONG state + state.strong = false; + // Reset state.quote + state.quote = false; + if (!htmlFound && state.f == htmlBlock) { + state.f = inlineNormal; + state.block = blockNormal; + } + return null; + } + + function blockNormal(stream, state) { + + if (state.list !== false && state.indentationDiff >= 0) { // Continued list + if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block + state.indentation -= state.indentationDiff; + } + state.list = null; + } else { // No longer a list + state.list = false; + } + + if (state.indentationDiff >= 4) { + state.indentation -= 4; + stream.skipToEnd(); + return code; + } else if (stream.eatSpace()) { + return null; + } else if (stream.peek() === '#' || (prevLineHasContent && stream.match(headerRE)) ) { + state.header = true; + } else if (stream.eat('>')) { + state.indentation++; + state.quote = true; + } else if (stream.peek() === '[') { + return switchInline(stream, state, footnoteLink); + } else if (stream.match(hrRE, true)) { + return hr; + } else if (stream.match(ulRE, true) || stream.match(olRE, true)) { + state.indentation += 4; + state.list = true; + } else if (modeCfg.fencedCodeBlocks && stream.match(/^```([\w+#]*)/, true)) { + // try switching mode + state.localMode = getMode(RegExp.$1); + if (state.localMode) state.localState = state.localMode.startState(); + switchBlock(stream, state, local); + return code; + } + + return switchInline(stream, state, state.inline); + } + + function htmlBlock(stream, state) { + var style = htmlMode.token(stream, state.htmlState); + if (htmlFound && style === 'tag' && state.htmlState.type !== 'openTag' && !state.htmlState.context) { + state.f = inlineNormal; + state.block = blockNormal; + } + if (state.md_inside && stream.current().indexOf(">")!=-1) { + state.f = inlineNormal; + state.block = blockNormal; + state.htmlState.context = undefined; + } + return style; + } + + function local(stream, state) { + if (stream.sol() && stream.match(/^```/, true)) { + state.localMode = state.localState = null; + state.f = inlineNormal; + state.block = blockNormal; + return code; + } else if (state.localMode) { + return state.localMode.token(stream, state.localState); + } else { + stream.skipToEnd(); + return code; + } + } + + // Inline + function getType(state) { + var styles = []; + + if (state.strong) { styles.push(state.em ? emstrong : strong); } + else if (state.em) { styles.push(em); } + + if (state.linkText) { styles.push(linktext); } + + if (state.code) { styles.push(code); } + + if (state.header) { styles.push(header); } + if (state.quote) { styles.push(quote); } + if (state.list !== false) { styles.push(list); } + + 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 list; + } + + var ch = stream.next(); + + if (ch === '\\') { + stream.next(); + return getType(state); + } + + // 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 linkhref; + } + } + + // If this block is changed, it may need to be updated in GFM mode + if (ch === '`') { + var t = getType(state); + var before = stream.pos; + stream.eatWhile('`'); + var difference = 1 + stream.pos - before; + if (!state.code) { + codeDepth = difference; + state.code = true; + return getType(state); + } else { + if (difference === codeDepth) { // Must be exact + state.code = false; + return t; + } + return getType(state); + } + } else if (state.code) { + return getType(state); + } + + if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { + stream.match(/\[[^\]]*\]/); + state.inline = state.f = linkHref; + return image; + } + + if (ch === '[' && stream.match(/.*\](\(| ?\[)/, false)) { + state.linkText = true; + return getType(state); + } + + if (ch === ']' && state.linkText) { + var type = getType(state); + state.linkText = false; + state.inline = state.f = linkHref; + return type; + } + + if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, true)) { + return switchInline(stream, state, inlineElement(linkinline, '>')); + } + + if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, true)) { + return switchInline(stream, state, inlineElement(linkemail, '>')); + } + + if (ch === '<' && stream.match(/^\w/, false)) { + if (stream.string.indexOf(">")!=-1) { + var atts = stream.string.substring(1,stream.string.indexOf(">")); + if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) { + state.md_inside = true; + } + } + stream.backUp(1); + return switchBlock(stream, state, htmlBlock); + } + + if (ch === '<' && stream.match(/^\/\w*?>/)) { + state.md_inside = false; + return "tag"; + } + + var ignoreUnderscore = false; + if (!modeCfg.underscoresBreakWords) { + if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) { + var prevPos = stream.pos - 2; + if (prevPos >= 0) { + var prevCh = stream.string.charAt(prevPos); + if (prevCh !== '_' && prevCh.match(/(\w)/, false)) { + ignoreUnderscore = true; + } + } + } + } + var t = getType(state); + if (ch === '*' || (ch === '_' && !ignoreUnderscore)) { + if (state.strong === ch && stream.eat(ch)) { // Remove STRONG + state.strong = false; + return t; + } else if (!state.strong && stream.eat(ch)) { // Add STRONG + state.strong = ch; + return getType(state); + } else if (state.em === ch) { // Remove EM + state.em = false; + return t; + } else if (!state.em) { // Add EM + state.em = ch; + return getType(state); + } + } 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); + } + } + } + + return getType(state); + } + + 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 === '[') { + return switchInline(stream, state, inlineElement(linkhref, ch === '(' ? ')' : ']')); + } + return 'error'; + } + + function footnoteLink(stream, state) { + if (stream.match(/^[^\]]*\]:/, true)) { + state.f = footnoteUrl; + return linktext; + } + return switchInline(stream, state, inlineNormal); + } + + 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 linkhref; + } + + var savedInlineRE = []; + function inlineRE(endChar) { + if (!savedInlineRE[endChar]) { + // Escape endChar for RegExp (taken from http://stackoverflow.com/a/494122/526741) + endChar = (endChar+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); + // Match any non-endChar, escaped character, as well as the closing + // endChar. + savedInlineRE[endChar] = new RegExp('^(?:[^\\\\]|\\\\.)*?(' + endChar + ')'); + } + return savedInlineRE[endChar]; + } + + function inlineElement(type, endChar, next) { + next = next || inlineNormal; + return function(stream, state) { + stream.match(inlineRE(endChar)); + state.inline = state.f = next; + return type; + }; + } + + return { + startState: function() { + prevLineHasContent = false; + thisLineHasContent = false; + return { + f: blockNormal, + + block: blockNormal, + htmlState: CodeMirror.startState(htmlMode), + indentation: 0, + + inline: inlineNormal, + text: handleText, + + linkText: false, + linkTitle: false, + em: false, + strong: false, + header: false, + list: false, + quote: false + }; + }, + + copyState: function(s) { + return { + f: s.f, + + block: s.block, + 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, + linkTitle: s.linkTitle, + em: s.em, + strong: s.strong, + header: s.header, + list: s.list, + quote: s.quote, + md_inside: s.md_inside + }; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (stream.match(/^\s*$/, true)) { + prevLineHasContent = false; + return blankLine(state); + } else { + if(thisLineHasContent){ + prevLineHasContent = true; + thisLineHasContent = false; + } + thisLineHasContent = true; + } + + // Reset state.header + state.header = false; + + // Reset state.code + state.code = false; + + state.f = state.block; + var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length; + var difference = Math.floor((indentation - state.indentation) / 4) * 4; + if (difference > 4) difference = 4; + var adjustedIndentation = state.indentation + difference; + state.indentationDiff = adjustedIndentation - state.indentation; + state.indentation = adjustedIndentation; + if (indentation > 0) return null; + } + return state.f(stream, state); + }, + + blankLine: blankLine, + + getType: getType + }; + +}, "xml"); + +CodeMirror.defineMIME("text/x-markdown", "markdown"); diff --git a/lib/codemirror-3.1/mode/markdown/test.js b/lib/codemirror-3.1/mode/markdown/test.js new file mode 100644 index 0000000000000000000000000000000000000000..eaa7343a20616a58da8e738b11900c8ee3dbe83d --- /dev/null +++ b/lib/codemirror-3.1/mode/markdown/test.js @@ -0,0 +1,579 @@ +(function() { + var mode = CodeMirror.getMode({tabSize: 4}, "markdown"); + function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); } + + MT("plainText", + "foo"); + + // 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 using 4 spaces with internal indentation + MT("codeBlocksUsing4SpacesIndentation", + " foo", + " [comment bar]", + " [comment hello]", + " [comment world]"); + + // Code blocks using 1 tab (regardless of CodeMirror.indentWithTabs value) + MT("codeBlocksUsing1Tab", + "\t[comment foo]"); + + // Inline code using backticks + MT("inlineCodeUsingBackticks", + "foo [comment `bar`]"); + + // Block code using single backtick (shouldn't work) + MT("blockCodeSingleBacktick", + "[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"); + + // atx headers + // http://daringfireball.net/projects/markdown/syntax#header + + MT("atxH1", + "[header # foo]"); + + MT("atxH2", + "[header ## foo]"); + + MT("atxH3", + "[header ### foo]"); + + MT("atxH4", + "[header #### foo]"); + + MT("atxH5", + "[header ##### foo]"); + + MT("atxH6", + "[header ###### foo]"); + + // H6 - 7x '#' should still be H6, per Dingus + // http://daringfireball.net/projects/markdown/dingus + MT("atxH6NotH7", + "[header ####### foo]"); + + // 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", + "foo", + "[header =]"); + + // Check if 3+ ='s work + MT("setextH1", + "foo", + "[header ===]"); + + // Check if single underlining - works + MT("setextH2", + "foo", + "[header -]"); + + // Check if 3+ -'s work + MT("setextH2", + "foo", + "[header ---]"); + + // Single-line blockquote with trailing space + MT("blockquoteSpace", + "[quote > foo]"); + + // Single-line blockquote + MT("blockquoteNoSpace", + "[quote >foo]"); + + // Single-line blockquote followed by normal paragraph + MT("blockquoteThenParagraph", + "[quote >foo]", + "", + "bar"); + + // Multi-line blockquote (lazy mode) + MT("multiBlockquoteLazy", + "[quote >foo]", + "[quote bar]"); + + // Multi-line blockquote followed by normal paragraph (lazy mode) + MT("multiBlockquoteLazyThenParagraph", + "[quote >foo]", + "[quote bar]", + "", + "hello"); + + // Multi-line blockquote (non-lazy mode) + MT("multiBlockquote", + "[quote >foo]", + "[quote >bar]"); + + // Multi-line blockquote followed by normal paragraph (non-lazy mode) + MT("multiBlockquoteThenParagraph", + "[quote >foo]", + "[quote >bar]", + "", + "hello"); + + // Check list types + + MT("listAsterisk", + "[string * foo]", + "[string * bar]"); + + MT("listPlus", + "[string + foo]", + "[string + bar]"); + + MT("listDash", + "[string - foo]", + "[string - bar]"); + + MT("listNumber", + "[string 1. foo]", + "[string 2. bar]"); + + // Formatting in lists (*) + MT("listAsteriskFormatting", + "[string * ][string&em *foo*][string bar]", + "[string * ][string&strong **foo**][string bar]", + "[string * ][string&strong **][string&emstrong *foo**][string&em *][string bar]", + "[string * ][string&comment `foo`][string bar]"); + + // Formatting in lists (+) + MT("listPlusFormatting", + "[string + ][string&em *foo*][string bar]", + "[string + ][string&strong **foo**][string bar]", + "[string + ][string&strong **][string&emstrong *foo**][string&em *][string bar]", + "[string + ][string&comment `foo`][string bar]"); + + // Formatting in lists (-) + MT("listDashFormatting", + "[string - ][string&em *foo*][string bar]", + "[string - ][string&strong **foo**][string bar]", + "[string - ][string&strong **][string&emstrong *foo**][string&em *][string bar]", + "[string - ][string&comment `foo`][string bar]"); + + // Formatting in lists (1.) + MT("listNumberFormatting", + "[string 1. ][string&em *foo*][string bar]", + "[string 2. ][string&strong **foo**][string bar]", + "[string 3. ][string&strong **][string&emstrong *foo**][string&em *][string bar]", + "[string 4. ][string&comment `foo`][string bar]"); + + // Paragraph lists + MT("listParagraph", + "[string * foo]", + "", + "[string * bar]"); + + // Multi-paragraph lists + // + // 4 spaces + MT("listMultiParagraph", + "[string * foo]", + "", + "[string * bar]", + "", + " [string hello]"); + + // 4 spaces, extra blank lines (should still be list, per Dingus) + MT("listMultiParagraphExtra", + "[string * foo]", + "", + "[string * bar]", + "", + " [string hello]"); + + // 4 spaces, plus 1 space (should still be list, per Dingus) + MT("listMultiParagraphExtraSpace", + "[string * foo]", + "", + "[string * bar]", + "", + " [string hello]", + "", + " [string world]"); + + // 1 tab + MT("listTab", + "[string * foo]", + "", + "[string * bar]", + "", + "\t[string hello]"); + + // No indent + MT("listNoIndent", + "[string * foo]", + "", + "[string * bar]", + "", + "hello"); + + // Blockquote + MT("blockquote", + "[string * foo]", + "", + "[string * bar]", + "", + " [string"e > hello]"); + + // Code block + MT("blockquoteCode", + "[string * foo]", + "", + "[string * bar]", + "", + " [comment > hello]", + "", + " [string world]"); + + // Code block followed by text + MT("blockquoteCodeText", + "[string * foo]", + "", + " [string bar]", + "", + " [comment hello]", + "", + " [string world]"); + + // Nested list + + MT("listAsteriskNested", + "[string * foo]", + "", + " [string * bar]"); + + MT("listPlusNested", + "[string + foo]", + "", + " [string + bar]"); + + MT("listDashNested", + "[string - foo]", + "", + " [string - bar]"); + + MT("listNumberNested", + "[string 1. foo]", + "", + " [string 2. bar]"); + + MT("listMixed", + "[string * foo]", + "", + " [string + bar]", + "", + " [string - hello]", + "", + " [string 1. world]"); + + MT("listBlockquote", + "[string * foo]", + "", + " [string + bar]", + "", + " [quote&string > hello]"); + + MT("listCode", + "[string * foo]", + "", + " [string + bar]", + "", + " [comment hello]"); + + // Code with internal indentation + MT("listCodeIndentation", + "[string * foo]", + "", + " [comment bar]", + " [comment hello]", + " [comment world]", + " [comment foo]", + " [string bar]"); + + // Code followed by text + MT("listCodeText", + "[string * 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 ---------------------------------------]"); + + // Inline link with title + MT("linkTitle", + "[link [[foo]]][string (http://example.com/ \"bar\")] hello"); + + // Inline link without title + MT("linkNoTitle", + "[link [[foo]]][string (http://example.com/)] bar"); + + // Inline link with image + MT("linkImage", + "[link [[][tag ![[foo]]][string (http://example.com/)][link ]]][string (http://example.com/)] bar"); + + // Inline link with Em + MT("linkEm", + "[link [[][link&em *foo*][link ]]][string (http://example.com/)] bar"); + + // Inline link with Strong + MT("linkStrong", + "[link [[][link&strong **foo**][link ]]][string (http://example.com/)] bar"); + + // Inline link with EmStrong + MT("linkEmStrong", + "[link [[][link&strong **][link&emstrong *foo**][link&em *][link ]]][string (http://example.com/)] bar"); + + // Image with title + MT("imageTitle", + "[tag ![[foo]]][string (http://example.com/ \"bar\")] hello"); + + // Image without title + MT("imageNoTitle", + "[tag ![[foo]]][string (http://example.com/)] bar"); + + // Image with asterisks + MT("imageAsterisks", + "[tag ![[*foo*]]][string (http://example.com/)] 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", + "[[foo]] (bar)"); + + // Reference-style links + MT("linkReference", + "[link [[foo]]][string [[bar]]] hello"); + + // Reference-style links with Em + MT("linkReferenceEm", + "[link [[][link&em *foo*][link ]]][string [[bar]]] hello"); + + // Reference-style links with Strong + MT("linkReferenceStrong", + "[link [[][link&strong **foo**][link ]]][string [[bar]]] hello"); + + // Reference-style links with EmStrong + MT("linkReferenceEmStrong", + "[link [[][link&strong **][link&emstrong *foo**][link&em *][link ]]][string [[bar]]] hello"); + + // Reference-style links with optional space separator (per docuentation) + // "You can optionally use a space to separate the sets of brackets" + MT("linkReferenceSpace", + "[link [[foo]]] [string [[bar]]] hello"); + + // Should only allow a single space ("...use *a* space...") + MT("linkReferenceDoubleSpace", + "[[foo]] [[bar]] hello"); + + // Reference-style links with implicit link name + MT("linkImplicit", + "[link [[foo]]][string [[]]] 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 http://example.com/]"); + + MT("labelIndented", + " [link [[foo]]:] [string http://example.com/]"); + + MT("labelSpaceTitle", + "[link [[foo bar]]:] [string http://example.com/ \"hello\"]"); + + MT("labelDoubleTitle", + "[link [[foo bar]]:] [string http://example.com/ \"hello\"] \"world\""); + + MT("labelTitleDoubleQuotes", + "[link [[foo]]:] [string http://example.com/ \"bar\"]"); + + MT("labelTitleSingleQuotes", + "[link [[foo]]:] [string http://example.com/ 'bar']"); + + MT("labelTitleParenthese", + "[link [[foo]]:] [string http://example.com/ (bar)]"); + + MT("labelTitleInvalid", + "[link [[foo]]:] [string http://example.com/] bar"); + + MT("labelLinkAngleBrackets", + "[link [[foo]]:] [string \"bar\"]"); + + MT("labelTitleNextDoubleQuotes", + "[link [[foo]]:] [string http://example.com/]", + "[string \"bar\"] hello"); + + MT("labelTitleNextSingleQuotes", + "[link [[foo]]:] [string http://example.com/]", + "[string 'bar'] hello"); + + MT("labelTitleNextParenthese", + "[link [[foo]]:] [string http://example.com/]", + "[string (bar)] hello"); + + MT("labelTitleNextMixed", + "[link [[foo]]:] [string http://example.com/]", + "(bar\" hello"); + + MT("linkWeb", + "[link ] foo"); + + MT("linkEmail", + "[link ] foo"); + + MT("emAsterisk", + "[em *foo*] bar"); + + MT("emUnderscore", + "[em _foo_] bar"); + + MT("emInWordAsterisk", + "foo[em *bar*]hello"); + + MT("emInWordUnderscore", + "foo[em _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"); + + // 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][emstrong **bar*][strong hello**] world"); + + MT("emStrongUnderscore", + "[em _foo][emstrong __bar_][strong hello__] world"); + + // "...same character must be used to open and close an emphasis span."" + MT("emStrongMixed", + "[em _foo][emstrong **bar*hello__ world]"); + + MT("emStrongMixed", + "[em *foo][emstrong __bar_hello** world]"); + + // 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"); +})(); diff --git a/lib/codemirror-3.1/mode/meta.js b/lib/codemirror-3.1/mode/meta.js new file mode 100644 index 0000000000000000000000000000000000000000..5d2ee0ffe9681939bda7f8502aae6f29a70c53f8 --- /dev/null +++ b/lib/codemirror-3.1/mode/meta.js @@ -0,0 +1,72 @@ +CodeMirror.modeInfo = [ + {name: 'APL', mime: 'text/apl', mode: 'apl'}, + {name: 'Asterisk', mime: 'text/x-asterisk', mode: 'asterisk'}, + {name: 'C', mime: 'text/x-csrc', mode: 'clike'}, + {name: 'C++', mime: 'text/x-c++src', mode: 'clike'}, + {name: 'Java', mime: 'text/x-java', mode: 'clike'}, + {name: 'C#', mime: 'text/x-csharp', mode: 'clike'}, + {name: 'Scala', mime: 'text/x-scala', mode: 'clike'}, + {name: 'Clojure', mime: 'text/x-clojure', mode: 'clojure'}, + {name: 'CoffeeScript', mime: 'text/x-coffeescript', mode: 'coffeescript'}, + {name: 'Common Lisp', mime: 'text/x-common-lisp', mode: 'commonlisp'}, + {name: 'CSS', mime: 'text/css', mode: 'css'}, + {name: 'D', mime: 'text/x-d', mode: 'd'}, + {name: 'diff', mime: 'text/x-diff', mode: 'diff'}, + {name: 'ECL', mime: 'text/x-ecl', mode: 'ecl'}, + {name: 'Erlang', mime: 'text/x-erlang', mode: 'erlang'}, + {name: 'GitHub Flavored Markdown', mode: 'gfm'}, + {name: 'GO', mime: 'text/x-go', mode: 'go'}, + {name: 'Groovy', mime: 'text/x-groovy', mode: 'groovy'}, + {name: 'Haskell', mime: 'text/x-haskell', mode: 'haskell'}, + {name: 'Haxe', mime: 'text/x-haxe', mode: 'haxe'}, + {name: 'ASP.NET', mime: 'application/x-aspx', mode: 'htmlembedded'}, + {name: 'Embedded Javascript', mime: 'application/x-ejs', mode: 'htmlembedded'}, + {name: 'JavaServer Pages', mime: 'application/x-jsp', mode: 'htmlembedded'}, + {name: 'HTML', mime: 'text/html', mode: 'htmlmixed'}, + {name: 'HTTP', mime: 'message/http', mode: 'http'}, + {name: 'JavaScript', mime: 'text/javascript', mode: 'javascript'}, + {name: 'JSON', mime: 'application/json', mode: 'javascript'}, + {name: 'TypeScript', mime: 'application/typescript', mode: 'javascript'}, + {name: 'Jinja2', mime: 'jinja2', mode: 'jinja2'}, + {name: 'LESS', mime: 'text/x-less', mode: 'less'}, + {name: 'Lua', mime: 'text/x-lua', mode: 'lua'}, + {name: 'Markdown (GitHub-flavour)', mime: 'text/x-markdown', mode: 'markdown'}, + {name: 'NTriples', mime: 'text/n-triples', mode: 'ntriples'}, + {name: 'OCaml', mime: 'text/x-ocaml', mode: 'ocaml'}, + {name: 'Pascal', mime: 'text/x-pascal', mode: 'pascal'}, + {name: 'Perl', mime: 'text/x-perl', mode: 'perl'}, + {name: 'PHP', mime: 'text/x-php', mode: 'php'}, + {name: 'PHP(HTML)', mime: 'application/x-httpd-php', mode: 'php'}, + {name: 'Pig', mime: 'text/x-pig', mode: 'pig'}, + {name: 'Plain Text', mime: 'text/plain', mode: 'null'}, + {name: 'Properties files', mime: 'text/x-properties', mode: 'clike'}, + {name: 'Python', mime: 'text/x-python', mode: 'python'}, + {name: 'R', mime: 'text/x-rsrc', mode: 'r'}, + {name: 'reStructuredText', mime: 'text/x-rst', mode: 'rst'}, + {name: 'Ruby', mime: 'text/x-ruby', mode: 'ruby'}, + {name: 'Rust', mime: 'text/x-rustsrc', mode: 'rust'}, + {name: 'Sass', mime: 'text/x-sass', mode: 'sass'}, + {name: 'Scheme', mime: 'text/x-scheme', mode: 'scheme'}, + {name: 'Shell', mime: 'text/x-sh', mode: 'shell'}, + {name: 'Sieve', mime: 'application/sieve', mode: 'sieve'}, + {name: 'Smalltalk', mime: 'text/x-stsrc', mode: 'smalltalk'}, + {name: 'Smarty', mime: 'text/x-smarty', mode: 'smarty'}, + {name: 'SPARQL', mime: 'application/x-sparql-query', mode: 'sparql'}, + {name: 'SQL', mime: 'text/x-sql', mode: 'sql'}, + {name: 'MySQL', mime: 'text/x-mysql', mode: 'sql'}, + {name: 'MariaDB', mime: 'text/x-mariadb', mode: 'sql'}, + {name: 'PL/SQL', mime: 'text/x-plsql', mode: 'sql'}, + {name: 'sTeX', mime: 'text/x-stex', mode: 'stex'}, + {name: 'LaTeX', mime: 'text/x-latex', mode: 'stex'}, + {name: 'TiddlyWiki ', mime: 'text/x-tiddlywiki', mode: 'tiddlywiki'}, + {name: 'Tiki wiki', mime: 'text/tiki', mode: 'tiki'}, + {name: 'VB.NET', mime: 'text/x-vb', mode: 'vb'}, + {name: 'VBScript', mime: 'text/vbscript', mode: 'vbscript'}, + {name: 'Velocity', mime: 'text/velocity', mode: 'velocity'}, + {name: 'Verilog', mime: 'text/x-verilog', mode: 'verilog'}, + {name: 'XML', mime: 'application/xml', mode: 'xml'}, + {name: 'HTML', mime: 'text/html', mode: 'xml'}, + {name: 'XQuery', mime: 'application/xquery', mode: 'xquery'}, + {name: 'YAML', mime: 'text/x-yaml', mode: 'yaml'}, + {name: 'Z80', mime: 'text/x-z80', mode: 'z80'} +]; diff --git a/lib/codemirror-3.1/mode/mysql/index.html b/lib/codemirror-3.1/mode/mysql/index.html new file mode 100644 index 0000000000000000000000000000000000000000..41aeed12d89661c1fa9b69233318332c9fd0ef29 --- /dev/null +++ b/lib/codemirror-3.1/mode/mysql/index.html @@ -0,0 +1,43 @@ + + + + + CodeMirror: MySQL mode + + + + + + + +

CodeMirror: MySQL mode

+
+ + +

!! This mode is deprecated in favor of the generic SQL mode (which can be configured to handle MySQL).

+ +

MIME types defined: text/x-mysql.

+ + + diff --git a/lib/codemirror-3.1/mode/mysql/mysql.js b/lib/codemirror-3.1/mode/mysql/mysql.js new file mode 100644 index 0000000000000000000000000000000000000000..69d3f9952bd49ec1f7cf7d9ba35a592d41d73725 --- /dev/null +++ b/lib/codemirror-3.1/mode/mysql/mysql.js @@ -0,0 +1,203 @@ +/* + * MySQL Mode for CodeMirror 2 by MySQL-Tools + * @author James Thorne (partydroid) + * @link http://github.com/partydroid/MySQL-Tools + * @link http://mysqltools.org + * @version 02/Jan/2012 +*/ +CodeMirror.defineMode("mysql", 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", + "isblank", "isliteral", "union", "a"]); + var keywords = wordRegexp([ + ('ACCESSIBLE'),('ALTER'),('AS'),('BEFORE'),('BINARY'),('BY'),('CASE'),('CHARACTER'),('COLUMN'),('CONTINUE'),('CROSS'),('CURRENT_TIMESTAMP'),('DATABASE'),('DAY_MICROSECOND'),('DEC'),('DEFAULT'), + ('DESC'),('DISTINCT'),('DOUBLE'),('EACH'),('ENCLOSED'),('EXIT'),('FETCH'),('FLOAT8'),('FOREIGN'),('GRANT'),('HIGH_PRIORITY'),('HOUR_SECOND'),('IN'),('INNER'),('INSERT'),('INT2'),('INT8'), + ('INTO'),('JOIN'),('KILL'),('LEFT'),('LINEAR'),('LOCALTIME'),('LONG'),('LOOP'),('MATCH'),('MEDIUMTEXT'),('MINUTE_SECOND'),('NATURAL'),('NULL'),('OPTIMIZE'),('OR'),('OUTER'),('PRIMARY'), + ('RANGE'),('READ_WRITE'),('REGEXP'),('REPEAT'),('RESTRICT'),('RIGHT'),('SCHEMAS'),('SENSITIVE'),('SHOW'),('SPECIFIC'),('SQLSTATE'),('SQL_CALC_FOUND_ROWS'),('STARTING'),('TERMINATED'), + ('TINYINT'),('TRAILING'),('UNDO'),('UNLOCK'),('USAGE'),('UTC_DATE'),('VALUES'),('VARCHARACTER'),('WHERE'),('WRITE'),('ZEROFILL'),('ALL'),('AND'),('ASENSITIVE'),('BIGINT'),('BOTH'),('CASCADE'), + ('CHAR'),('COLLATE'),('CONSTRAINT'),('CREATE'),('CURRENT_TIME'),('CURSOR'),('DAY_HOUR'),('DAY_SECOND'),('DECLARE'),('DELETE'),('DETERMINISTIC'),('DIV'),('DUAL'),('ELSEIF'),('EXISTS'),('FALSE'), + ('FLOAT4'),('FORCE'),('FULLTEXT'),('HAVING'),('HOUR_MINUTE'),('IGNORE'),('INFILE'),('INSENSITIVE'),('INT1'),('INT4'),('INTERVAL'),('ITERATE'),('KEYS'),('LEAVE'),('LIMIT'),('LOAD'),('LOCK'), + ('LONGTEXT'),('MASTER_SSL_VERIFY_SERVER_CERT'),('MEDIUMINT'),('MINUTE_MICROSECOND'),('MODIFIES'),('NO_WRITE_TO_BINLOG'),('ON'),('OPTIONALLY'),('OUT'),('PRECISION'),('PURGE'),('READS'), + ('REFERENCES'),('RENAME'),('REQUIRE'),('REVOKE'),('SCHEMA'),('SELECT'),('SET'),('SPATIAL'),('SQLEXCEPTION'),('SQL_BIG_RESULT'),('SSL'),('TABLE'),('TINYBLOB'),('TO'),('TRUE'),('UNIQUE'), + ('UPDATE'),('USING'),('UTC_TIMESTAMP'),('VARCHAR'),('WHEN'),('WITH'),('YEAR_MONTH'),('ADD'),('ANALYZE'),('ASC'),('BETWEEN'),('BLOB'),('CALL'),('CHANGE'),('CHECK'),('CONDITION'),('CONVERT'), + ('CURRENT_DATE'),('CURRENT_USER'),('DATABASES'),('DAY_MINUTE'),('DECIMAL'),('DELAYED'),('DESCRIBE'),('DISTINCTROW'),('DROP'),('ELSE'),('ESCAPED'),('EXPLAIN'),('FLOAT'),('FOR'),('FROM'), + ('GROUP'),('HOUR_MICROSECOND'),('IF'),('INDEX'),('INOUT'),('INT'),('INT3'),('INTEGER'),('IS'),('KEY'),('LEADING'),('LIKE'),('LINES'),('LOCALTIMESTAMP'),('LONGBLOB'),('LOW_PRIORITY'), + ('MEDIUMBLOB'),('MIDDLEINT'),('MOD'),('NOT'),('NUMERIC'),('OPTION'),('ORDER'),('OUTFILE'),('PROCEDURE'),('READ'),('REAL'),('RELEASE'),('REPLACE'),('RETURN'),('RLIKE'),('SECOND_MICROSECOND'), + ('SEPARATOR'),('SMALLINT'),('SQL'),('SQLWARNING'),('SQL_SMALL_RESULT'),('STRAIGHT_JOIN'),('THEN'),('TINYTEXT'),('TRIGGER'),('UNION'),('UNSIGNED'),('USE'),('UTC_TIME'),('VARBINARY'),('VARYING'), + ('WHILE'),('XOR'),('FULL'),('COLUMNS'),('MIN'),('MAX'),('STDEV'),('COUNT') + ]); + var operatorChars = /[*+\-<>=&|]/; + + function tokenBase(stream, state) { + var ch = stream.next(); + curPunc = null; + if (ch == "$" || ch == "?") { + 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 (ch == "`") { + state.tokenize = tokenOpLiteral(ch); + return state.tokenize(stream, state); + } + else if (/[{}\(\),\.;\[\]]/.test(ch)) { + curPunc = ch; + return null; + } + else if (ch == "-" && stream.eat("-")) { + stream.skipToEnd(); + return "comment"; + } + else if (ch == "/" && stream.eat("*")) { + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } + else if (operatorChars.test(ch)) { + stream.eatWhile(operatorChars); + return null; + } + else if (ch == ":") { + stream.eatWhile(/[\w\d\._\-]/); + return "atom"; + } + else { + stream.eatWhile(/[_\w\d]/); + if (stream.eat(":")) { + stream.eatWhile(/[\w\d_\-]/); + return "atom"; + } + var word = stream.current(); + if (ops.test(word)) + return null; + 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 tokenOpLiteral(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 "variable-2"; + }; + } + + function tokenComment(stream, state) { + for (;;) { + if (stream.skipTo("*")) { + stream.next(); + if (stream.eat("/")) { + state.tokenize = tokenBase; + break; + } + } else { + stream.skipToEnd(); + break; + } + } + return "comment"; + } + + + 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-mysql", "mysql"); diff --git a/lib/codemirror-3.1/mode/ntriples/index.html b/lib/codemirror-3.1/mode/ntriples/index.html new file mode 100644 index 0000000000000000000000000000000000000000..052a53d86a40b7de923f6507c38edc2db190c7b4 --- /dev/null +++ b/lib/codemirror-3.1/mode/ntriples/index.html @@ -0,0 +1,33 @@ + + + + + CodeMirror: NTriples mode + + + + + + + +

CodeMirror: NTriples mode

+
+ +
+ + +

MIME types defined: text/n-triples.

+ + diff --git a/lib/codemirror-3.1/mode/ntriples/ntriples.js b/lib/codemirror-3.1/mode/ntriples/ntriples.js new file mode 100644 index 0000000000000000000000000000000000000000..ced8645169e1954b059aead216c6d0f06b55fa5f --- /dev/null +++ b/lib/codemirror-3.1/mode/ntriples/ntriples.js @@ -0,0 +1,170 @@ +/********************************************************** +* This script provides syntax highlighting support for +* the Ntriples format. +* Ntriples format specification: +* http://www.w3.org/TR/rdf-testcases/#ntriples +***********************************************************/ + +/* + 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 + } +*/ +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); + } + } + }; +}); + +CodeMirror.defineMIME("text/n-triples", "ntriples"); diff --git a/lib/codemirror-3.1/mode/ocaml/index.html b/lib/codemirror-3.1/mode/ocaml/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c10a84fade08619fa363cee6beb9ddbb08af582c --- /dev/null +++ b/lib/codemirror-3.1/mode/ocaml/index.html @@ -0,0 +1,131 @@ + + +CodeMirror: OCaml mode + + + + + + + + + + +

CodeMirror: OCaml mode

+ + + + + +

MIME types defined: text/x-ocaml.

diff --git a/lib/codemirror-3.1/mode/ocaml/ocaml.js b/lib/codemirror-3.1/mode/ocaml/ocaml.js new file mode 100644 index 0000000000000000000000000000000000000000..2ce3fb8f0c1f7d627dbfb40db7984786afecc733 --- /dev/null +++ b/lib/codemirror-3.1/mode/ocaml/ocaml.js @@ -0,0 +1,113 @@ +CodeMirror.defineMode('ocaml', function() { + + var words = { + 'true': 'atom', + 'false': 'atom', + 'let': 'keyword', + 'rec': 'keyword', + 'in': 'keyword', + 'of': 'keyword', + 'and': 'keyword', + 'succ': 'keyword', + 'if': 'keyword', + 'then': 'keyword', + 'else': 'keyword', + 'for': 'keyword', + 'to': 'keyword', + 'while': 'keyword', + 'do': 'keyword', + 'done': 'keyword', + 'fun': 'keyword', + 'function': 'keyword', + 'val': 'keyword', + 'type': 'keyword', + 'mutable': 'keyword', + 'match': 'keyword', + 'with': 'keyword', + 'try': 'keyword', + 'raise': 'keyword', + 'begin': 'keyword', + 'end': 'keyword', + 'open': 'builtin', + 'trace': 'builtin', + 'ignore': 'builtin', + 'exit': 'builtin', + 'print_string': 'builtin', + 'print_endline': 'builtin' + }; + + function tokenBase(stream, state) { + var ch = stream.next(); + + if (ch === '"') { + state.tokenize = tokenString; + return state.tokenize(stream, state); + } + if (ch === '(') { + if (stream.eat('*')) { + state.commentLevel++; + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } + } + if (ch === '~') { + stream.eatWhile(/\w/); + return 'variable-2'; + } + if (ch === '`') { + stream.eatWhile(/\w/); + return 'quote'; + } + if (/\d/.test(ch)) { + stream.eatWhile(/[\d]/); + if (stream.eat('.')) { + stream.eatWhile(/[\d]/); + } + return 'number'; + } + if ( /[+\-*&%=<>!?|]/.test(ch)) { + return 'operator'; + } + stream.eatWhile(/\w/); + var cur = stream.current(); + return words[cur] || 'variable'; + } + + 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); + } + }; +}); + +CodeMirror.defineMIME('text/x-ocaml', 'ocaml'); diff --git a/lib/codemirror-3.1/mode/pascal/LICENSE b/lib/codemirror-3.1/mode/pascal/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8e3747e74808d9c135b4afff23ce215d074d9973 --- /dev/null +++ b/lib/codemirror-3.1/mode/pascal/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2011 souceLair + +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. diff --git a/lib/codemirror-3.1/mode/pascal/index.html b/lib/codemirror-3.1/mode/pascal/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b3016afb10cbd2bb30b33509e096335cf219e010 --- /dev/null +++ b/lib/codemirror-3.1/mode/pascal/index.html @@ -0,0 +1,48 @@ + + + + + CodeMirror: Pascal mode + + + + + + + +

CodeMirror: Pascal mode

+ +
+ + + +

MIME types defined: text/x-pascal.

+ + diff --git a/lib/codemirror-3.1/mode/pascal/pascal.js b/lib/codemirror-3.1/mode/pascal/pascal.js new file mode 100644 index 0000000000000000000000000000000000000000..09d9b0617b1b254cb15a9be7da16e7c61bf0b946 --- /dev/null +++ b/lib/codemirror-3.1/mode/pascal/pascal.js @@ -0,0 +1,94 @@ +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("and array begin case const div do downto else end file for forward integer " + + "boolean char function goto if in label mod nil not of or packed procedure " + + "program record repeat set string then to type until var while with"); + 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"); diff --git a/lib/codemirror-3.1/mode/perl/LICENSE b/lib/codemirror-3.1/mode/perl/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..96f4115af8a96e1fb2ab78d5ac0d9490f16c7469 --- /dev/null +++ b/lib/codemirror-3.1/mode/perl/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2011 by Sabaca under the MIT license. + +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. diff --git a/lib/codemirror-3.1/mode/perl/index.html b/lib/codemirror-3.1/mode/perl/index.html new file mode 100644 index 0000000000000000000000000000000000000000..13c7af64d3c79c51f7737915e7e44c844b3d26be --- /dev/null +++ b/lib/codemirror-3.1/mode/perl/index.html @@ -0,0 +1,62 @@ + + + + + CodeMirror: Perl mode + + + + + + + +

CodeMirror: Perl mode

+ +
+ + + +

MIME types defined: text/x-perl.

+ + diff --git a/lib/codemirror-3.1/mode/perl/perl.js b/lib/codemirror-3.1/mode/perl/perl.js new file mode 100644 index 0000000000000000000000000000000000000000..52361c6107a42f0e674e207a41e45c97a8f738c4 --- /dev/null +++ b/lib/codemirror-3.1/mode/perl/perl.js @@ -0,0 +1,816 @@ +// 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) +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 owership 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)){ + stream.eatSuffix(1); + return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}} + else if(c=="q"){ + c=stream.look(1); + if(c=="("){ + stream.eatSuffix(2); + return tokenChain(stream,state,[")"],"string");} + if(c=="["){ + stream.eatSuffix(2); + return tokenChain(stream,state,["]"],"string");} + if(c=="{"){ + stream.eatSuffix(2); + return tokenChain(stream,state,["}"],"string");} + if(c=="<"){ + stream.eatSuffix(2); + return tokenChain(stream,state,[">"],"string");} + if(/[\^'"!~\/]/.test(c)){ + stream.eatSuffix(1); + return tokenChain(stream,state,[stream.eat(c)],"string");}} + else if(c=="w"){ + c=stream.look(1); + if(c=="("){ + stream.eatSuffix(2); + return tokenChain(stream,state,[")"],"bracket");} + if(c=="["){ + stream.eatSuffix(2); + return tokenChain(stream,state,["]"],"bracket");} + if(c=="{"){ + stream.eatSuffix(2); + return tokenChain(stream,state,["}"],"bracket");} + if(c=="<"){ + stream.eatSuffix(2); + return tokenChain(stream,state,[">"],"bracket");} + if(/[\^'"!~\/]/.test(c)){ + stream.eatSuffix(1); + return tokenChain(stream,state,[stream.eat(c)],"bracket");}} + else if(c=="r"){ + c=stream.look(1); + if(c=="("){ + stream.eatSuffix(2); + return tokenChain(stream,state,[")"],RXstyle,RXmodifiers);} + if(c=="["){ + stream.eatSuffix(2); + return tokenChain(stream,state,["]"],RXstyle,RXmodifiers);} + if(c=="{"){ + stream.eatSuffix(2); + return tokenChain(stream,state,["}"],RXstyle,RXmodifiers);} + if(c=="<"){ + stream.eatSuffix(2); + return tokenChain(stream,state,[">"],RXstyle,RXmodifiers);} + if(/[\^'"!~\/]/.test(c)){ + stream.eatSuffix(1); + return tokenChain(stream,state,[stream.eat(c)],RXstyle,RXmodifiers);}} + else if(/[\^'"!~\/(\[{<]/.test(c)){ + if(c=="("){ + stream.eatSuffix(1); + return tokenChain(stream,state,[")"],"string");} + if(c=="["){ + stream.eatSuffix(1); + return tokenChain(stream,state,["]"],"string");} + if(c=="{"){ + stream.eatSuffix(1); + return tokenChain(stream,state,["}"],"string");} + if(c=="<"){ + stream.eatSuffix(1); + return tokenChain(stream,state,[">"],"string");} + if(/[\^'"!~\/]/.test(c)){ + return tokenChain(stream,state,[stream.eat(c)],"string");}}}} + if(ch=="m"){ + var c=stream.look(-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(stream.look(-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(stream.look(-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(stream.look(-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(stream.prefix())) + 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(stream.look(-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(stream.look(-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(stream.suffix(6)=="_END__"){ + return tokenChain(stream,state,['\0'],"comment");} + else if(stream.suffix(7)=="_DATA__"){ + return tokenChain(stream,state,['\0'],"variable-2");} + else if(stream.suffix(7)=="_C__"){ + return tokenChain(stream,state,['\0'],"string");}}} + if(/\w/.test(ch)){ + var p=stream.pos; + if(stream.look(-2)=="{"&&(stream.look(0)=="}"||stream.eatWhile(/\w/)&&stream.look(0)=="}")) + return "string"; + else + stream.pos=p;} + if(/[A-Z]/.test(ch)){ + var l=stream.look(-2); + var p=stream.pos; + stream.eatWhile(/[A-Z_]/); + if(/[\da-z]/.test(stream.look(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=stream.look(-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);}, + electricChars:"{}"};}); + +CodeMirror.defineMIME("text/x-perl", "perl"); + +// it's like "peek", but need for look-ahead or look-behind if index < 0 +CodeMirror.StringStream.prototype.look=function(c){ + return this.string.charAt(this.pos+(c||0));}; + +// return a part of prefix of current stream from current position +CodeMirror.StringStream.prototype.prefix=function(c){ + if(c){ + var x=this.pos-c; + return this.string.substr((x>=0?x:0),c);} + else{ + return this.string.substr(0,this.pos-1);}}; + +// return a part of suffix of current stream from current position +CodeMirror.StringStream.prototype.suffix=function(c){ + var y=this.string.length; + var x=y-this.pos+1; + return this.string.substr(this.pos,(c&&c=(y=this.string.length-1)) + this.pos=y; + else + this.pos=x;}; diff --git a/lib/codemirror-3.1/mode/php/index.html b/lib/codemirror-3.1/mode/php/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3d4c336ce0f84ef884f84d7727b2ec9cebf30b44 --- /dev/null +++ b/lib/codemirror-3.1/mode/php/index.html @@ -0,0 +1,51 @@ + + + + + CodeMirror: PHP mode + + + + + + + + + + + + + +

CodeMirror: 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).

+ + diff --git a/lib/codemirror-3.1/mode/php/php.js b/lib/codemirror-3.1/mode/php/php.js new file mode 100644 index 0000000000000000000000000000000000000000..56497ed4360f6319f9df8208ce5c176a378d1f9a --- /dev/null +++ b/lib/codemirror-3.1/mode/php/php.js @@ -0,0 +1,129 @@ +(function() { + function keywords(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + function heredoc(delim) { + return function(stream, state) { + if (stream.match(delim)) state.tokenize = null; + else stream.skipToEnd(); + return "string"; + }; + } + var phpConfig = { + name: "clike", + keywords: keywords("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"), + blockKeywords: keywords("catch do else elseif for foreach if switch try while"), + atoms: keywords("true false null TRUE FALSE NULL __CLASS__ __DIR__ __FILE__ __LINE__ __METHOD__ __FUNCTION__ __NAMESPACE__"), + builtin: keywords("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 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 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 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 echo print global static exit array empty eval isset unset die include require include_once require_once"), + multiLineStrings: true, + hooks: { + "$": function(stream) { + stream.eatWhile(/[\w\$_]/); + return "variable-2"; + }, + "<": function(stream, state) { + if (stream.match(/<", false)) stream.next(); + return "comment"; + }, + "/": function(stream) { + if (stream.eat("/")) { + while (!stream.eol() && !stream.match("?>", false)) stream.next(); + return "comment"; + } + return false; + } + } + }; + + CodeMirror.defineMode("php", function(config, parserConfig) { + var htmlMode = CodeMirror.getMode(config, "text/html"); + var phpMode = CodeMirror.getMode(config, phpConfig); + + function dispatch(stream, state) { + var isPHP = state.curMode == phpMode; + if (stream.sol() && state.pending != '"') state.pending = null; + if (!isPHP) { + if (stream.match(/^<\?\w*/)) { + state.curMode = phpMode; + state.curState = state.php; + return "meta"; + } + if (state.pending == '"') { + while (!stream.eol() && stream.next() != '"') {} + 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); + } + state.pending = null; + var cur = stream.current(), openPHP = cur.search(/<\?/); + if (openPHP != -1) { + if (style == "string" && /\"$/.test(cur) && !/\?>/.test(cur)) state.pending = '"'; + 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; + return "meta"; + } else { + return phpMode.token(stream, state.curState); + } + } + + return { + startState: function() { + var html = CodeMirror.startState(htmlMode), php = CodeMirror.startState(phpMode); + 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 = 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) { + if ((state.curMode != phpMode && /^\s*<\//.test(textAfter)) || + (state.curMode == phpMode && /^\?>/.test(textAfter))) + return htmlMode.indent(state.html, textAfter); + return state.curMode.indent(state.curState, textAfter); + }, + + electricChars: "/{}:", + + 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); +})(); diff --git a/lib/codemirror-3.1/mode/pig/index.html b/lib/codemirror-3.1/mode/pig/index.html new file mode 100644 index 0000000000000000000000000000000000000000..1b0c60267f830c3bd924dc32a6f70452645b442e --- /dev/null +++ b/lib/codemirror-3.1/mode/pig/index.html @@ -0,0 +1,42 @@ + + + + + CodeMirror: Pig Latin mode + + + + + + + +

CodeMirror: Pig Latin mode

+ +
+ + + +

+ Simple mode that handles Pig Latin language. +

+ +

MIME type defined: text/x-pig + (PIG code) + diff --git a/lib/codemirror-3.1/mode/pig/pig.js b/lib/codemirror-3.1/mode/pig/pig.js new file mode 100644 index 0000000000000000000000000000000000000000..f8818a9b66b88bc294d1f34e8d4e109f88183d01 --- /dev/null +++ b/lib/codemirror-3.1/mode/pig/pig.js @@ -0,0 +1,171 @@ +/* + * 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. +*/ +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); + } + + var type; + function ret(tp, style) { + type = tp; + return style; + } + + function tokenComment(stream, state) { + var isEnd = false; + var ch; + while(ch = stream.next()) { + if(ch == "/" && isEnd) { + state.tokenize = tokenBase; + break; + } + isEnd = (ch == "*"); + } + return ret("comment", "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 ret("string", "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 ret(ch); + // is it a number? + else if(/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return ret("number", "number"); + } + // multi line comment or operator + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, tokenComment); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + } + // single line comment or operator + else if (ch=="-") { + if(stream.eat("-")){ + stream.skipToEnd(); + return ret("comment", "comment"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + } + // is it an operator + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + else { + // get the while word + stream.eatWhile(/[\w\$_]/); + // is it one of the listed keywords? + if (keywords && keywords.propertyIsEnumerable(stream.current().toUpperCase())) { + if (stream.eat(")") || stream.eat(".")) { + //keywords can be used as variables like flatten(group), group.$0 etc.. + } + else { + return ("keyword", "keyword"); + } + } + // is it one of the builtin functions? + if (builtins && builtins.propertyIsEnumerable(stream.current().toUpperCase())) + { + return ("keyword", "variable-2"); + } + // is it one of the listed types? + if (types && types.propertyIsEnumerable(stream.current().toUpperCase())) + return ("keyword", "variable-3"); + // default is a 'variable' + return ret("variable", "pig-word"); + } + } + + // 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 "; + + // 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) + }); +}()); diff --git a/lib/codemirror-3.1/mode/plsql/index.html b/lib/codemirror-3.1/mode/plsql/index.html new file mode 100644 index 0000000000000000000000000000000000000000..52e60710d56b716714e971405b05453d505aa09c --- /dev/null +++ b/lib/codemirror-3.1/mode/plsql/index.html @@ -0,0 +1,64 @@ + + + + + CodeMirror: Oracle PL/SQL mode + + + + + + + +

CodeMirror: Oracle PL/SQL mode

+ +
+ + + +

!! This mode is deprecated in favor of the generic SQL mode (which can be configured to handle PL/SQL).

+ +

+ Simple mode that handles Oracle PL/SQL language (and Oracle SQL, of course). +

+ +

MIME type defined: text/x-plsql + (PLSQL code) + diff --git a/lib/codemirror-3.1/mode/plsql/plsql.js b/lib/codemirror-3.1/mode/plsql/plsql.js new file mode 100644 index 0000000000000000000000000000000000000000..df119baee195b6bba14529dcf2491761e51547cc --- /dev/null +++ b/lib/codemirror-3.1/mode/plsql/plsql.js @@ -0,0 +1,216 @@ +CodeMirror.defineMode("plsql", function(_config, parserConfig) { + var keywords = parserConfig.keywords, + functions = parserConfig.functions, + types = parserConfig.types, + sqlplus = parserConfig.sqlplus, + multiLineStrings = parserConfig.multiLineStrings; + var isOperatorChar = /[+\-*&%=<>!?:\/|]/; + function chain(stream, state, f) { + state.tokenize = f; + return f(stream, state); + } + + var type; + function ret(tp, style) { + type = tp; + return style; + } + + function tokenBase(stream, state) { + var ch = stream.next(); + // start of string? + if (ch == '"' || ch == "'") + return chain(stream, state, tokenString(ch)); + // is it one of the special signs []{}().,;? Seperator? + else if (/[\[\]{}\(\),;\.]/.test(ch)) + return ret(ch); + // start of a number value? + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return ret("number", "number"); + } + // multi line comment or simple operator? + else if (ch == "/") { + if (stream.eat("*")) { + return chain(stream, state, tokenComment); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + } + // single line comment or simple operator? + else if (ch == "-") { + if (stream.eat("-")) { + stream.skipToEnd(); + return ret("comment", "comment"); + } + else { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + } + // pl/sql variable? + else if (ch == "@" || ch == "$") { + stream.eatWhile(/[\w\d\$_]/); + return ret("word", "variable"); + } + // is it a operator? + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return ret("operator", "operator"); + } + else { + // get the whole word + stream.eatWhile(/[\w\$_]/); + // is it one of the listed keywords? + if (keywords && keywords.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "keyword"); + // is it one of the listed functions? + if (functions && functions.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "builtin"); + // is it one of the listed types? + if (types && types.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-2"); + // is it one of the listed sqlplus keywords? + if (sqlplus && sqlplus.propertyIsEnumerable(stream.current().toLowerCase())) return ret("keyword", "variable-3"); + // default: just a "variable" + return ret("word", "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 = tokenBase; + return ret("string", "plsql-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", "plsql-comment"); + } + + // 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; + } + var cKeywords = "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 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 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"; + + var cFunctions = "abs acos add_months ascii asin atan atan2 average " + + "bfilename " + + "ceil chartorowid chr concat convert cos cosh count " + + "decode deref dual dump dup_val_on_index " + + "empty error exp " + + "false floor found " + + "glb greatest " + + "hextoraw " + + "initcap instr instrb isopen " + + "last_day least lenght lenghtb ln lower lpad ltrim lub " + + "make_ref max min mod months_between " + + "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 nvl " + + "others " + + "power " + + "rawtohex reftohex round rowcount rowidtochar rpad rtrim " + + "sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate " + + "tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc " + + "uid upper user userenv " + + "variance vsize"; + + var cTypes = "bfile blob " + + "character clob " + + "dec " + + "float " + + "int integer " + + "mlslabel " + + "natural naturaln nchar nclob number numeric nvarchar2 " + + "real rowtype " + + "signtype smallint string " + + "varchar varchar2"; + + var cSqlplus = "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"; + + CodeMirror.defineMIME("text/x-plsql", { + name: "plsql", + keywords: keywords(cKeywords), + functions: keywords(cFunctions), + types: keywords(cTypes), + sqlplus: keywords(cSqlplus) + }); +}()); diff --git a/lib/codemirror-3.1/mode/properties/index.html b/lib/codemirror-3.1/mode/properties/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e21e02abd28d5e5d813f73c9fb1ad1da0b5ce350 --- /dev/null +++ b/lib/codemirror-3.1/mode/properties/index.html @@ -0,0 +1,41 @@ + + + + + CodeMirror: Properties files mode + + + + + + + +

CodeMirror: Properties files mode

+
+ + +

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

+ + + diff --git a/lib/codemirror-3.1/mode/properties/properties.js b/lib/codemirror-3.1/mode/properties/properties.js new file mode 100644 index 0000000000000000000000000000000000000000..d3a13c765dca5afbd2b8a69ebef4017033bdd68b --- /dev/null +++ b/lib/codemirror-3.1/mode/properties/properties.js @@ -0,0 +1,63 @@ +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.next() !== "u") { // u = Unicode sequence \u1234 + // 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"); diff --git a/lib/codemirror-3.1/mode/python/LICENSE.txt b/lib/codemirror-3.1/mode/python/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..918866b42a7709e69143605918c4adc30863bbdd --- /dev/null +++ b/lib/codemirror-3.1/mode/python/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2010 Timothy Farrell + +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. \ No newline at end of file diff --git a/lib/codemirror-3.1/mode/python/index.html b/lib/codemirror-3.1/mode/python/index.html new file mode 100644 index 0000000000000000000000000000000000000000..4244c6fc5a7b25e541321b0b7eef2a3952e0a13b --- /dev/null +++ b/lib/codemirror-3.1/mode/python/index.html @@ -0,0 +1,135 @@ + + + + + CodeMirror: Python mode + + + + + + + + +

CodeMirror: Python mode

+ +
+ +

Configuration Options:

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

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 :
    ^[\\+\\-\\*/%&|\\^~<>!]
  • +
  • singleDelimiters - RegEx - Regular Expression for single delimiter matching, default :
    ^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]
  • +
  • doubleOperators - RegEx - Regular Expression for double operators matching, default :
    ^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))
  • +
  • doubleDelimiters - RegEx - Regular Expressoin 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]*
  • +
+ + +

MIME types defined: text/x-python.

+ + diff --git a/lib/codemirror-3.1/mode/python/python.js b/lib/codemirror-3.1/mode/python/python.js new file mode 100644 index 0000000000000000000000000000000000000000..951aaf8197d22d0a1a700b76c73c533b33b47cd7 --- /dev/null +++ b/lib/codemirror-3.1/mode/python/python.js @@ -0,0 +1,340 @@ +CodeMirror.defineMode("python", function(conf, parserConf) { + var ERRORCLASS = 'error'; + + function wordRegexp(words) { + return new RegExp("^((" + words.join(")|(") + "))\\b"); + } + + var singleOperators = parserConf.singleOperators || new RegExp("^[\\+\\-\\*/%&|\\^~<>!]"); + var singleDelimiters = parserConf.singleDelimiters || new RegExp('^[\\(\\)\\[\\]\\{\\}@,:`=;\\.]'); + var doubleOperators = parserConf.doubleOperators || new RegExp("^((==)|(!=)|(<=)|(>=)|(<>)|(<<)|(>>)|(//)|(\\*\\*))"); + var doubleDelimiters = parserConf.doubleDelimiters || new RegExp("^((\\+=)|(\\-=)|(\\*=)|(%=)|(/=)|(&=)|(\\|=)|(\\^=))"); + var tripleDelimiters = parserConf.tripleDelimiters || new RegExp("^((//=)|(>>=)|(<<=)|(\\*\\*=))"); + var identifiers = parserConf.identifiers|| new RegExp("^[_A-Za-z][_A-Za-z0-9]*"); + + var wordOperators = wordRegexp(['and', 'or', 'not', 'is', 'in']); + 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']; + 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__']; + var py2 = {'builtins': ['apply', 'basestring', 'buffer', 'cmp', 'coerce', 'execfile', + 'file', 'intern', 'long', 'raw_input', 'reduce', 'reload', + 'unichr', 'unicode', 'xrange', 'False', 'True', 'None'], + 'keywords': ['exec', 'print']}; + var py3 = {'builtins': ['ascii', 'bytes', 'exec', 'print'], + 'keywords': ['nonlocal', 'False', 'True', 'None']}; + + if (!!parserConf.version && parseInt(parserConf.version, 10) === 3) { + commonkeywords = commonkeywords.concat(py3.keywords); + commonBuiltins = commonBuiltins.concat(py3.builtins); + var stringPrefixes = new RegExp("^(([rb]|(br))?('{3}|\"{3}|['\"]))", "i"); + } else { + commonkeywords = commonkeywords.concat(py2.keywords); + commonBuiltins = commonBuiltins.concat(py2.builtins); + var stringPrefixes = new RegExp("^(([rub]|(ur)|(br))?('{3}|\"{3}|['\"]))", "i"); + } + var keywords = wordRegexp(commonkeywords); + var builtins = wordRegexp(commonBuiltins); + + var indentInfo = null; + + // tokenizers + function tokenBase(stream, state) { + // Handle scope changes + if (stream.sol()) { + var scopeOffset = state.scopes[0].offset; + if (stream.eatSpace()) { + var lineOffset = stream.indentation(); + if (lineOffset > scopeOffset) { + indentInfo = 'indent'; + } else if (lineOffset < scopeOffset) { + indentInfo = 'dedent'; + } + return null; + } else { + if (scopeOffset > 0) { + dedent(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(/^[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)) { + 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(keywords)) { + return 'keyword'; + } + + if (stream.match(builtins)) { + return 'builtin'; + } + + if (stream.match(identifiers)) { + return 'variable'; + } + + // Handle non-detected items + stream.next(); + return ERRORCLASS; + } + + function tokenStringFactory(delimiter) { + while ('rub'.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 = tokenBase; + return OUTCLASS; + } else { + stream.eat(/['"]/); + } + } + if (singleline) { + if (parserConf.singleLineStringErrors) { + return ERRORCLASS; + } else { + state.tokenize = tokenBase; + } + } + return OUTCLASS; + } + tokenString.isString = true; + return tokenString; + } + + function indent(stream, state, type) { + type = type || 'py'; + var indentUnit = 0; + if (type === 'py') { + if (state.scopes[0].type !== 'py') { + state.scopes[0].offset = stream.indentation(); + return; + } + for (var i = 0; i < state.scopes.length; ++i) { + if (state.scopes[i].type === 'py') { + indentUnit = state.scopes[i].offset + conf.indentUnit; + break; + } + } + } else { + indentUnit = stream.column() + stream.current().length; + } + state.scopes.unshift({ + offset: indentUnit, + type: type + }); + } + + function dedent(stream, state, type) { + type = type || 'py'; + if (state.scopes.length == 1) return; + if (state.scopes[0].type === 'py') { + var _indent = stream.indentation(); + var _indent_index = -1; + for (var i = 0; i < state.scopes.length; ++i) { + if (_indent === state.scopes[i].offset) { + _indent_index = i; + break; + } + } + if (_indent_index === -1) { + return true; + } + while (state.scopes[0].offset !== _indent) { + state.scopes.shift(); + } + return false; + } else { + if (type === 'py') { + state.scopes[0].offset = stream.indentation(); + return false; + } else { + if (state.scopes[0].type != type) { + return true; + } + state.scopes.shift(); + return false; + } + } + } + + function tokenLexer(stream, state) { + indentInfo = null; + var style = state.tokenize(stream, state); + var current = stream.current(); + + // Handle '.' connected identifiers + if (current === '.') { + style = stream.match(identifiers, false) ? null : ERRORCLASS; + if (style === null && state.lastToken === 'meta') { + // Apply 'meta' style to '.' connected identifiers when + // appropriate. + style = 'meta'; + } + return style; + } + + // Handle decorators + if (current === '@') { + return stream.match(identifiers, false) ? 'meta' : ERRORCLASS; + } + + 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 && state.scopes[0].type == 'py') + || indentInfo === 'indent') { + indent(stream, state); + } + var delimiter_index = '[({'.indexOf(current); + if (delimiter_index !== -1) { + indent(stream, state, '])}'.slice(delimiter_index, delimiter_index+1)); + } + if (indentInfo === 'dedent') { + if (dedent(stream, state)) { + return ERRORCLASS; + } + } + delimiter_index = '])}'.indexOf(current); + if (delimiter_index !== -1) { + if (dedent(stream, state, current)) { + return ERRORCLASS; + } + } + if (state.dedent > 0 && stream.eol() && state.scopes[0].type == 'py') { + if (state.scopes.length > 1) state.scopes.shift(); + state.dedent -= 1; + } + + return style; + } + + var external = { + startState: function(basecolumn) { + return { + tokenize: tokenBase, + scopes: [{offset:basecolumn || 0, type:'py'}], + lastToken: null, + lambda: false, + dedent: 0 + }; + }, + + token: function(stream, state) { + var style = tokenLexer(stream, state); + + state.lastToken = style; + + if (stream.eol() && stream.lambda) { + state.lambda = false; + } + + return style; + }, + + indent: function(state) { + if (state.tokenize != tokenBase) { + return state.tokenize.isString ? CodeMirror.Pass : 0; + } + + return state.scopes[0].offset; + } + + }; + return external; +}); + +CodeMirror.defineMIME("text/x-python", "python"); diff --git a/lib/codemirror-3.1/mode/q/index.html b/lib/codemirror-3.1/mode/q/index.html new file mode 100644 index 0000000000000000000000000000000000000000..303ec1d3ad31121dfbc0b689449be844dfa00c03 --- /dev/null +++ b/lib/codemirror-3.1/mode/q/index.html @@ -0,0 +1,131 @@ + + + + + CodeMirror: Q mode + + + + + + + + +

CodeMirror: Q mode

+ +
+ + + +

MIME type defined: text/x-q.

+ + diff --git a/lib/codemirror-3.1/mode/q/q.js b/lib/codemirror-3.1/mode/q/q.js new file mode 100644 index 0000000000000000000000000000000000000000..6fc4e65a9cea09f2624f5d59711c6930310a6d4a --- /dev/null +++ b/lib/codemirror-3.1/mode/q/q.js @@ -0,0 +1,124 @@ +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):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-Z|a-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}([D|T](\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[\d|a-f|A-F]*/) + || stream.match(/^[0|1]+[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-Z|a-z]|\./.test(c)) + return stream.eatWhile(/[A-Z|a-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"); diff --git a/lib/codemirror-3.1/mode/r/LICENSE b/lib/codemirror-3.1/mode/r/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..2510ae16cf7288da165dfe6a29717eb24a3a58cc --- /dev/null +++ b/lib/codemirror-3.1/mode/r/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2011, Ubalo, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Ubalo, Inc nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/codemirror-3.1/mode/r/index.html b/lib/codemirror-3.1/mode/r/index.html new file mode 100644 index 0000000000000000000000000000000000000000..12819553e9c25eb7f2136d60a5eeb20c8871b43c --- /dev/null +++ b/lib/codemirror-3.1/mode/r/index.html @@ -0,0 +1,74 @@ + + + + + CodeMirror: R mode + + + + + + + +

CodeMirror: R mode

+
+ + +

MIME types defined: text/x-rsrc.

+ +

Development of the CodeMirror R mode was kindly sponsored + by Ubalo, who hold + the license.

+ + + diff --git a/lib/codemirror-3.1/mode/r/r.js b/lib/codemirror-3.1/mode/r/r.js new file mode 100644 index 0000000000000000000000000000000000000000..6410efbb22723c98a48efafe4519d958f73508d4 --- /dev/null +++ b/lib/codemirror-3.1/mode/r/r.js @@ -0,0 +1,141 @@ +CodeMirror.defineMode("r", function(config) { + function wordObj(str) { + var words = str.split(" "), res = {}; + for (var i = 0; i < words.length; ++i) res[words[i]] = true; + return res; + } + var atoms = wordObj("NULL NA Inf NaN NA_integer_ NA_real_ NA_complex_ NA_character_"); + var builtins = wordObj("list quote bquote eval return call parse deparse"); + var keywords = wordObj("if else repeat while function for in next break"); + var blockkeywords = wordObj("if else repeat while function for"); + 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(/.[.\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)) { + if (blockkeywords.propertyIsEnumerable(word)) curPunc = "block"; + return "keyword"; + } + if (builtins.propertyIsEnumerable(word)) return "builtin"; + return "variable"; + } else if (ch == "%") { + if (stream.skipTo("%")) stream.next(); + return "variable-2"; + } else if (ch == "<" && stream.eat("-")) { + return "arrow"; + } else if (ch == "=" && state.ctx.argList) { + return "arg-is"; + } else if (opChars.test(ch)) { + if (ch == "$") return "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"; + } + }; + } + + function push(state, type, stream) { + state.ctx = {type: type, + indent: state.indent, + align: null, + column: stream.column(), + prev: state.ctx}; + } + 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, + align: false}, + indent: 0, + afterIdent: false}; + }, + + token: function(stream, state) { + if (stream.sol()) { + if (state.ctx.align == null) state.ctx.align = false; + state.indent = stream.indentation(); + } + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + if (style != "comment" && state.ctx.align == null) state.ctx.align = true; + + var ctype = state.ctx.type; + if ((curPunc == ";" || curPunc == "{" || curPunc == "}") && ctype == "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 == ctype) pop(state); + 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.type == "block") return ctx.indent + (firstChar == "{" ? 0 : config.indentUnit); + else if (ctx.align) return ctx.column + (closing ? 0 : 1); + else return ctx.indent + (closing ? 0 : config.indentUnit); + } + }; +}); + +CodeMirror.defineMIME("text/x-rsrc", "r"); diff --git a/lib/codemirror-3.1/mode/rpm/changes/changes.js b/lib/codemirror-3.1/mode/rpm/changes/changes.js new file mode 100644 index 0000000000000000000000000000000000000000..14a08d9700849eb74c727fb4e2bff8ee78befa73 --- /dev/null +++ b/lib/codemirror-3.1/mode/rpm/changes/changes.js @@ -0,0 +1,19 @@ +CodeMirror.defineMode("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", "changes"); diff --git a/lib/codemirror-3.1/mode/rpm/changes/index.html b/lib/codemirror-3.1/mode/rpm/changes/index.html new file mode 100644 index 0000000000000000000000000000000000000000..e0e2d8778bd0e8e128ac8348b60a4b77d49fb97d --- /dev/null +++ b/lib/codemirror-3.1/mode/rpm/changes/index.html @@ -0,0 +1,53 @@ + + + + + CodeMirror: RPM changes mode + + + + + + + +

CodeMirror: RPM changes mode

+ +
+ + +

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

+ + diff --git a/lib/codemirror-3.1/mode/rpm/spec/index.html b/lib/codemirror-3.1/mode/rpm/spec/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8be98b63ec3c9b5f7d1167e2462053376839bb60 --- /dev/null +++ b/lib/codemirror-3.1/mode/rpm/spec/index.html @@ -0,0 +1,99 @@ + + + + + CodeMirror: RPM spec mode + + + + + + + + +

CodeMirror: RPM spec mode

+ +
+ + +

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

+ + diff --git a/lib/codemirror-3.1/mode/rpm/spec/spec.css b/lib/codemirror-3.1/mode/rpm/spec/spec.css new file mode 100644 index 0000000000000000000000000000000000000000..d0a5d430cacf07486842e77e55fdc429d70c6f70 --- /dev/null +++ b/lib/codemirror-3.1/mode/rpm/spec/spec.css @@ -0,0 +1,5 @@ +.cm-s-default span.cm-preamble {color: #b26818; font-weight: bold;} +.cm-s-default span.cm-macro {color: #b218b2;} +.cm-s-default span.cm-section {color: green; font-weight: bold;} +.cm-s-default span.cm-script {color: red;} +.cm-s-default span.cm-issue {color: yellow;} diff --git a/lib/codemirror-3.1/mode/rpm/spec/spec.js b/lib/codemirror-3.1/mode/rpm/spec/spec.js new file mode 100644 index 0000000000000000000000000000000000000000..9f339c21b1ae75d5988d48182f967ac90acef79b --- /dev/null +++ b/lib/codemirror-3.1/mode/rpm/spec/spec.js @@ -0,0 +1,66 @@ +// Quick and dirty spec file highlighting + +CodeMirror.defineMode("spec", function() { + var arch = /^(i386|i586|i686|x86_64|ppc64|ppc|ia64|s390x|s390|sparc64|sparcv9|sparc|noarch|alphaev6|alpha|hppa|mipsel)/; + + var preamble = /^(Name|Version|Release|License|Summary|Url|Group|Source|BuildArch|BuildRequires|BuildRoot|AutoReqProv|Provides|Requires(\(\w+\))?|Obsoletes|Conflicts|Recommends|Source\d*|Patch\d*|ExclusiveArch|NoSource|Supplements):/; + var section = /^%(debug_package|package|description|prep|build|install|files|clean|changelog|preun|postun|pre|post|triggerin|triggerun|pretrans|posttrans|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 "preamble"; } + if (stream.match(section)) { return "section"; } + } + + 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)) { return "number"; } + + // Macros like '%make_install' or '%attr(0775,root,root)' + if (stream.match(/^%[\w]+/)) { + if (stream.match(/^\(/)) { state.macroParameters = true; } + return "macro"; + } + if (state.macroParameters) { + if (stream.match(/^\d+/)) { return "number";} + if (stream.match(/^\)/)) { + state.macroParameters = false; + return "macro"; + } + } + if (stream.match(/^%\{\??[\w \-]+\}/)) { return "macro"; } // Macros like '%{defined fedora}' + + //TODO: Include bash script sub-parser (CodeMirror supports that) + stream.next(); + return null; + } + }; +}); + +CodeMirror.defineMIME("text/x-rpm-spec", "spec"); diff --git a/lib/codemirror-3.1/mode/rst/index.html b/lib/codemirror-3.1/mode/rst/index.html new file mode 100644 index 0000000000000000000000000000000000000000..6e477201f4fa7336df64bf93788de55cf301fc85 --- /dev/null +++ b/lib/codemirror-3.1/mode/rst/index.html @@ -0,0 +1,526 @@ + + + + + CodeMirror: reStructuredText mode + + + + + + + +

CodeMirror: reStructuredText mode

+ +
+ + +

The reStructuredText mode supports one configuration parameter:

+
+
verbatim (string)
+
A name or MIME type of a mode that will be used for highlighting + verbatim blocks. By default, reStructuredText mode uses uniform color + for whole block of verbatim text if no mode is given.
+
+

If python mode is available, + it will be used for highlighting blocks containing Python/IPython terminal + sessions (blocks starting with >>> (for Python) or + In [num]: (for IPython). + +

MIME types defined: text/x-rst.

+ + + diff --git a/lib/codemirror-3.1/mode/rst/rst.js b/lib/codemirror-3.1/mode/rst/rst.js new file mode 100644 index 0000000000000000000000000000000000000000..56d8502e7d52f533c65c37fad39bce10e8a4f43b --- /dev/null +++ b/lib/codemirror-3.1/mode/rst/rst.js @@ -0,0 +1,314 @@ +CodeMirror.defineMode('rst', function(config, options) { + function setState(state, fn, ctx) { + state.fn = fn; + setCtx(state, ctx); + } + + function setCtx(state, ctx) { + state.ctx = ctx || {}; + } + + function setNormal(state, ch) { + if (ch && (typeof ch !== 'string')) { + var str = ch.current(); + ch = str[str.length-1]; + } + + setState(state, normal, {back: ch}); + } + + function hasMode(mode) { + return mode && CodeMirror.modes.hasOwnProperty(mode); + } + + function getMode(mode) { + if (hasMode(mode)) { + return CodeMirror.getMode(config, mode); + } else { + return null; + } + } + + var verbatimMode = getMode(options.verbatim); + var pythonMode = getMode('python'); + + var reSection = /^[!"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/; + var reDirective = /^\s*\w([-:.\w]*\w)?::(\s|$)/; + var reHyperlink = /^\s*_[\w-]+:(\s|$)/; + var reFootnote = /^\s*\[(\d+|#)\](\s|$)/; + var reCitation = /^\s*\[[A-Za-z][\w-]*\](\s|$)/; + var reFootnoteRef = /^\[(\d+|#)\]_/; + var reCitationRef = /^\[[A-Za-z][\w-]*\]_/; + var reDirectiveMarker = /^\.\.(\s|$)/; + var reVerbatimMarker = /^::\s*$/; + var rePreInline = /^[-\s"([{/:.,;!?\\_]/; + var reExamples = /^\s+(>>>|In \[\d+\]:)\s/; + + function normal(stream, state) { + var ch, sol, i; + + if (stream.eat(/\\/)) { + ch = stream.next(); + setNormal(state, ch); + return null; + } + + sol = stream.sol(); + + if (sol && (ch = stream.eat(reSection))) { + for (i = 0; stream.eat(ch); i++); + + if (i >= 3 && stream.match(/^\s*$/)) { + setNormal(state, null); + return 'header'; + } else { + stream.backUp(i + 1); + } + } + + if (sol && stream.match(reDirectiveMarker)) { + if (!stream.eol()) { + setState(state, directive); + } + return 'meta'; + } + + if (stream.match(reVerbatimMarker)) { + if (!verbatimMode) { + setState(state, verbatim); + } else { + var mode = verbatimMode; + + setState(state, verbatim, { + mode: mode, + local: mode.startState() + }); + } + return 'meta'; + } + + if (sol && stream.match(reExamples, false)) { + if (!pythonMode) { + setState(state, verbatim); + return 'meta'; + } else { + var mode = pythonMode; + + setState(state, verbatim, { + mode: mode, + local: mode.startState() + }); + + return null; + } + } + + function testBackward(re) { + return sol || !state.ctx.back || re.test(state.ctx.back); + } + + function testForward(re) { + return stream.eol() || stream.match(re, false); + } + + function testInline(re) { + return stream.match(re) && testBackward(/\W/) && testForward(/\W/); + } + + if (testInline(reFootnoteRef)) { + setNormal(state, stream); + return 'footnote'; + } + + if (testInline(reCitationRef)) { + setNormal(state, stream); + return 'citation'; + } + + ch = stream.next(); + + if (testBackward(rePreInline)) { + if ((ch === ':' || ch === '|') && stream.eat(/\S/)) { + var token; + + if (ch === ':') { + token = 'builtin'; + } else { + token = 'atom'; + } + + setState(state, inline, { + ch: ch, + wide: false, + prev: null, + token: token + }); + + return token; + } + + if (ch === '*' || ch === '`') { + var orig = ch, + wide = false; + + ch = stream.next(); + + if (ch == orig) { + wide = true; + ch = stream.next(); + } + + if (ch && !/\s/.test(ch)) { + var token; + + if (orig === '*') { + token = wide ? 'strong' : 'em'; + } else { + token = wide ? 'string' : 'string-2'; + } + + setState(state, inline, { + ch: orig, // inline() has to know what to search for + wide: wide, // are we looking for `ch` or `chch` + prev: null, // terminator must not be preceeded with whitespace + token: token // I don't want to recompute this all the time + }); + + return token; + } + } + } + + setNormal(state, ch); + return null; + } + + function inline(stream, state) { + var ch = stream.next(), + token = state.ctx.token; + + function finish(ch) { + state.ctx.prev = ch; + return token; + } + + if (ch != state.ctx.ch) { + return finish(ch); + } + + if (/\s/.test(state.ctx.prev)) { + return finish(ch); + } + + if (state.ctx.wide) { + ch = stream.next(); + + if (ch != state.ctx.ch) { + return finish(ch); + } + } + + if (!stream.eol() && !rePostInline.test(stream.peek())) { + if (state.ctx.wide) { + stream.backUp(1); + } + + return finish(ch); + } + + setState(state, normal); + setNormal(state, ch); + + return token; + } + + function directive(stream, state) { + var token = null; + + if (stream.match(reDirective)) { + token = 'attribute'; + } else if (stream.match(reHyperlink)) { + token = 'link'; + } else if (stream.match(reFootnote)) { + token = 'quote'; + } else if (stream.match(reCitation)) { + token = 'quote'; + } else { + stream.eatSpace(); + + if (stream.eol()) { + setNormal(state, stream); + return null; + } else { + stream.skipToEnd(); + setState(state, comment); + return 'comment'; + } + } + + // FIXME this is unreachable + setState(state, body, {start: true}); + return token; + } + + function body(stream, state) { + var token = 'body'; + + if (!state.ctx.start || stream.sol()) { + return block(stream, state, token); + } + + stream.skipToEnd(); + setCtx(state); + + return token; + } + + function comment(stream, state) { + return block(stream, state, 'comment'); + } + + function verbatim(stream, state) { + if (!verbatimMode) { + return block(stream, state, 'meta'); + } else { + if (stream.sol()) { + if (!stream.eatSpace()) { + setNormal(state, stream); + } + + return null; + } + + return verbatimMode.token(stream, state.ctx.local); + } + } + + function block(stream, state, token) { + if (stream.eol() || stream.eatSpace()) { + stream.skipToEnd(); + return token; + } else { + setNormal(state, stream); + return null; + } + } + + return { + startState: function() { + return {fn: normal, ctx: {}}; + }, + + copyState: function(state) { + return {fn: state.fn, ctx: state.ctx}; + }, + + token: function(stream, state) { + var token = state.fn(stream, state); + return token; + } + }; +}, "python"); + +CodeMirror.defineMIME("text/x-rst", "rst"); diff --git a/lib/codemirror-3.1/mode/ruby/LICENSE b/lib/codemirror-3.1/mode/ruby/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ac09fc4035781366af9b7693ceaf19cf30deee27 --- /dev/null +++ b/lib/codemirror-3.1/mode/ruby/LICENSE @@ -0,0 +1,24 @@ +Copyright (c) 2011, Ubalo, Inc. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the Ubalo, Inc. nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL UBALO, INC BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/codemirror-3.1/mode/ruby/index.html b/lib/codemirror-3.1/mode/ruby/index.html new file mode 100644 index 0000000000000000000000000000000000000000..64cfe5ef34327a2eed167be2e144d8c1d16b7716 --- /dev/null +++ b/lib/codemirror-3.1/mode/ruby/index.html @@ -0,0 +1,173 @@ + + + + + CodeMirror: Ruby mode + + + + + + + + +

CodeMirror: Ruby mode

+
+ + +

MIME types defined: text/x-ruby.

+ +

Development of the CodeMirror Ruby mode was kindly sponsored + by Ubalo, who hold + the license.

+ + + diff --git a/lib/codemirror-3.1/mode/ruby/ruby.js b/lib/codemirror-3.1/mode/ruby/ruby.js new file mode 100644 index 0000000000000000000000000000000000000000..d106a542db5d7846a3087978a6d84c5db1d84808 --- /dev/null +++ b/lib/codemirror-3.1/mode/ruby/ruby.js @@ -0,0 +1,195 @@ +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" + ]); + var indentWords = wordObj(["def", "class", "case", "for", "while", "do", "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) { + curPunc = null; + 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 == '"' || + (ch == "/" && !stream.eol() && stream.peek() != " ")) { + return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state); + } else if (ch == "%") { + var style, embed = false; + if (stream.eat("s")) style = "atom"; + else if (stream.eat(/[WQ]/)) { style = "string"; embed = true; } + else if (stream.eat(/[wxqr]/)) style = "string"; + 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[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); + stream.eatWhile(/[\w\?]/); + return "atom"; + } else if (ch == "@") { + stream.eat("@"); + stream.eatWhile(/[\w\?]/); + return "variable-2"; + } else if (ch == "$") { + stream.next(); + stream.eatWhile(/[\w\?]/); + return "variable-3"; + } else if (/\w/.test(ch)) { + stream.eatWhile(/[\w\?]/); + 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)) { + stream.eatWhile(/[=+\-\/*:\.^%<>~|]/); + return "operator"; + } else { + return null; + } + } + + function tokenBaseUntilBrace() { + var depth = 1; + return function(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); + }; + } + function readQuoted(quote, style, embed, unescaped) { + return function(stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && (unescaped || !escaped)) { + state.tokenize.pop(); + break; + } + if (embed && ch == "#" && !escaped && stream.eat("{")) { + state.tokenize.push(tokenBaseUntilBrace(arguments.callee)); + break; + } + escaped = !escaped && ch == "\\"; + } + return style; + }; + } + function readHereDoc(phrase) { + return function(stream, state) { + 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) { + if (stream.sol()) state.indented = stream.indentation(); + var style = state.tokenize[state.tokenize.length-1](stream, state), kwtype; + if (style == "ident") { + var word = stream.current(); + style = keywords.propertyIsEnumerable(stream.current()) ? "keyword" + : /^[A-Z]/.test(word) ? "tag" + : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def" + : "variable"; + 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"; + } + if (curPunc || (style && style != "comment")) state.lastTok = word || curPunc || style; + 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 0; + 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); + }, + electricChars: "}de" // enD and rescuE + + }; +}); + +CodeMirror.defineMIME("text/x-ruby", "ruby"); + diff --git a/lib/codemirror-3.1/mode/rust/index.html b/lib/codemirror-3.1/mode/rust/index.html new file mode 100644 index 0000000000000000000000000000000000000000..a6d47fe84db98e7804c6d36370c4124dab41d9c7 --- /dev/null +++ b/lib/codemirror-3.1/mode/rust/index.html @@ -0,0 +1,48 @@ + + + + + CodeMirror: Rust mode + + + + + + + +

CodeMirror: Rust mode

+ +
+ + + +

MIME types defined: text/x-rustsrc.

+ + diff --git a/lib/codemirror-3.1/mode/rust/rust.js b/lib/codemirror-3.1/mode/rust/rust.js new file mode 100644 index 0000000000000000000000000000000000000000..ea3005c360da3c9369ec2fffca70b6db3d40fd00 --- /dev/null +++ b/lib/codemirror-3.1/mode/rust/rust.js @@ -0,0 +1,432 @@ +CodeMirror.defineMode("rust", function() { + var indentUnit = 4, altIndentUnit = 2; + var valKeywords = { + "if": "if-style", "while": "if-style", "else": "else-style", + "do": "else-style", "ret": "else-style", "fail": "else-style", + "break": "atom", "cont": "atom", "const": "let", "resource": "fn", + "let": "let", "fn": "fn", "for": "for", "alt": "alt", "iface": "iface", + "impl": "impl", "type": "type", "enum": "enum", "mod": "mod", + "as": "op", "true": "atom", "false": "atom", "assert": "op", "check": "op", + "claim": "op", "native": "ignore", "unsafe": "ignore", "import": "else-style", + "export": "else-style", "copy": "op", "log": "op", "log_err": "op", + "use": "op", "bind": "op", "self": "atom" + }; + var typeKeywords = function() { + var keywords = {"fn": "fn", "block": "fn", "obj": "obj"}; + var atoms = "bool uint int i8 i16 i32 i64 u8 u16 u32 u64 float f32 f64 str char".split(" "); + for (var i = 0, e = atoms.length; i < e; ++i) keywords[atoms[i]] = "atom"; + return keywords; + }(); + var operatorChar = /[+\-*&%=<>!?|\.@]/; + + // Tokenizer + + // Used as scratch variable to communicate multiple values without + // consing up tons of objects. + var tcat, content; + function r(tc, style) { + tcat = tc; + return style; + } + + function tokenBase(stream, state) { + var ch = stream.next(); + if (ch == '"') { + state.tokenize = tokenString; + return state.tokenize(stream, state); + } + if (ch == "'") { + tcat = "atom"; + if (stream.eat("\\")) { + if (stream.skipTo("'")) { stream.next(); return "string"; } + else { return "error"; } + } else { + stream.next(); + return stream.eat("'") ? "string" : "error"; + } + } + if (ch == "/") { + if (stream.eat("/")) { stream.skipToEnd(); return "comment"; } + if (stream.eat("*")) { + state.tokenize = tokenComment(1); + return state.tokenize(stream, state); + } + } + if (ch == "#") { + if (stream.eat("[")) { tcat = "open-attr"; return null; } + stream.eatWhile(/\w/); + return r("macro", "meta"); + } + if (ch == ":" && stream.match(":<")) { + return r("op", null); + } + if (ch.match(/\d/) || (ch == "." && stream.eat(/\d/))) { + var flp = false; + if (!stream.match(/^x[\da-f]+/i) && !stream.match(/^b[01]+/)) { + stream.eatWhile(/\d/); + if (stream.eat(".")) { flp = true; stream.eatWhile(/\d/); } + if (stream.match(/^e[+\-]?\d+/i)) { flp = true; } + } + if (flp) stream.match(/^f(?:32|64)/); + else stream.match(/^[ui](?:8|16|32|64)/); + return r("atom", "number"); + } + if (ch.match(/[()\[\]{}:;,]/)) return r(ch, null); + if (ch == "-" && stream.eat(">")) return r("->", null); + if (ch.match(operatorChar)) { + stream.eatWhile(operatorChar); + return r("op", null); + } + stream.eatWhile(/\w/); + content = stream.current(); + if (stream.match(/^::\w/)) { + stream.backUp(1); + return r("prefix", "variable-2"); + } + if (state.keywords.propertyIsEnumerable(content)) + return r(state.keywords[content], content.match(/true|false/) ? "atom" : "keyword"); + return r("name", "variable"); + } + + function tokenString(stream, state) { + var ch, escaped = false; + while (ch = stream.next()) { + if (ch == '"' && !escaped) { + state.tokenize = tokenBase; + return r("atom", "string"); + } + escaped = !escaped && ch == "\\"; + } + // Hack to not confuse the parser when a string is split in + // pieces. + return r("op", "string"); + } + + function tokenComment(depth) { + return function(stream, state) { + var lastCh = null, ch; + while (ch = stream.next()) { + if (ch == "/" && lastCh == "*") { + if (depth == 1) { + state.tokenize = tokenBase; + break; + } else { + state.tokenize = tokenComment(depth - 1); + return state.tokenize(stream, state); + } + } + if (ch == "*" && lastCh == "/") { + state.tokenize = tokenComment(depth + 1); + return state.tokenize(stream, state); + } + lastCh = ch; + } + return "comment"; + }; + } + + // Parser + + var cx = {state: null, stream: 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 pushlex(type, info) { + var result = function() { + var state = cx.state; + state.lexical = {indented: state.indented, column: cx.stream.column(), + type: type, prev: state.lexical, info: 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; + } + } + function typecx() { cx.state.keywords = typeKeywords; } + function valcx() { cx.state.keywords = valKeywords; } + poplex.lex = typecx.lex = valcx.lex = true; + + function commasep(comb, end) { + function more(type) { + if (type == ",") return cont(comb, more); + if (type == end) return cont(); + return cont(more); + } + return function(type) { + if (type == end) return cont(); + return pass(comb, more); + }; + } + + function stat_of(comb, tag) { + return cont(pushlex("stat", tag), comb, poplex, block); + } + function block(type) { + if (type == "}") return cont(); + if (type == "let") return stat_of(letdef1, "let"); + if (type == "fn") return stat_of(fndef); + if (type == "type") return cont(pushlex("stat"), tydef, endstatement, poplex, block); + if (type == "enum") return stat_of(enumdef); + if (type == "mod") return stat_of(mod); + if (type == "iface") return stat_of(iface); + if (type == "impl") return stat_of(impl); + if (type == "open-attr") return cont(pushlex("]"), commasep(expression, "]"), poplex); + if (type == "ignore" || type.match(/[\]\);,]/)) return cont(block); + return pass(pushlex("stat"), expression, poplex, endstatement, block); + } + function endstatement(type) { + if (type == ";") return cont(); + return pass(); + } + function expression(type) { + if (type == "atom" || type == "name") return cont(maybeop); + if (type == "{") return cont(pushlex("}"), exprbrace, poplex); + if (type.match(/[\[\(]/)) return matchBrackets(type, expression); + if (type.match(/[\]\)\};,]/)) return pass(); + if (type == "if-style") return cont(expression, expression); + if (type == "else-style" || type == "op") return cont(expression); + if (type == "for") return cont(pattern, maybetype, inop, expression, expression); + if (type == "alt") return cont(expression, altbody); + if (type == "fn") return cont(fndef); + if (type == "macro") return cont(macro); + return cont(); + } + function maybeop(type) { + if (content == ".") return cont(maybeprop); + if (content == "::<"){return cont(typarams, maybeop);} + if (type == "op" || content == ":") return cont(expression); + if (type == "(" || type == "[") return matchBrackets(type, expression); + return pass(); + } + function maybeprop() { + if (content.match(/^\w+$/)) {cx.marked = "variable"; return cont(maybeop);} + return pass(expression); + } + function exprbrace(type) { + if (type == "op") { + if (content == "|") return cont(blockvars, poplex, pushlex("}", "block"), block); + if (content == "||") return cont(poplex, pushlex("}", "block"), block); + } + if (content == "mutable" || (content.match(/^\w+$/) && cx.stream.peek() == ":" + && !cx.stream.match("::", false))) + return pass(record_of(expression)); + return pass(block); + } + function record_of(comb) { + function ro(type) { + if (content == "mutable" || content == "with") {cx.marked = "keyword"; return cont(ro);} + if (content.match(/^\w*$/)) {cx.marked = "variable"; return cont(ro);} + if (type == ":") return cont(comb, ro); + if (type == "}") return cont(); + return cont(ro); + } + return ro; + } + function blockvars(type) { + if (type == "name") {cx.marked = "def"; return cont(blockvars);} + if (type == "op" && content == "|") return cont(); + return cont(blockvars); + } + + function letdef1(type) { + if (type.match(/[\]\)\};]/)) return cont(); + if (content == "=") return cont(expression, letdef2); + if (type == ",") return cont(letdef1); + return pass(pattern, maybetype, letdef1); + } + function letdef2(type) { + if (type.match(/[\]\)\};,]/)) return pass(letdef1); + else return pass(expression, letdef2); + } + function maybetype(type) { + if (type == ":") return cont(typecx, rtype, valcx); + return pass(); + } + function inop(type) { + if (type == "name" && content == "in") {cx.marked = "keyword"; return cont();} + return pass(); + } + function fndef(type) { + if (content == "@" || content == "~") {cx.marked = "keyword"; return cont(fndef);} + if (type == "name") {cx.marked = "def"; return cont(fndef);} + if (content == "<") return cont(typarams, fndef); + if (type == "{") return pass(expression); + if (type == "(") return cont(pushlex(")"), commasep(argdef, ")"), poplex, fndef); + if (type == "->") return cont(typecx, rtype, valcx, fndef); + if (type == ";") return cont(); + return cont(fndef); + } + function tydef(type) { + if (type == "name") {cx.marked = "def"; return cont(tydef);} + if (content == "<") return cont(typarams, tydef); + if (content == "=") return cont(typecx, rtype, valcx); + return cont(tydef); + } + function enumdef(type) { + if (type == "name") {cx.marked = "def"; return cont(enumdef);} + if (content == "<") return cont(typarams, enumdef); + if (content == "=") return cont(typecx, rtype, valcx, endstatement); + if (type == "{") return cont(pushlex("}"), typecx, enumblock, valcx, poplex); + return cont(enumdef); + } + function enumblock(type) { + if (type == "}") return cont(); + if (type == "(") return cont(pushlex(")"), commasep(rtype, ")"), poplex, enumblock); + if (content.match(/^\w+$/)) cx.marked = "def"; + return cont(enumblock); + } + function mod(type) { + if (type == "name") {cx.marked = "def"; return cont(mod);} + if (type == "{") return cont(pushlex("}"), block, poplex); + return pass(); + } + function iface(type) { + if (type == "name") {cx.marked = "def"; return cont(iface);} + if (content == "<") return cont(typarams, iface); + if (type == "{") return cont(pushlex("}"), block, poplex); + return pass(); + } + function impl(type) { + if (content == "<") return cont(typarams, impl); + if (content == "of" || content == "for") {cx.marked = "keyword"; return cont(rtype, impl);} + if (type == "name") {cx.marked = "def"; return cont(impl);} + if (type == "{") return cont(pushlex("}"), block, poplex); + return pass(); + } + function typarams() { + if (content == ">") return cont(); + if (content == ",") return cont(typarams); + if (content == ":") return cont(rtype, typarams); + return pass(rtype, typarams); + } + function argdef(type) { + if (type == "name") {cx.marked = "def"; return cont(argdef);} + if (type == ":") return cont(typecx, rtype, valcx); + return pass(); + } + function rtype(type) { + if (type == "name") {cx.marked = "variable-3"; return cont(rtypemaybeparam); } + if (content == "mutable") {cx.marked = "keyword"; return cont(rtype);} + if (type == "atom") return cont(rtypemaybeparam); + if (type == "op" || type == "obj") return cont(rtype); + if (type == "fn") return cont(fntype); + if (type == "{") return cont(pushlex("{"), record_of(rtype), poplex); + return matchBrackets(type, rtype); + } + function rtypemaybeparam() { + if (content == "<") return cont(typarams); + return pass(); + } + function fntype(type) { + if (type == "(") return cont(pushlex("("), commasep(rtype, ")"), poplex, fntype); + if (type == "->") return cont(rtype); + return pass(); + } + function pattern(type) { + if (type == "name") {cx.marked = "def"; return cont(patternmaybeop);} + if (type == "atom") return cont(patternmaybeop); + if (type == "op") return cont(pattern); + if (type.match(/[\]\)\};,]/)) return pass(); + return matchBrackets(type, pattern); + } + function patternmaybeop(type) { + if (type == "op" && content == ".") return cont(); + if (content == "to") {cx.marked = "keyword"; return cont(pattern);} + else return pass(); + } + function altbody(type) { + if (type == "{") return cont(pushlex("}", "alt"), altblock1, poplex); + return pass(); + } + function altblock1(type) { + if (type == "}") return cont(); + if (type == "|") return cont(altblock1); + if (content == "when") {cx.marked = "keyword"; return cont(expression, altblock2);} + if (type.match(/[\]\);,]/)) return cont(altblock1); + return pass(pattern, altblock2); + } + function altblock2(type) { + if (type == "{") return cont(pushlex("}", "alt"), block, poplex, altblock1); + else return pass(altblock1); + } + + function macro(type) { + if (type.match(/[\[\(\{]/)) return matchBrackets(type, expression); + return pass(); + } + function matchBrackets(type, comb) { + if (type == "[") return cont(pushlex("]"), commasep(comb, "]"), poplex); + if (type == "(") return cont(pushlex(")"), commasep(comb, ")"), poplex); + if (type == "{") return cont(pushlex("}"), commasep(comb, "}"), poplex); + return cont(); + } + + function parse(state, stream, style) { + 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; + + while (true) { + var combinator = cc.length ? cc.pop() : block; + if (combinator(tcat)) { + while(cc.length && cc[cc.length - 1].lex) + cc.pop()(); + return cx.marked || style; + } + } + } + + return { + startState: function() { + return { + tokenize: tokenBase, + cc: [], + lexical: {indented: -indentUnit, column: 0, type: "top", align: false}, + keywords: valKeywords, + indented: 0 + }; + }, + + 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; + tcat = content = null; + var style = state.tokenize(stream, state); + if (style == "comment") return style; + if (!state.lexical.hasOwnProperty("align")) + state.lexical.align = true; + if (tcat == "prefix") return style; + if (!content) content = stream.current(); + return parse(state, stream, style); + }, + + indent: function(state, textAfter) { + if (state.tokenize != tokenBase) return 0; + var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, + type = lexical.type, closing = firstChar == type; + if (type == "stat") return lexical.indented + indentUnit; + if (lexical.align) return lexical.column + (closing ? 0 : 1); + return lexical.indented + (closing ? 0 : (lexical.info == "alt" ? altIndentUnit : indentUnit)); + }, + + electricChars: "{}" + }; +}); + +CodeMirror.defineMIME("text/x-rustsrc", "rust"); diff --git a/lib/codemirror-3.1/mode/sass/index.html b/lib/codemirror-3.1/mode/sass/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3af7bff9ed9d9daccc37dec5c39baf7bb6aa86cb --- /dev/null +++ b/lib/codemirror-3.1/mode/sass/index.html @@ -0,0 +1,54 @@ + + + + + CodeMirror: Sass mode + + + + + + + + +

CodeMirror: Sass mode

+
+ + +

MIME types defined: text/x-sass.

+ + diff --git a/lib/codemirror-3.1/mode/sass/sass.js b/lib/codemirror-3.1/mode/sass/sass.js new file mode 100644 index 0000000000000000000000000000000000000000..9aed75a1afb06cb3cf107d0fac52b14d9514ff90 --- /dev/null +++ b/lib/codemirror-3.1/mode/sass/sass.js @@ -0,0 +1,349 @@ +CodeMirror.defineMode("sass", function(config) { + var tokenRegexp = function(words){ + return new RegExp("^" + words.join("|")); + }; + + var tags = ["&", "a","abbr","acronym","address","applet","area","article","aside","audio","b","base","basefont","bdi","bdo","big","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","command","datalist","dd","del","details","dfn","dir","div","dl","dt","em","embed","fieldset","figcaption","figure","font","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","keygen","kbd","label","legend","li","link","map","mark","menu","meta","meter","nav","noframes","noscript","object","ol","optgroup","option","output","p","param","pre","progress","q","rp","rt","ruby","s","samp","script","section","select","small","source","span","strike","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","title","tr","track","tt","u","ul","var","video","wbr"]; + var keywords = ["true", "false", "null", "auto"]; + var keywordsRegexp = new RegExp("^" + keywords.join("|")); + + var operators = ["\\(", "\\)", "=", ">", "<", "==", ">=", "<=", "\\+", "-", "\\!=", "/", "\\*", "%", "and", "or", "not"]; + var opRegexp = tokenRegexp(operators); + + function htmlTag(val){ + for(var i=0; i + + + + CodeMirror: Scheme mode + + + + + + + +

CodeMirror: Scheme mode

+
+ + +

MIME types defined: text/x-scheme.

+ + + diff --git a/lib/codemirror-3.1/mode/scheme/scheme.js b/lib/codemirror-3.1/mode/scheme/scheme.js new file mode 100644 index 0000000000000000000000000000000000000000..2ed0a24cd85fa3453da843d3dc32fce127b2d8c3 --- /dev/null +++ b/lib/codemirror-3.1/mode/scheme/scheme.js @@ -0,0 +1,230 @@ +/** + * Author: Koh Zi Han, based on implementation by Koh Zi Chun + */ +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 + }; + }, + + 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 non spaces + returnType = COMMENT; + break; + } + default: // default parsing mode + var ch = stream.next(); + + if (ch == "\"") { + state.mode = "string"; + returnType = STRING; + + } else if (ch == "'") { + 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++; + + 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 + } + } + } + } else { + stream.eatWhile(/[\w\$_\-!$%&*+\.\/:<=>?@\^~]/); + + if (keywords && keywords.propertyIsEnumerable(stream.current())) { + returnType = BUILTIN; + } else returnType = "variable"; + } + } + return (typeof state.sExprComment == "number") ? COMMENT : returnType; + }, + + indent: function (state) { + if (state.indentStack == null) return state.indentation; + return state.indentStack.indent; + } + }; +}); + +CodeMirror.defineMIME("text/x-scheme", "scheme"); diff --git a/lib/codemirror-3.1/mode/shell/index.html b/lib/codemirror-3.1/mode/shell/index.html new file mode 100644 index 0000000000000000000000000000000000000000..9a2ef7c4cd77b079120538cc4d1c51f2a6ccc250 --- /dev/null +++ b/lib/codemirror-3.1/mode/shell/index.html @@ -0,0 +1,51 @@ + + +CodeMirror: Shell mode + + + + + + + + + + +

CodeMirror: Shell mode

+ + + + + +

MIME types defined: text/x-sh.

diff --git a/lib/codemirror-3.1/mode/shell/shell.js b/lib/codemirror-3.1/mode/shell/shell.js new file mode 100644 index 0000000000000000000000000000000000000000..9ce139b411f482aa6ea23c909c17e87e6f8ba7ea --- /dev/null +++ b/lib/codemirror-3.1/mode/shell/shell.js @@ -0,0 +1,118 @@ +CodeMirror.defineMode('shell', function() { + + var words = {}; + function define(style, string) { + var split = string.split(' '); + for(var i = 0; i < split.length; i++) { + words[split[i]] = style; + } + }; + + // Atoms + define('atom', 'true false'); + + // Keywords + define('keyword', 'if then do else elif while until for in esac fi fin ' + + 'fil done exit set unset export function'); + + // Commands + define('builtin', 'ab awk bash beep cat cc cd chown chmod chroot clear cp ' + + 'curl cut diff echo find gawk gcc get git grep kill killall ln ls make ' + + 'mkdir openssl mv nc node npm ping ps restart rm rmdir sed service sh ' + + 'shopt shred source sort sleep ssh start stop su sudo tee telnet top ' + + 'touch vi vim wall wc wget who write yes zsh'); + + function tokenBase(stream, state) { + + var sol = stream.sol(); + var ch = stream.next(); + + if (ch === '\'' || ch === '"' || ch === '`') { + state.tokens.unshift(tokenString(ch)); + 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(!/\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) { + return function(stream, state) { + var next, end = false, escaped = false; + while ((next = stream.next()) != null) { + if (next === quote && !escaped) { + end = true; + break; + } + if (next === '$' && !escaped && quote !== '\'') { + escaped = true; + stream.backUp(1); + state.tokens.unshift(tokenDollar); + break; + } + escaped = !escaped && next === '\\'; + } + if (end || !escaped) { + state.tokens.shift(); + } + return (quote === '`' || quote === ')' ? 'quote' : 'string'); + }; + }; + + var tokenDollar = function(stream, state) { + if (state.tokens.length > 1) stream.eat('$'); + var ch = stream.next(), hungry = /\w/; + if (ch === '{') hungry = /[^}]/; + if (ch === '(') { + state.tokens[0] = tokenString(')'); + return tokenize(stream, state); + } + if (!/\d/.test(ch)) { + stream.eatWhile(hungry); + stream.eat('}'); + } + 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) { + if (stream.eatSpace()) return null; + return tokenize(stream, state); + } + }; +}); + +CodeMirror.defineMIME('text/x-sh', 'shell'); diff --git a/lib/codemirror-3.1/mode/sieve/LICENSE b/lib/codemirror-3.1/mode/sieve/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8a74612cbaf5f2554fa5fa25d5359289a99b4af8 --- /dev/null +++ b/lib/codemirror-3.1/mode/sieve/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2012 Thomas Schmid + +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. diff --git a/lib/codemirror-3.1/mode/sieve/index.html b/lib/codemirror-3.1/mode/sieve/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8b549815ce37dc7ca702315b6010c198bdf6a24f --- /dev/null +++ b/lib/codemirror-3.1/mode/sieve/index.html @@ -0,0 +1,81 @@ + + + + + CodeMirror: Sieve (RFC5228) mode + + + + + + + +

CodeMirror: Sieve (RFC5228) mode

+
+ + +

MIME types defined: application/sieve.

+ + + diff --git a/lib/codemirror-3.1/mode/sieve/sieve.js b/lib/codemirror-3.1/mode/sieve/sieve.js new file mode 100644 index 0000000000000000000000000000000000000000..b1bba53e0527ae267d92f1650c303fc393190041 --- /dev/null +++ b/lib/codemirror-3.1/mode/sieve/sieve.js @@ -0,0 +1,183 @@ +/* + * See LICENSE in this directory for the license under which this code + * is released. + */ + +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"); diff --git a/lib/codemirror-3.1/mode/smalltalk/index.html b/lib/codemirror-3.1/mode/smalltalk/index.html new file mode 100644 index 0000000000000000000000000000000000000000..b7aebdb7fbac6ccea9559fd6534d7aa365fd2ab2 --- /dev/null +++ b/lib/codemirror-3.1/mode/smalltalk/index.html @@ -0,0 +1,57 @@ + + + + + CodeMirror: Smalltalk mode + + + + + + + + +

CodeMirror: Smalltalk mode

+ +
+ + + +

Simple Smalltalk mode.

+ +

MIME types defined: text/x-stsrc.

+ + diff --git a/lib/codemirror-3.1/mode/smalltalk/smalltalk.js b/lib/codemirror-3.1/mode/smalltalk/smalltalk.js new file mode 100644 index 0000000000000000000000000000000000000000..33ea11eae70ec08c8d6bae2252e712a568535410 --- /dev/null +++ b/lib/codemirror-3.1/mode/smalltalk/smalltalk.js @@ -0,0 +1,139 @@ +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 === '#') { + stream.eatWhile(/[^ .]/); + token.name = 'string-2'; + + } else if (aChar === '$') { + stream.eatWhile(/[^ ]/); + 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 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; + + state.lastToken = token; + 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'}); \ No newline at end of file diff --git a/lib/codemirror-3.1/mode/smarty/index.html b/lib/codemirror-3.1/mode/smarty/index.html new file mode 100644 index 0000000000000000000000000000000000000000..6b7debedc4be652867116f46998f0bd25098f096 --- /dev/null +++ b/lib/codemirror-3.1/mode/smarty/index.html @@ -0,0 +1,83 @@ + + + + + CodeMirror: Smarty mode + + + + + + + +

CodeMirror: Smarty mode

+ +
+ + + +
+ +
+ + + +

A plain text/Smarty mode which allows for custom delimiter tags (defaults to { and }).

+ +

MIME types defined: text/x-smarty

+ + diff --git a/lib/codemirror-3.1/mode/smarty/smarty.js b/lib/codemirror-3.1/mode/smarty/smarty.js new file mode 100644 index 0000000000000000000000000000000000000000..9ee1e4851c468821cd075b5a2a65c4a85c390632 --- /dev/null +++ b/lib/codemirror-3.1/mode/smarty/smarty.js @@ -0,0 +1,148 @@ +CodeMirror.defineMode("smarty", function(config) { + var keyFuncs = ["debug", "extends", "function", "include", "literal"]; + var last; + var regs = { + operatorChars: /[+\-*&%=<>!?]/, + validIdentifier: /[a-zA-Z0-9\_]/, + stringChar: /[\'\"]/ + }; + var leftDelim = (typeof config.mode.leftDelimiter != 'undefined') ? config.mode.leftDelimiter : "{"; + var rightDelim = (typeof config.mode.rightDelimiter != 'undefined') ? config.mode.rightDelimiter : "}"; + function ret(style, lst) { last = lst; return style; } + + + function tokenizer(stream, state) { + function chain(parser) { + state.tokenize = parser; + return parser(stream, state); + } + + if (stream.match(leftDelim, true)) { + if (stream.eat("*")) { + return chain(inBlock("comment", "*" + rightDelim)); + } + else { + state.tokenize = inSmarty; + return "tag"; + } + } + else { + // I'd like to do an eatWhile() here, but I can't get it to eat only up to the rightDelim string/char + stream.next(); + return null; + } + } + + function inSmarty(stream, state) { + if (stream.match(rightDelim, true)) { + state.tokenize = tokenizer; + return ret("tag", null); + } + + var ch = stream.next(); + if (ch == "$") { + stream.eatWhile(regs.validIdentifier); + return ret("variable-2", "variable"); + } + else if (ch == ".") { + return ret("operator", "property"); + } + else if (regs.stringChar.test(ch)) { + state.tokenize = inAttribute(ch); + return ret("string", "string"); + } + else if (regs.operatorChars.test(ch)) { + stream.eatWhile(regs.operatorChars); + return ret("operator", "operator"); + } + else if (ch == "[" || ch == "]") { + return ret("bracket", "bracket"); + } + else if (/\d/.test(ch)) { + stream.eatWhile(/\d/); + return ret("number", "number"); + } + else { + if (state.last == "variable") { + if (ch == "@") { + stream.eatWhile(regs.validIdentifier); + return ret("property", "property"); + } + else if (ch == "|") { + stream.eatWhile(regs.validIdentifier); + return ret("qualifier", "modifier"); + } + } + else if (state.last == "whitespace") { + stream.eatWhile(regs.validIdentifier); + return ret("attribute", "modifier"); + } + else if (state.last == "property") { + stream.eatWhile(regs.validIdentifier); + return ret("property", null); + } + else if (/\s/.test(ch)) { + last = "whitespace"; + return null; + } + + var str = ""; + if (ch != "/") { + str += ch; + } + var c = ""; + while ((c = stream.eat(regs.validIdentifier))) { + str += c; + } + var i, j; + for (i=0, j=keyFuncs.length; i + + + + CodeMirror: SPARQL mode + + + + + + + + +

CodeMirror: SPARQL mode

+
+ + +

MIME types defined: application/x-sparql-query.

+ + + diff --git a/lib/codemirror-3.1/mode/sparql/sparql.js b/lib/codemirror-3.1/mode/sparql/sparql.js new file mode 100644 index 0000000000000000000000000000000000000000..0b367b2a801787eedabce41e9052c4ac75fa6c14 --- /dev/null +++ b/lib/codemirror-3.1/mode/sparql/sparql.js @@ -0,0 +1,143 @@ +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", + "isblank", "isliteral", "union", "a"]); + var keywords = wordRegexp(["base", "prefix", "select", "distinct", "reduced", "construct", "describe", + "ask", "from", "named", "where", "order", "limit", "offset", "filter", "optional", + "graph", "by", "asc", "desc"]); + var operatorChars = /[*+\-<>=&|]/; + + function tokenBase(stream, state) { + var ch = stream.next(); + curPunc = null; + if (ch == "$" || ch == "?") { + 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 null; + } + else if (ch == "#") { + stream.skipToEnd(); + return "comment"; + } + else if (operatorChars.test(ch)) { + stream.eatWhile(operatorChars); + return null; + } + else if (ch == ":") { + stream.eatWhile(/[\w\d\._\-]/); + return "atom"; + } + else { + stream.eatWhile(/[_\w\d]/); + if (stream.eat(":")) { + stream.eatWhile(/[\w\d_\-]/); + return "atom"; + } + var word = stream.current(); + if (ops.test(word)) + return null; + 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); + } + 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("application/x-sparql-query", "sparql"); diff --git a/lib/codemirror-3.1/mode/sql/index.html b/lib/codemirror-3.1/mode/sql/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7ec938a1211f323dda1b7c2bbc9d912f3fb86a34 --- /dev/null +++ b/lib/codemirror-3.1/mode/sql/index.html @@ -0,0 +1,68 @@ + + + + + SQL Mode for CodeMirror + + + + + + + + + + +

SQL Mode for CodeMirror

+
+ +
+

MIME types defined: + text/x-sql, + text/x-mysql, + text/x-mariadb, + text/x-plsql. +

+

+ Tests: + normal, + verbose. +

+ + diff --git a/lib/codemirror-3.1/mode/sql/sql.js b/lib/codemirror-3.1/mode/sql/sql.js new file mode 100644 index 0000000000000000000000000000000000000000..2a16882aea8ef2fabfd0c832b8abd68e5e26a433 --- /dev/null +++ b/lib/codemirror-3.1/mode/sql/sql.js @@ -0,0 +1,268 @@ +CodeMirror.defineMode("sql", function(config, parserConfig) { + "use strict"; + + var client = parserConfig.client || {}, + atoms = parserConfig.atoms || {"false": true, "true": true, "null": true}, + builtin = parserConfig.builtin || {}, + keywords = parserConfig.keywords, + operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, + support = parserConfig.support || {}, + hooks = parserConfig.hooks || {}, + dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true}; + + 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 ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) + || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/)) { + // hex + return "number"; + } else if (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) + || (ch == "0" && stream.match(/^b[01]+/))) { + // bitstring + return "number"; + } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { + // numbers + stream.match(/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/); + return "number"; + } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { + // placeholders + return "variable-3"; + } else if (ch == '"' || ch == "'") { + // strings + state.tokenize = tokenLiteral(ch); + return state.tokenize(stream, state); + } else if (/^[\(\),\;\[\]]/.test(ch)) { + // no highlightning + return null; + } else if (ch == "#" || (ch == "-" && stream.eat("-") && stream.eat(" "))) { + // 1-line comments + stream.skipToEnd(); + return "comment"; + } else if (ch == "/" && stream.eat("*")) { + // multi-line comments + state.tokenize = tokenComment; + return state.tokenize(stream, state); + } else if (ch == ".") { + // .1 for 0.1 + if (stream.match(/^[0-9eE]+/) && support.zerolessFloat == true) { + return "number"; + } + // .table_name (ODBC) + if (stream.match(/^[a-zA-Z_]+/) && support.ODBCdotTable == true) { + return "variable-2"; + } + } else if (operatorChars.test(ch)) { + // operators + stream.eatWhile(operatorChars); + return null; + } else if (ch == '{' && + (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) { + // dates (weird ODBC syntax) + return "number"; + } else { + stream.eatWhile(/^[_\w\d]/); + var word = stream.current().toLowerCase(); + // dates (standard SQL syntax) + 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 = !escaped && ch == "\\"; + } + return "string"; + }; + } + function tokenComment(stream, state) { + while (true) { + if (stream.skipTo("*")) { + stream.next(); + if (stream.eat("/")) { + state.tokenize = tokenBase; + break; + } + } else { + stream.skipToEnd(); + break; + } + } + 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 (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; + if (cx.align) return cx.col + (textAfter.charAt(0) == cx.type ? 0 : 1); + else return cx.indent + config.indentUnit; + } + }; +}); + +(function() { + "use strict"; + + // `identifier` + function hookIdentifier(stream) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == "`" && !escaped) return "variable-2"; + escaped = !escaped && ch == "`"; + } + return null; + } + + // variable token + function hookVar(stream) { + // variables + // @@ and prefix + 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) { + // \g, etc + return stream.match(/^[a-zA-Z]\b/) ? "variable-2" : null; + } + + var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where "; + + function set(str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + CodeMirror.defineMIME("text/x-sql", { + name: "sql", + keywords: set(sqlKeywords + "begin"), + builtin: set("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"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable") + }); + + 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_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 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 global grant grants group groupby_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 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 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 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 enum 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 zerolessFloat"), + 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_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 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 global grant grants group groupby_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 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 signal slave slow smallint snapshot 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 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 enum 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 zerolessFloat"), + hooks: { + "@": hookVar, + "`": hookIdentifier, + "\\": hookClient + } + }); + + // 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 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 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"), + functions: set("abs acos add_months ascii asin atan atan2 average bfilename ceil chartorowid chr concat convert cos cosh count decode deref dual dump dup_val_on_index empty error exp false floor found glb greatest hextoraw initcap instr instrb isopen last_day least lenght lenghtb ln lower lpad ltrim lub make_ref max min mod months_between 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 nvl others power rawtohex reftohex round rowcount rowidtochar rpad rtrim sign sin sinh soundex sqlcode sqlerrm sqrt stddev substr substrb sum sysdate tan tanh to_char to_date to_label to_multi_byte to_number to_single_byte translate true trunc uid upper user userenv variance vsize"), + builtin: set("bfile blob character clob dec float int integer mlslabel natural naturaln nchar nclob number numeric nvarchar2 real rowtype signtype smallint string varchar varchar2"), + operatorChars: /^[*+\-%<>!=~]/, + dateSQL: set("date time timestamp") + }); +}()); diff --git a/lib/codemirror-3.1/mode/stex/index.html b/lib/codemirror-3.1/mode/stex/index.html new file mode 100644 index 0000000000000000000000000000000000000000..2dafe698160dfd7015cb9c68a286228b8f91d8f8 --- /dev/null +++ b/lib/codemirror-3.1/mode/stex/index.html @@ -0,0 +1,98 @@ + + + + + CodeMirror: sTeX mode + + + + + + + +

CodeMirror: sTeX mode

+
+ + +

MIME types defined: text/x-stex.

+ +

Parsing/Highlighting Tests: normal, verbose.

+ + + diff --git a/lib/codemirror-3.1/mode/stex/stex.js b/lib/codemirror-3.1/mode/stex/stex.js new file mode 100644 index 0000000000000000000000000000000000000000..42ed82c6690f93471b3e403f84fedd021f5191dc --- /dev/null +++ b/lib/codemirror-3.1/mode/stex/stex.js @@ -0,0 +1,175 @@ +/* + * Author: Constantin Jucovschi (c.jucovschi@jacobs-university.de) + * Licence: MIT + */ + +CodeMirror.defineMode("stex", function() +{ + 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) { + if (state.cmdState.length>0) { + var plug = state.cmdState.pop(); + plug.closeBracket(); + } + } + + function applyMostPowerful(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.styleIdentifier(); + } + return null; + } + + function addPluginPattern(pluginName, cmdStyle, brackets, styles) { + return function () { + this.name=pluginName; + this.bracketNo = 0; + this.style=cmdStyle; + this.styles = styles; + this.brackets = brackets; + + this.styleIdentifier = function() { + if (this.bracketNo<=this.styles.length) + return this.styles[this.bracketNo-1]; + else + return null; + }; + this.openBracket = function() { + this.bracketNo++; + return "bracket"; + }; + this.closeBracket = function() {}; + }; + } + + var plugins = new Array(); + + plugins["importmodule"] = addPluginPattern("importmodule", "tag", "{[", ["string", "builtin"]); + plugins["documentclass"] = addPluginPattern("documentclass", "tag", "{[", ["", "atom"]); + plugins["usepackage"] = addPluginPattern("documentclass", "tag", "[", ["atom"]); + plugins["begin"] = addPluginPattern("documentclass", "tag", "[", ["atom"]); + plugins["end"] = addPluginPattern("documentclass", "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; + } + + function normal(source, state) { + if (source.match(/^\\[a-zA-Z@]+/)) { + var cmdName = source.current(); + cmdName = cmdName.substr(1, cmdName.length-1); + var plug; + if (plugins.hasOwnProperty(cmdName)) { + plug = plugins[cmdName]; + } else { + plug = 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"; + } + + var ch = source.next(); + if (ch == "%") { + // special case: % at end of its own line; stay in same state + if (!source.eol()) { + setState(state, inCComment); + } + 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-_]/); + return applyMostPowerful(state); + } + } + + function inCComment(source, state) { + source.skipToEnd(); + setState(state, normal); + return "comment"; + } + + function beginParams(source, state) { + var ch = source.peek(); + if (ch == '{' || ch == '[') { + var 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); + lastPlug = peekCommand(state); + if (lastPlug) { + popCommand(state); + } + return normal(source, state); + } + + return { + startState: function() { return { f:normal, cmdState:[] }; }, + copyState: function(s) { return { f: s.f, cmdState: s.cmdState.slice(0, s.cmdState.length) }; }, + + token: function(stream, state) { + var t = state.f(stream, state); + return t; + } + }; +}); + +CodeMirror.defineMIME("text/x-stex", "stex"); +CodeMirror.defineMIME("text/x-latex", "stex"); diff --git a/lib/codemirror-3.1/mode/stex/test.js b/lib/codemirror-3.1/mode/stex/test.js new file mode 100644 index 0000000000000000000000000000000000000000..e7e9c29c1e1de002381804ae86da00db6d68789c --- /dev/null +++ b/lib/codemirror-3.1/mode/stex/test.js @@ -0,0 +1,104 @@ +(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 }]"); +})(); diff --git a/lib/codemirror-3.1/mode/tiddlywiki/index.html b/lib/codemirror-3.1/mode/tiddlywiki/index.html new file mode 100644 index 0000000000000000000000000000000000000000..848f33a592b55d4099fa22bc674cf90554f134a4 --- /dev/null +++ b/lib/codemirror-3.1/mode/tiddlywiki/index.html @@ -0,0 +1,142 @@ + + + + + CodeMirror: TiddlyWiki mode + + + + + + + + + +

CodeMirror: TiddlyWiki mode

+ +
+ + + +

TiddlyWiki mode supports a single configuration.

+ +

MIME types defined: text/x-tiddlywiki.

+ + diff --git a/lib/codemirror-3.1/mode/tiddlywiki/tiddlywiki.css b/lib/codemirror-3.1/mode/tiddlywiki/tiddlywiki.css new file mode 100644 index 0000000000000000000000000000000000000000..9a69b639f8a71389a99dacb03bd03e4bb2a57ded --- /dev/null +++ b/lib/codemirror-3.1/mode/tiddlywiki/tiddlywiki.css @@ -0,0 +1,14 @@ +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; +} diff --git a/lib/codemirror-3.1/mode/tiddlywiki/tiddlywiki.js b/lib/codemirror-3.1/mode/tiddlywiki/tiddlywiki.js new file mode 100644 index 0000000000000000000000000000000000000000..0d506ee6088b6bcd06b551a378e0452b836467f1 --- /dev/null +++ b/lib/codemirror-3.1/mode/tiddlywiki/tiddlywiki.js @@ -0,0 +1,353 @@ +/*** +|''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''|http://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! +***/ +//{{{ +CodeMirror.defineMode("tiddlywiki", function () { + // Tokenizer + var textwords = {}; + + var keywords = function () { + function kw(type) { + return { type: type, style: "macro"}; + } + return { + "allTags": kw('allTags'), "closeAll": kw('closeAll'), "list": kw('list'), + "newJournal": kw('newJournal'), "newTiddler": kw('newTiddler'), + "permaview": kw('permaview'), "saveChanges": kw('saveChanges'), + "search": kw('search'), "slider": kw('slider'), "tabs": kw('tabs'), + "tag": kw('tag'), "tagging": kw('tagging'), "tags": kw('tags'), + "tiddler": kw('tiddler'), "timeline": kw('timeline'), + "today": kw('today'), "version": kw('version'), "option": kw('option'), + + "with": kw('with'), + "filter": kw('filter') + }; + }(); + + 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); + } + + // 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 jsTokenBase(stream, state) { + var sol = stream.sol(), ch; + + state.block = false; // indicates the start of a code block. + + ch = stream.peek(); // don't eat, to make matching simpler + + // 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 ret('quote', 'quote'); + } + if (stream.match(reWikiCommentStart) || stream.match(reWikiCommentStop)) { + return ret('code', 'comment'); + } + if (stream.match(reJsCodeStart) || stream.match(reJsCodeStop) || stream.match(reXmlCodeStart) || stream.match(reXmlCodeStop)) { + return ret('code', 'comment'); + } + if (stream.match(reHR)) { + return ret('hr', 'hr'); + } + } // sol + ch = stream.next(); + + if (sol && /[\/\*!#;:>|]/.test(ch)) { + if (ch == "!") { // tw header + stream.skipToEnd(); + return ret("header", "header"); + } + if (ch == "*") { // tw list + stream.eatWhile('*'); + return ret("list", "comment"); + } + if (ch == "#") { // tw numbered list + stream.eatWhile('#'); + return ret("list", "comment"); + } + if (ch == ";") { // definition list, term + stream.eatWhile(';'); + return ret("list", "comment"); + } + if (ch == ":") { // definition list, description + stream.eatWhile(':'); + return ret("list", "comment"); + } + if (ch == ">") { // single line quote + stream.eatWhile(">"); + return ret("quote", "quote"); + } + if (ch == '|') { + return ret('table', 'header'); + } + } + + if (ch == '{' && stream.match(/\{\{/)) { + return chain(stream, state, twTokenCode); + } + + // rudimentary html:// file:// link matching. TW knows much more ... + if (/[hf]/i.test(ch)) { + if (/[ti]/i.test(stream.peek()) && stream.match(/\b(ttps?|tp|ile):\/\/[\-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i)) { + return ret("link", "link"); + } + } + // just a little string indicator, don't want to have the whole string covered + if (ch == '"') { + return ret('string', 'string'); + } + if (ch == '~') { // _no_ CamelCase indicator should be bold + return ret('text', 'brace'); + } + if (/[\[\]]/.test(ch)) { // check for [[..]] + if (stream.peek() == ch) { + stream.next(); + return ret('brace', 'brace'); + } + } + if (ch == "@") { // check for space link. TODO fix @@...@@ highlighting + stream.eatWhile(isSpaceName); + return ret("link", "link"); + } + if (/\d/.test(ch)) { // numbers + stream.eatWhile(/\d/); + return ret("number", "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 == "_") { // tw underline + if (stream.eat("_")) { + return chain(stream, state, twTokenUnderline); + } + } + // strikethrough and mdash handling + if (ch == "-") { + if (stream.eat("-")) { + // if strikethrough looks ugly, change CSS. + if (stream.peek() != ' ') + return chain(stream, state, twTokenStrike); + // mdash + if (stream.peek() == ' ') + return ret('text', 'brace'); + } + } + if (ch == "'") { // tw bold + if (stream.eat("'")) { + return chain(stream, state, twTokenStrong); + } + } + if (ch == "<") { // tw macro + if (stream.eat("<")) { + return chain(stream, state, twTokenMacro); + } + } + else { + return ret(ch); + } + + // core macro handling + stream.eatWhile(/[\w\$_]/); + var word = stream.current(), + known = textwords.propertyIsEnumerable(word) && textwords[word]; + + return known ? ret(known.type, known.style, word) : ret("text", null, word); + + } // jsTokenBase() + + // tw invisible comment + function twTokenComment(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "%"); + } + return ret("comment", "comment"); + } + + // tw strong / bold + function twTokenStrong(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "'" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "'"); + } + return ret("text", "strong"); + } + + // tw code + function twTokenCode(stream, state) { + var ch, sb = state.block; + + if (sb && stream.current()) { + return ret("code", "comment"); + } + + if (!sb && stream.match(reUntilCodeStop)) { + state.tokenize = jsTokenBase; + return ret("code", "comment"); + } + + if (sb && stream.sol() && stream.match(reCodeBlockStop)) { + state.tokenize = jsTokenBase; + return ret("code", "comment"); + } + + ch = stream.next(); + return (sb) ? ret("code", "comment") : ret("code", "comment"); + } + + // tw em / italic + function twTokenEm(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "/" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "/"); + } + return ret("text", "em"); + } + + // tw underlined text + function twTokenUnderline(stream, state) { + var maybeEnd = false, + ch; + while (ch = stream.next()) { + if (ch == "_" && maybeEnd) { + state.tokenize = jsTokenBase; + break; + } + maybeEnd = (ch == "_"); + } + return ret("text", "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 = jsTokenBase; + break; + } + maybeEnd = (ch == "-"); + } + return ret("text", "strikethrough"); + } + + // macro + function twTokenMacro(stream, state) { + var ch, word, known; + + if (stream.current() == '<<') { + return ret('brace', 'macro'); + } + + ch = stream.next(); + if (!ch) { + state.tokenize = jsTokenBase; + return ret(ch); + } + if (ch == ">") { + if (stream.peek() == '>') { + stream.next(); + state.tokenize = jsTokenBase; + return ret("brace", "macro"); + } + } + + stream.eatWhile(/[\w\$_]/); + word = stream.current(); + known = keywords.propertyIsEnumerable(word) && keywords[word]; + + if (known) { + return ret(known.type, known.style, word); + } + else { + return ret("macro", null, word); + } + } + + // Interface + return { + startState: function () { + return { + tokenize: jsTokenBase, + indented: 0, + level: 0 + }; + }, + + token: function (stream, state) { + if (stream.eatSpace()) return null; + var style = state.tokenize(stream, state); + return style; + }, + + electricChars: "" + }; +}); + +CodeMirror.defineMIME("text/x-tiddlywiki", "tiddlywiki"); +//}}} diff --git a/lib/codemirror-3.1/mode/tiki/index.html b/lib/codemirror-3.1/mode/tiki/index.html new file mode 100644 index 0000000000000000000000000000000000000000..7b85a44a7e0b1edd81da263419e0bafdc7fe8707 --- /dev/null +++ b/lib/codemirror-3.1/mode/tiki/index.html @@ -0,0 +1,81 @@ + + + + CodeMirror: Tiki wiki mode + + + + + + + + +

CodeMirror: Tiki wiki mode

+ +
+ + + + + diff --git a/lib/codemirror-3.1/mode/tiki/tiki.css b/lib/codemirror-3.1/mode/tiki/tiki.css new file mode 100644 index 0000000000000000000000000000000000000000..e3c3c0fd2d2bfdec704f3fcc9c4ad0903a99284a --- /dev/null +++ b/lib/codemirror-3.1/mode/tiki/tiki.css @@ -0,0 +1,26 @@ +.cm-tw-syntaxerror { + color: #FFFFFF; + background-color: #990000; +} + +.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; +} \ No newline at end of file diff --git a/lib/codemirror-3.1/mode/tiki/tiki.js b/lib/codemirror-3.1/mode/tiki/tiki.js new file mode 100644 index 0000000000000000000000000000000000000000..81e87ab213c90d3fc37e1e1811aad33e9b5cecdc --- /dev/null +++ b/lib/codemirror-3.1/mode/tiki/tiki.js @@ -0,0 +1,309 @@ +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(); + var tagName = ""; + var c; + while ((c = stream.eat(/[^\s\u00a0=\"\'\/?(}]/))) tagName += c; + state.tokenize = inPlugin; + return "tag"; + break; + case "_": //bold + if (stream.eat("_")) { + return chain(inBlock("strong", "__", inText)); + } + break; + case "'": //italics + if (stream.eat("'")) { + // Italic text + 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 == ">") { + ch = 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: "/" + }; +}); + +//I figure, why not +CodeMirror.defineMIME("text/tiki", "tiki"); diff --git a/lib/codemirror-3.1/mode/turtle/index.html b/lib/codemirror-3.1/mode/turtle/index.html new file mode 100644 index 0000000000000000000000000000000000000000..5e56e5755ca0d7521d0bb589333f45330c86c38f --- /dev/null +++ b/lib/codemirror-3.1/mode/turtle/index.html @@ -0,0 +1,39 @@ + + + + + CodeMirror: Turtle mode + + + + + + + +

    CodeMirror: Turtle mode

    +
    + + +

    MIME types defined: text/turtle.

    + + + diff --git a/lib/codemirror-3.1/mode/turtle/turtle.js b/lib/codemirror-3.1/mode/turtle/turtle.js new file mode 100644 index 0000000000000000000000000000000000000000..5c7c28eb02b18e656deccbdb420d26c9ce450607 --- /dev/null +++ b/lib/codemirror-3.1/mode/turtle/turtle.js @@ -0,0 +1,145 @@ +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); + } + }; +}); + +CodeMirror.defineMIME("text/turtle", "turtle"); diff --git a/lib/codemirror-3.1/mode/vb/LICENSE.txt b/lib/codemirror-3.1/mode/vb/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..60839703a97eb623070a57da751df1dfc903327e --- /dev/null +++ b/lib/codemirror-3.1/mode/vb/LICENSE.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2012 Codility Limited, 107 Cheapside, London EC2V 6DN, UK + +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. diff --git a/lib/codemirror-3.1/mode/vb/index.html b/lib/codemirror-3.1/mode/vb/index.html new file mode 100644 index 0000000000000000000000000000000000000000..74dd5e81619b3e38bedc341f43aac0dc8ed4ef9e --- /dev/null +++ b/lib/codemirror-3.1/mode/vb/index.html @@ -0,0 +1,88 @@ + + + + CodeMirror: VB.NET mode + + + + + + + + + +

    CodeMirror: VB.NET mode

    + + + +
    + +
    +
    
    +  

    MIME type defined: text/x-vb.

    + + diff --git a/lib/codemirror-3.1/mode/vb/vb.js b/lib/codemirror-3.1/mode/vb/vb.js new file mode 100644 index 0000000000000000000000000000000000000000..764c07101acaf950bffb8a9ee0900896fa2ff3b9 --- /dev/null +++ b/lib/codemirror-3.1/mode/vb/vb.js @@ -0,0 +1,260 @@ +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 wordOperators = wordRegexp(['and', 'or', 'not', 'xor', 'in']); + 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; + + + + + 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); + current = stream.current(); + 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; + } + + }; + return external; +}); + +CodeMirror.defineMIME("text/x-vb", "vb"); + diff --git a/lib/codemirror-3.1/mode/vbscript/index.html b/lib/codemirror-3.1/mode/vbscript/index.html new file mode 100644 index 0000000000000000000000000000000000000000..8c86f9ef9424fd506b8ac2c598e6c4477ac2433f --- /dev/null +++ b/lib/codemirror-3.1/mode/vbscript/index.html @@ -0,0 +1,42 @@ + + + + + CodeMirror: VBScript mode + + + + + + + +

    CodeMirror: VBScript mode

    + +
    + + + +

    MIME types defined: text/vbscript.

    + + + diff --git a/lib/codemirror-3.1/mode/vbscript/vbscript.js b/lib/codemirror-3.1/mode/vbscript/vbscript.js new file mode 100644 index 0000000000000000000000000000000000000000..65d6c212767a64d4dc34df33d3185d56fc6ffc8b --- /dev/null +++ b/lib/codemirror-3.1/mode/vbscript/vbscript.js @@ -0,0 +1,26 @@ +CodeMirror.defineMode("vbscript", function() { + var regexVBScriptKeyword = /^(?:Call|Case|CDate|Clear|CInt|CLng|Const|CStr|Description|Dim|Do|Each|Else|ElseIf|End|Err|Error|Exit|False|For|Function|If|LCase|Loop|LTrim|Next|Nothing|Now|Number|On|Preserve|Quit|ReDim|Resume|RTrim|Select|Set|Sub|Then|To|Trim|True|UBound|UCase|Until|VbCr|VbCrLf|VbLf|VbTab)$/im; + + return { + token: function(stream) { + if (stream.eatSpace()) return null; + var ch = stream.next(); + if (ch == "'") { + stream.skipToEnd(); + return "comment"; + } + if (ch == '"') { + stream.skipTo('"'); + return "string"; + } + + if (/\w/.test(ch)) { + stream.eatWhile(/\w/); + if (regexVBScriptKeyword.test(stream.current())) return "keyword"; + } + return null; + } + }; +}); + +CodeMirror.defineMIME("text/vbscript", "vbscript"); diff --git a/lib/codemirror-3.1/mode/velocity/index.html b/lib/codemirror-3.1/mode/velocity/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fb59cb590df7c0c11e38719611454fa2ef1cb963 --- /dev/null +++ b/lib/codemirror-3.1/mode/velocity/index.html @@ -0,0 +1,103 @@ + + + + + CodeMirror: Velocity mode + + + + + + + + +

    CodeMirror: Velocity mode

    +
    + + +

    MIME types defined: text/velocity.

    + + + diff --git a/lib/codemirror-3.1/mode/velocity/velocity.js b/lib/codemirror-3.1/mode/velocity/velocity.js new file mode 100644 index 0000000000000000000000000000000000000000..43a97ba676585dd67a2bb1bcd08e8152db8afb93 --- /dev/null +++ b/lib/codemirror-3.1/mode/velocity/velocity.js @@ -0,0 +1,144 @@ +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 $velocityCount"); + 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 string? + if ((ch == '"' || ch == "'") && 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; + return null; + } + // start of a number value? + else if (/\d/.test(ch)) { + stream.eatWhile(/[\w\.]/); + return "number"; + } + // multi line comment? + else if (ch == "#" && stream.eat("*")) { + return chain(stream, state, tokenComment); + } + // unparsed content? + else if (ch == "#" && stream.match(/ *\[ *\[/)) { + return chain(stream, state, tokenUnparsed); + } + // single line comment? + else if (ch == "#" && stream.eat("#")) { + stream.skipToEnd(); + return "comment"; + } + // variable? + else if (ch == "$") { + stream.eatWhile(/[\w\d\$_\.{}]/); + // is it one of the specials? + if (specials && specials.propertyIsEnumerable(stream.current().toLowerCase())) { + return "keyword"; + } + else { + state.beforeParams = true; + return "builtin"; + } + } + // is it a operator? + else if (isOperatorChar.test(ch)) { + stream.eatWhile(isOperatorChar); + return "operator"; + } + else { + // get the whole word + stream.eatWhile(/[\w\$_{}]/); + var word = stream.current().toLowerCase(); + // 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()=="(") { + state.beforeParams = true; + return "keyword"; + } + // default: just a "word" + 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"; + } + // Interface + + 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/velocity", "velocity"); diff --git a/lib/codemirror-3.1/mode/verilog/index.html b/lib/codemirror-3.1/mode/verilog/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c1d14d682a1b61bccd60b836978986788cfa9cd3 --- /dev/null +++ b/lib/codemirror-3.1/mode/verilog/index.html @@ -0,0 +1,210 @@ + + + + + CodeMirror: Verilog mode + + + + + + + +

    CodeMirror: Verilog mode

    + +
    + + + +

    Simple mode that tries to handle Verilog-like languages as well as it + can. Takes one configuration parameters: keywords, an + object whose property names are the keywords in the language.

    + +

    MIME types defined: text/x-verilog (Verilog code).

    + + diff --git a/lib/codemirror-3.1/mode/verilog/verilog.js b/lib/codemirror-3.1/mode/verilog/verilog.js new file mode 100644 index 0000000000000000000000000000000000000000..708de23f491ba57870ae4fee4d56b6730f9c43ad --- /dev/null +++ b/lib/codemirror-3.1/mode/verilog/verilog.js @@ -0,0 +1,182 @@ +CodeMirror.defineMode("verilog", function(config, parserConfig) { + var indentUnit = config.indentUnit, + keywords = parserConfig.keywords || {}, + blockKeywords = parserConfig.blockKeywords || {}, + atoms = parserConfig.atoms || {}, + hooks = parserConfig.hooks || {}, + multiLineStrings = parserConfig.multiLineStrings; + var isOperatorChar = /[&|~> + + + + CodeMirror: XML mode + + + + + + + +

    CodeMirror: XML mode

    +
    + +

    The XML mode supports two 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.
    +
    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.

    + + diff --git a/lib/codemirror-3.1/mode/xml/xml.js b/lib/codemirror-3.1/mode/xml/xml.js new file mode 100644 index 0000000000000000000000000000000000000000..7b11fd6746cef7e6b6d80300143a6973357dd4c3 --- /dev/null +++ b/lib/codemirror-3.1/mode/xml/xml.js @@ -0,0 +1,324 @@ +CodeMirror.defineMode("xml", function(config, parserConfig) { + var indentUnit = config.indentUnit; + var Kludges = parserConfig.htmlMode ? { + 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}, + 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 + } : { + autoSelfClosers: {}, + implicitlyClosed: {}, + contextGrabbers: {}, + doNotIndent: {}, + allowUnquoted: false, + allowMissing: false + }; + var alignCDATA = parserConfig.alignCDATA; + + // Return variables for tokenizers + var tagName, type; + + 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 { + var isClose = stream.eat("/"); + tagName = ""; + var c; + while ((c = stream.eat(/[^\s\u00a0=<>\"\'\/?]/))) tagName += c; + if (!tagName) return "error"; + type = isClose ? "closeTag" : "openTag"; + state.tokenize = inTag; + return "tag"; + } + } + 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; + } + } + + function inTag(stream, state) { + var ch = stream.next(); + if (ch == ">" || (ch == "/" && stream.eat(">"))) { + state.tokenize = inText; + type = ch == ">" ? "endTag" : "selfcloseTag"; + return "tag"; + } + else if (ch == "=") { + type = "equals"; + return null; + } + else if (/[\'\"]/.test(ch)) { + state.tokenize = inAttribute(ch); + return state.tokenize(stream, state); + } + else { + stream.eatWhile(/[^\s\u00a0=<>\"\']/); + return "word"; + } + } + + function inAttribute(quote) { + return function(stream, state) { + while (!stream.eol()) { + if (stream.next() == quote) { + state.tokenize = inTag; + break; + } + } + return "string"; + }; + } + + 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"; + }; + } + + 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(tagName, startOfLine) { + var noIndent = Kludges.doNotIndent.hasOwnProperty(tagName) || (curState.context && curState.context.noIndent); + curState.context = { + prev: curState.context, + tagName: tagName, + indent: curState.indented, + startOfLine: startOfLine, + noIndent: noIndent + }; + } + function popContext() { + if (curState.context) curState.context = curState.context.prev; + } + + function element(type) { + if (type == "openTag") { + curState.tagName = tagName; + return cont(attributes, endtag(curState.startOfLine)); + } else if (type == "closeTag") { + var err = false; + if (curState.context) { + if (curState.context.tagName != tagName) { + if (Kludges.implicitlyClosed.hasOwnProperty(curState.context.tagName.toLowerCase())) { + popContext(); + } + err = !curState.context || curState.context.tagName != tagName; + } + } else { + err = true; + } + if (err) setStyle = "error"; + return cont(endclosetag(err)); + } + return cont(); + } + function endtag(startOfLine) { + return function(type) { + var tagName = curState.tagName; + curState.tagName = null; + if (type == "selfcloseTag" || + (type == "endTag" && Kludges.autoSelfClosers.hasOwnProperty(tagName.toLowerCase()))) { + maybePopContext(tagName.toLowerCase()); + return cont(); + } + if (type == "endTag") { + maybePopContext(tagName.toLowerCase()); + pushContext(tagName, startOfLine); + return cont(); + } + return cont(); + }; + } + function endclosetag(err) { + return function(type) { + if (err) setStyle = "error"; + if (type == "endTag") { popContext(); return cont(); } + setStyle = "error"; + return cont(arguments.callee); + }; + } + function maybePopContext(nextTagName) { + var parentTagName; + while (true) { + if (!curState.context) { + return; + } + parentTagName = curState.context.tagName.toLowerCase(); + if (!Kludges.contextGrabbers.hasOwnProperty(parentTagName) || + !Kludges.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) { + return; + } + popContext(); + } + } + + function attributes(type) { + if (type == "word") {setStyle = "attribute"; return cont(attribute, attributes);} + if (type == "endTag" || type == "selfcloseTag") return pass(); + setStyle = "error"; + return cont(attributes); + } + function attribute(type) { + if (type == "equals") return cont(attvalue, attributes); + if (!Kludges.allowMissing) setStyle = "error"; + else if (type == "word") setStyle = "attribute"; + return (type == "endTag" || type == "selfcloseTag") ? pass() : cont(); + } + function attvalue(type) { + if (type == "string") return cont(attvaluemaybe); + if (type == "word" && Kludges.allowUnquoted) {setStyle = "string"; return cont();} + setStyle = "error"; + return (type == "endTag" || type == "selfCloseTag") ? pass() : cont(); + } + function attvaluemaybe(type) { + if (type == "string") return cont(attvaluemaybe); + else return pass(); + } + + return { + startState: function() { + return {tokenize: inText, cc: [], indented: 0, startOfLine: true, tagName: null, context: null}; + }, + + token: function(stream, state) { + if (stream.sol()) { + state.startOfLine = true; + state.indented = stream.indentation(); + } + if (stream.eatSpace()) return null; + + setStyle = type = tagName = null; + var style = state.tokenize(stream, state); + state.type = type; + 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, fullLine) { + var context = state.context; + if ((state.tokenize != inTag && state.tokenize != inText) || + context && context.noIndent) + return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0; + if (alignCDATA && / + +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. \ No newline at end of file diff --git a/lib/codemirror-3.1/mode/xquery/index.html b/lib/codemirror-3.1/mode/xquery/index.html new file mode 100644 index 0000000000000000000000000000000000000000..27acb89786deac66a4ace494fd1b7f451fa0b3b5 --- /dev/null +++ b/lib/codemirror-3.1/mode/xquery/index.html @@ -0,0 +1,221 @@ + + + + + + CodeMirror: XQuery mode + + + + + + + + +

    CodeMirror: XQuery mode

    + +
    + +
    + + + +

    MIME types defined: application/xquery.

    + +

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

    + + + diff --git a/lib/codemirror-3.1/mode/xquery/test.js b/lib/codemirror-3.1/mode/xquery/test.js new file mode 100644 index 0000000000000000000000000000000000000000..41719dd169dc3c7acdae6f67c2db3a3293611ef9 --- /dev/null +++ b/lib/codemirror-3.1/mode/xquery/test.js @@ -0,0 +1,64 @@ +// 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] [keyword private] [keyword function] [def&variable local:declare]() {()}[variable ;]", + " [keyword declare] [keyword private] [keyword function] [def&variable local:private]() {()}[variable ;]", + " [keyword declare] [keyword private] [keyword function] [def&variable local:function]() {()}[variable ;]", + " [keyword declare] [keyword 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"] [variable 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\\\"])"); +})(); diff --git a/lib/codemirror-3.1/mode/xquery/xquery.js b/lib/codemirror-3.1/mode/xquery/xquery.js new file mode 100644 index 0000000000000000000000000000000000000000..d5c859e00a6deecf42ad0bb683f4cf588081d4ae --- /dev/null +++ b/lib/codemirror-3.1/mode/xquery/xquery.js @@ -0,0 +1,450 @@ +/* +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. +*/ +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(){ + // conveinence functions used to build keywords object + function kw(type) {return {type: type, style: "keyword"};} + var A = kw("keyword a") + , B = kw("keyword b") + , C = kw("keyword c") + , 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 = { + 'if': A, 'switch': A, 'while': A, 'for': A, + 'else': B, 'then': B, 'try': B, 'finally': B, 'catch': B, + 'element': C, 'attribute': C, 'let': C, 'implements': C, 'import': C, 'module': C, 'namespace': C, + 'return': C, 'super': C, 'this': C, 'throws': C, 'where': C, 'private': C, + ',': punctuation, + 'null': atom, 'fn:false()': atom, 'fn:true()': atom + }; + + // 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','ancestor','ancestor-or-self','and','as','ascending','assert','attribute','before', + 'by','case','cast','child','comment','declare','default','define','descendant','descendant-or-self', + 'descending','document','document-node','element','else','eq','every','except','external','following', + 'following-sibling','follows','for','function','if','import','in','instance','intersect','item', + 'let','module','namespace','node','node','of','only','or','order','parent','precedes','preceding', + 'preceding-sibling','processing-instruction','ref','return','returns','satisfies','schema','schema-element', + 'self','some','sortby','stable','text','then','to','treat','typeswitch','union','variable','version','where', + 'xquery', 'empty-sequence']; + 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:string', 'xs:float', 'xs:decimal', 'xs:double', 'xs:integer', 'xs:boolean', 'xs:date', 'xs:dateTime', + 'xs:time', 'xs:duration', 'xs:dayTimeDuration', 'xs:time', 'xs:yearMonthDuration', 'numeric', 'xs:hexBinary', + 'xs:base64Binary', 'xs:anyURI', 'xs:QName', 'xs:byte','xs:boolean','xs:anyURI','xf: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; + }(); + + // 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 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 ret("tag", "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 ret("", null); + } + // end code block + else if(ch == "}") { + popStateStack(state); + return ret("", null); + } + // if we're in an XML block + else if(isInXmlBlock(state)) { + if(ch == ">") + return ret("tag", "tag"); + else if(ch == "/" && stream.eat(">")) { + popStateStack(state); + return ret("tag", "tag"); + } + else + return ret("word", "variable"); + } + // if a number + else if (/\d/.test(ch)) { + stream.match(/^\d*(?:\.\d*)?(?:E[+\-]?\d+)?/); + return ret("number", "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 ret("operator", "keyword"); + } + // open paren + else if(ch === "(") { + pushStateStack(state, { type: "paren"}); + return ret("", null); + } + // close paren + else if(ch === ")") { + popStateStack(state); + return ret("", null); + } + // open paren + else if(ch === "[") { + pushStateStack(state, { type: "bracket"}); + return ret("", null); + } + // close paren + else if(ch === "]") { + popStateStack(state); + return ret("", 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 ret("word", "variable", word); + } + // 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 ? ret(known.type, known.style, word) : + ret("word", "variable", word); + } + } + + // 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 ret("comment", "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 ret("string", "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 ret("string", "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 ret("string", "string"); + } + + } + } + + return ret("string", "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 ret("variable", "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 ret("tag", "tag"); + } + // self closing tag without attributes? + if(!stream.eat("/")) + pushStateStack(state, { type: "tag", name: name, tokenize: tokenBase}); + if(!stream.eat(">")) { + state.tokenize = tokenAttribute; + return ret("tag", "tag"); + } + else { + state.tokenize = tokenBase; + } + return ret("tag", "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 ret("tag", "tag"); + } + if(ch == ">") { + if(isInXmlAttributeBlock(state)) popStateStack(state); + return ret("tag", "tag"); + } + if(ch == "=") + return ret("", null); + // quoted string + if (ch == '"' || ch == "'") + return chain(stream, state, tokenString(ch, tokenAttribute)); + + if(!isInXmlAttributeBlock(state)) + pushStateStack(state, { type: "attribute", name: name, 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 ret("attribute", "attribute"); + } + + // handle comments, including nested + function tokenXMLComment(stream, state) { + var ch; + while (ch = stream.next()) { + if (ch == "-" && stream.match("->", true)) { + state.tokenize = tokenBase; + return ret("comment", "comment"); + } + } + } + + + // handle CDATA + function tokenCDATA(stream, state) { + var ch; + while (ch = stream.next()) { + if (ch == "]" && stream.match("]", true)) { + state.tokenize = tokenBase; + return ret("comment", "comment"); + } + } + } + + // handle preprocessing instructions + function tokenPreProcessing(stream, state) { + var ch; + while (ch = stream.next()) { + if (ch == "?" && stream.match(">", true)) { + state.tokenize = tokenBase; + return ret("comment", "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; + } + }; + +}); + +CodeMirror.defineMIME("application/xquery", "xquery"); diff --git a/lib/codemirror-3.1/mode/yaml/index.html b/lib/codemirror-3.1/mode/yaml/index.html new file mode 100644 index 0000000000000000000000000000000000000000..65e1ea73fb525efc2449e3312fd51ae89cc97c6a --- /dev/null +++ b/lib/codemirror-3.1/mode/yaml/index.html @@ -0,0 +1,68 @@ + + + + + CodeMirror: YAML mode + + + + + + + +

    CodeMirror: YAML mode

    +
    + + +

    MIME types defined: text/x-yaml.

    + + + diff --git a/lib/codemirror-3.1/mode/yaml/yaml.js b/lib/codemirror-3.1/mode/yaml/yaml.js new file mode 100644 index 0000000000000000000000000000000000000000..59e2641a016eedc79ee7c43259ee1f6923c384ff --- /dev/null +++ b/lib/codemirror-3.1/mode/yaml/yaml.js @@ -0,0 +1,95 @@ +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.skipToEnd(); return "comment"; } + 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'; } + } + /* pairs (associative arrays) -> key */ + if (!state.pair && stream.match(/^\s*([a-z0-9\._-])+(?=\s*:)/i)) { + state.pair = true; + state.keyCol = stream.indentation(); + return "atom"; + } + if (state.pair && stream.match(/^:\s*/)) { state.pairStart = true; 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'; } + } + + /* 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 + }; + } + }; +}); + +CodeMirror.defineMIME("text/x-yaml", "yaml"); diff --git a/lib/codemirror-3.1/mode/z80/index.html b/lib/codemirror-3.1/mode/z80/index.html new file mode 100644 index 0000000000000000000000000000000000000000..133c870e326feac6df2ebbd8f17fefade31a83f0 --- /dev/null +++ b/lib/codemirror-3.1/mode/z80/index.html @@ -0,0 +1,39 @@ + + + + + CodeMirror: Z80 assembly mode + + + + + + + +

    CodeMirror: Z80 assembly mode

    + +
    + + + +

    MIME type defined: text/x-z80.

    + + diff --git a/lib/codemirror-3.1/mode/z80/z80.js b/lib/codemirror-3.1/mode/z80/z80.js new file mode 100644 index 0000000000000000000000000000000000000000..c026790dc733d9918b5422c9e53c33777a7b162e --- /dev/null +++ b/lib/codemirror-3.1/mode/z80/z80.js @@ -0,0 +1,113 @@ +CodeMirror.defineMode('z80', function() +{ + var 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; + var keywords2 = /^(call|j[pr]|ret[in]?)\b/i; + var keywords3 = /^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+)\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/)) + { + w = stream.current(); + + if (stream.indentation()) + { + if (state.context == 1 && variables1.test(w)) + return 'variable-2'; + + if (state.context == 2 && variables2.test(w)) + return 'variable-3'; + + if (keywords1.test(w)) + { + state.context = 1; + return 'keyword'; + } + else if (keywords2.test(w)) + { + state.context = 2; + return 'keyword'; + } + else if (keywords3.test(w)) + { + state.context = 3; + return 'keyword'; + } + + if (errors.test(w)) + return 'error'; + } + else if (numbers.test(w)) + { + 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 = 4; + + 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"); diff --git a/lib/codemirror-3.1/package.json b/lib/codemirror-3.1/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8b435d1537c773325cc86f263ec55c5af420a602 --- /dev/null +++ b/lib/codemirror-3.1/package.json @@ -0,0 +1,21 @@ +{ + "name": "codemirror", + "version":"3.10.00", + "main": "codemirror.js", + "description": "In-browser code editing made bearable", + "licenses": [{"type": "MIT", + "url": "http://codemirror.net/LICENSE"}], + "directories": {"lib": "./lib"}, + "scripts": {"test": "node ./test/run.js"}, + "devDependencies": {"node-static": "0.6.0"}, + "bugs": "http://github.com/marijnh/CodeMirror/issues", + "keywords": ["JavaScript", "CodeMirror", "Editor"], + "homepage": "http://codemirror.net", + "maintainers":[{"name": "Marijn Haverbeke", + "email": "marijnh@gmail.com", + "web": "http://marijnhaverbeke.nl"}], + "repositories": [{"type": "git", + "url": "http://marijnhaverbeke.nl/git/codemirror"}, + {"type": "git", + "url": "https://github.com/marijnh/CodeMirror.git"}] +} diff --git a/lib/codemirror-3.1/test/doc_test.js b/lib/codemirror-3.1/test/doc_test.js new file mode 100644 index 0000000000000000000000000000000000000000..3e04e155b387373e85db8a5847d146c8107e79fa --- /dev/null +++ b/lib/codemirror-3.1/test/doc_test.js @@ -0,0 +1,329 @@ +(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 ((debug && !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)); + eqPos(b.getCursor(), Pos(2, 1)); + a.replaceRange("-1\n0\n", Pos(0, 0)); + eq(b.firstLine(), 3); + eqPos(b.getCursor(), Pos(4, 1)); + a.undo(); + eqPos(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 eqPos(a, b, msg) { + function str(p) { return "{line:" + p.line + ",ch:" + p.ch + "}"; } + 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 is(a, msg) { + if (!a) throw new Failure(label("assertion failed", msg)); +} + +function countTests() { + if (!debug) return tests.length; + var sum = 0; + for (var i = 0; i < tests.length; ++i) { + var name = tests[i].name; + if (indexOf(debug, name) != -1 || + indexOf(debug, name.split("_")[0] + "_*") != -1) + ++sum; + } + return sum; +} diff --git a/lib/codemirror-3.1/test/index.html b/lib/codemirror-3.1/test/index.html new file mode 100644 index 0000000000000000000000000000000000000000..24bdf999d8a9d47a9f98bf99f82c8faf000aef30 --- /dev/null +++ b/lib/codemirror-3.1/test/index.html @@ -0,0 +1,181 @@ + + + + + CodeMirror: Test Suite + + + + + + + + + + + + + +

    CodeMirror: Test Suite

    + +

    A limited set of programmatic sanity tests for CodeMirror.

    + +
    +
    Ran 0 of 0 tests
    +
    +

    Please enable JavaScript...

    +
    + +
    + + + + + + + + + + + + + + + + + + + diff --git a/lib/codemirror-3.1/test/lint/acorn.js b/lib/codemirror-3.1/test/lint/acorn.js new file mode 100644 index 0000000000000000000000000000000000000000..6323b1fc6a039760ac7f87ebd03052669fe84269 --- /dev/null +++ b/lib/codemirror-3.1/test/lint/acorn.js @@ -0,0 +1,1593 @@ +// Acorn is a tiny, fast JavaScript parser written in JavaScript. +// +// Acorn was written by Marijn Haverbeke and released under an MIT +// license. The Unicode regexps (for identifiers and whitespace) were +// taken from [Esprima](http://esprima.org) by Ariya Hidayat. +// +// Git repositories for Acorn are available at +// +// http://marijnhaverbeke.nl/git/acorn +// https://github.com/marijnh/acorn.git +// +// Please use the [github bug tracker][ghbt] to report issues. +// +// [ghbt]: https://github.com/marijnh/acorn/issues + +(function(exports) { + "use strict"; + + exports.version = "0.0.1"; + + // The main exported interface (under `window.acorn` when in the + // browser) is a `parse` function that takes a code string and + // returns an abstract syntax tree as specified by [Mozilla parser + // API][api], with the caveat that the SpiderMonkey-specific syntax + // (`let`, `yield`, inline XML, etc) is not recognized. + // + // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API + + var options, input, inputLen, sourceFile; + + exports.parse = function(inpt, opts) { + input = String(inpt); inputLen = input.length; + options = opts || {}; + for (var opt in defaultOptions) if (!options.hasOwnProperty(opt)) + options[opt] = defaultOptions[opt]; + sourceFile = options.sourceFile || null; + return parseTopLevel(options.program); + }; + + // A second optional argument can be given to further configure + // the parser process. These options are recognized: + + var defaultOptions = exports.defaultOptions = { + // `ecmaVersion` indicates the ECMAScript version to parse. Must + // be either 3 or 5. This + // influences support for strict mode, the set of reserved words, and + // support for getters and setter. + ecmaVersion: 5, + // Turn on `strictSemicolons` to prevent the parser from doing + // automatic semicolon insertion. + strictSemicolons: false, + // When `allowTrailingCommas` is false, the parser will not allow + // trailing commas in array and object literals. + allowTrailingCommas: true, + // By default, reserved words are not enforced. Enable + // `forbidReserved` to enforce them. + forbidReserved: false, + // When `trackComments` is turned on, the parser will attach + // `commentsBefore` and `commentsAfter` properties to AST nodes + // holding arrays of strings. A single comment may appear in both + // a `commentsBefore` and `commentsAfter` array (of the nodes + // after and before it), but never twice in the before (or after) + // array of different nodes. + trackComments: false, + // When `locations` is on, `loc` properties holding objects with + // `start` and `end` properties in `{line, column}` form (with + // line being 1-based and column 0-based) will be attached to the + // nodes. + locations: false, + // Nodes have their start and end characters offsets recorded in + // `start` and `end` properties (directly on the node, rather than + // the `loc` object, which holds line/column data. To also add a + // [semi-standardized][range] `range` property holding a `[start, + // end]` array with the same numbers, set the `ranges` option to + // `true`. + // + // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678 + ranges: false, + // It is possible to parse multiple files into a single AST by + // passing the tree produced by parsing the first file as + // `program` option in subsequent parses. This will add the + // toplevel forms of the parsed file to the `Program` (top) node + // of an existing parse tree. + program: null, + // When `location` is on, you can pass this to record the source + // file in every node's `loc` object. + sourceFile: null + }; + + // The `getLineInfo` function is mostly useful when the + // `locations` option is off (for performance reasons) and you + // want to find the line/column position for a given character + // offset. `input` should be the code string that the offset refers + // into. + + var getLineInfo = exports.getLineInfo = function(input, offset) { + for (var line = 1, cur = 0;;) { + lineBreak.lastIndex = cur; + var match = lineBreak.exec(input); + if (match && match.index < offset) { + ++line; + cur = match.index + match[0].length; + } else break; + } + return {line: line, column: offset - cur}; + }; + + // Acorn is organized as a tokenizer and a recursive-descent parser. + // Both use (closure-)global variables to keep their state and + // communicate. We already saw the `options`, `input`, and + // `inputLen` variables above (set in `parse`). + + // The current position of the tokenizer in the input. + + var tokPos; + + // The start and end offsets of the current token. + + var tokStart, tokEnd; + + // When `options.locations` is true, these hold objects + // containing the tokens start and end line/column pairs. + + var tokStartLoc, tokEndLoc; + + // The type and value of the current token. Token types are objects, + // named by variables against which they can be compared, and + // holding properties that describe them (indicating, for example, + // the precedence of an infix operator, and the original name of a + // keyword token). The kind of value that's held in `tokVal` depends + // on the type of the token. For literals, it is the literal value, + // for operators, the operator name, and so on. + + var tokType, tokVal; + + // These are used to hold arrays of comments when + // `options.trackComments` is true. + + var tokCommentsBefore, tokCommentsAfter; + + // Interal state for the tokenizer. To distinguish between division + // operators and regular expressions, it remembers whether the last + // token was one that is allowed to be followed by an expression. + // (If it is, a slash is probably a regexp, if it isn't it's a + // division operator. See the `parseStatement` function for a + // caveat.) + + var tokRegexpAllowed, tokComments; + + // When `options.locations` is true, these are used to keep + // track of the current line, and know when a new line has been + // entered. See the `curLineLoc` function. + + var tokCurLine, tokLineStart, tokLineStartNext; + + // These store the position of the previous token, which is useful + // when finishing a node and assigning its `end` position. + + var lastStart, lastEnd, lastEndLoc; + + // This is the parser's state. `inFunction` is used to reject + // `return` statements outside of functions, `labels` to verify that + // `break` and `continue` have somewhere to jump to, and `strict` + // indicates whether strict mode is on. + + var inFunction, labels, strict; + + // This function is used to raise exceptions on parse errors. It + // takes either a `{line, column}` object or an offset integer (into + // the current `input`) as `pos` argument. It attaches the position + // to the end of the error message, and then raises a `SyntaxError` + // with that message. + + function raise(pos, message) { + if (typeof pos == "number") pos = getLineInfo(input, pos); + message += " (" + pos.line + ":" + pos.column + ")"; + throw new SyntaxError(message); + } + + // ## Token types + + // The assignment of fine-grained, information-carrying type objects + // allows the tokenizer to store the information it has about a + // token in a way that is very cheap for the parser to look up. + + // All token type variables start with an underscore, to make them + // easy to recognize. + + // These are the general types. The `type` property is only used to + // make them recognizeable when debugging. + + var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"}; + var _name = {type: "name"}, _eof = {type: "eof"}; + + // Keyword tokens. The `keyword` property (also used in keyword-like + // operators) indicates that the token originated from an + // identifier-like word, which is used when parsing property names. + // + // The `beforeExpr` property is used to disambiguate between regular + // expressions and divisions. It is set on all token types that can + // be followed by an expression (thus, a slash after them would be a + // regular expression). + // + // `isLoop` marks a keyword as starting a loop, which is important + // to know when parsing a label, in order to allow or disallow + // continue jumps to that label. + + var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"}; + var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"}; + var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true}; + var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"}; + var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"}; + var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"}; + var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true}; + var _this = {keyword: "this"}; + + // The keywords that denote values. + + var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true}; + var _false = {keyword: "false", atomValue: false}; + + // Some keywords are treated as regular operators. `in` sometimes + // (when parsing `for`) needs to be tested against specifically, so + // we assign a variable name to it for quick comparing. + + var _in = {keyword: "in", binop: 7, beforeExpr: true}; + + // Map keyword names to token types. + + var keywordTypes = {"break": _break, "case": _case, "catch": _catch, + "continue": _continue, "debugger": _debugger, "default": _default, + "do": _do, "else": _else, "finally": _finally, "for": _for, + "function": _function, "if": _if, "return": _return, "switch": _switch, + "throw": _throw, "try": _try, "var": _var, "while": _while, "with": _with, + "null": _null, "true": _true, "false": _false, "new": _new, "in": _in, + "instanceof": {keyword: "instanceof", binop: 7}, "this": _this, + "typeof": {keyword: "typeof", prefix: true}, + "void": {keyword: "void", prefix: true}, + "delete": {keyword: "delete", prefix: true}}; + + // Punctuation token types. Again, the `type` property is purely for debugging. + + var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true}; + var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"}; + var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true}; + var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true}; + + // Operators. These carry several kinds of properties to help the + // parser use them properly (the presence of these properties is + // what categorizes them as operators). + // + // `binop`, when present, specifies that this operator is a binary + // operator, and will refer to its precedence. + // + // `prefix` and `postfix` mark the operator as a prefix or postfix + // unary operator. `isUpdate` specifies that the node produced by + // the operator should be of type UpdateExpression rather than + // simply UnaryExpression (`++` and `--`). + // + // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as + // binary operators with a very low precedence, that should result + // in AssignmentExpression nodes. + + var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true}; + var _assign = {isAssign: true, beforeExpr: true}, _plusmin = {binop: 9, prefix: true, beforeExpr: true}; + var _incdec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true}; + var _bin1 = {binop: 1, beforeExpr: true}, _bin2 = {binop: 2, beforeExpr: true}; + var _bin3 = {binop: 3, beforeExpr: true}, _bin4 = {binop: 4, beforeExpr: true}; + var _bin5 = {binop: 5, beforeExpr: true}, _bin6 = {binop: 6, beforeExpr: true}; + var _bin7 = {binop: 7, beforeExpr: true}, _bin8 = {binop: 8, beforeExpr: true}; + var _bin10 = {binop: 10, beforeExpr: true}; + + // This is a trick taken from Esprima. It turns out that, on + // non-Chrome browsers, to check whether a string is in a set, a + // predicate containing a big ugly `switch` statement is faster than + // a regular expression, and on Chrome the two are about on par. + // This function uses `eval` (non-lexical) to produce such a + // predicate from a space-separated string of words. + // + // It starts by sorting the words by length. + + function makePredicate(words) { + words = words.split(" "); + var f = "", cats = []; + out: for (var i = 0; i < words.length; ++i) { + for (var j = 0; j < cats.length; ++j) + if (cats[j][0].length == words[i].length) { + cats[j].push(words[i]); + continue out; + } + cats.push([words[i]]); + } + function compareTo(arr) { + if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";"; + f += "switch(str){"; + for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":"; + f += "return true}return false;"; + } + + // When there are more than three length categories, an outer + // switch first dispatches on the lengths, to save on comparisons. + + if (cats.length > 3) { + cats.sort(function(a, b) {return b.length - a.length;}); + f += "switch(str.length){"; + for (var i = 0; i < cats.length; ++i) { + var cat = cats[i]; + f += "case " + cat[0].length + ":"; + compareTo(cat); + } + f += "}"; + + // Otherwise, simply generate a flat `switch` statement. + + } else { + compareTo(words); + } + return new Function("str", f); + } + + // The ECMAScript 3 reserved word list. + + var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"); + + // ECMAScript 5 reserved words. + + var isReservedWord5 = makePredicate("class enum extends super const export import"); + + // The additional reserved words in strict mode. + + var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield"); + + // The forbidden variable names in strict mode. + + var isStrictBadIdWord = makePredicate("eval arguments"); + + // And the keywords. + + var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"); + + // ## Character categories + + // Big ugly regular expressions that match characters in the + // whitespace, identifier, and identifier-start categories. These + // are only applied when a character is found to actually have a + // code point above 128. + + var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/; + var nonASCIIidentifierStartChars = "\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-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\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\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\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\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\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-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\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\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\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-\u209c\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\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\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-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\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\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\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"; + var nonASCIIidentifierChars = "\u0371-\u0374\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + + // Whether a single character denotes a newline. + + var newline = /[\n\r\u2028\u2029]/; + + // Matches a whole line break (where CRLF is considered a single + // line break). Used to count lines. + + var lineBreak = /\r\n|[\n\r\u2028\u2029]/g; + + // Test whether a given character code starts an identifier. + + function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code < 91) return true; + if (code < 97) return code === 95; + if (code < 123)return true; + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + // Test whether a given character is part of an identifier. + + function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code < 91) return true; + if (code < 97) return code === 95; + if (code < 123)return true; + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + // ## Tokenizer + + // These are used when `options.locations` is on, in order to track + // the current line number and start of line offset, in order to set + // `tokStartLoc` and `tokEndLoc`. + + function nextLineStart() { + lineBreak.lastIndex = tokLineStart; + var match = lineBreak.exec(input); + return match ? match.index + match[0].length : input.length + 1; + } + + function curLineLoc() { + while (tokLineStartNext <= tokPos) { + ++tokCurLine; + tokLineStart = tokLineStartNext; + tokLineStartNext = nextLineStart(); + } + return {line: tokCurLine, column: tokPos - tokLineStart}; + } + + // Reset the token state. Used at the start of a parse. + + function initTokenState() { + tokCurLine = 1; + tokPos = tokLineStart = 0; + tokLineStartNext = nextLineStart(); + tokRegexpAllowed = true; + tokComments = null; + skipSpace(); + } + + // Called at the end of every token. Sets `tokEnd`, `tokVal`, + // `tokCommentsAfter`, and `tokRegexpAllowed`, and skips the space + // after the token, so that the next one's `tokStart` will point at + // the right position. + + function finishToken(type, val) { + tokEnd = tokPos; + if (options.locations) tokEndLoc = curLineLoc(); + tokType = type; + skipSpace(); + tokVal = val; + tokCommentsAfter = tokComments; + tokRegexpAllowed = type.beforeExpr; + } + + function skipBlockComment() { + var end = input.indexOf("*/", tokPos += 2); + if (end === -1) raise(tokPos - 2, "Unterminated comment"); + if (options.trackComments) + (tokComments || (tokComments = [])).push(input.slice(tokPos, end)); + tokPos = end + 2; + } + + function skipLineComment() { + var start = tokPos; + var ch = input.charCodeAt(tokPos+=2); + while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8329) { + ++tokPos; + ch = input.charCodeAt(tokPos); + } + (tokComments || (tokComments = [])).push(input.slice(start, tokPos)); + } + + // Called at the start of the parse and after every token. Skips + // whitespace and comments, and, if `options.trackComments` is on, + // will store all skipped comments in `tokComments`. + + function skipSpace() { + tokComments = null; + while (tokPos < inputLen) { + var ch = input.charCodeAt(tokPos); + if (ch === 47) { // '/' + var next = input.charCodeAt(tokPos+1); + if (next === 42) { // '*' + skipBlockComment(); + } else if (next === 47) { // '/' + skipLineComment(); + } else break; + } else if (ch < 14 && ch > 8) { + ++tokPos; + } else if (ch === 32 || ch === 160) { // ' ', '\xa0' + ++tokPos; + } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) { + ++tokPos; + } else { + break; + } + } + } + + // ### Token reading + + // This is the function that is called to fetch the next token. It + // is somewhat obscure, because it works in character codes rather + // than characters, and because operator parsing has been inlined + // into it. + // + // All in the name of speed. + // + // The `forceRegexp` parameter is used in the one case where the + // `tokRegexpAllowed` trick does not work. See `parseStatement`. + + function readToken(forceRegexp) { + tokStart = tokPos; + if (options.locations) tokStartLoc = curLineLoc(); + tokCommentsBefore = tokComments; + if (forceRegexp) return readRegexp(); + if (tokPos >= inputLen) return finishToken(_eof); + + var code = input.charCodeAt(tokPos); + // Identifier or keyword. '\uXXXX' sequences are allowed in + // identifiers, so '\' also dispatches to that. + if (isIdentifierStart(code) || code === 92 /* '\' */) return readWord(); + var next = input.charCodeAt(tokPos+1); + + switch(code) { + // The interpretation of a dot depends on whether it is followed + // by a digit. + case 46: // '.' + if (next >= 48 && next <= 57) return readNumber(String.fromCharCode(code)); + ++tokPos; + return finishToken(_dot); + + // Punctuation tokens. + case 40: ++tokPos; return finishToken(_parenL); + case 41: ++tokPos; return finishToken(_parenR); + case 59: ++tokPos; return finishToken(_semi); + case 44: ++tokPos; return finishToken(_comma); + case 91: ++tokPos; return finishToken(_bracketL); + case 93: ++tokPos; return finishToken(_bracketR); + case 123: ++tokPos; return finishToken(_braceL); + case 125: ++tokPos; return finishToken(_braceR); + case 58: ++tokPos; return finishToken(_colon); + case 63: ++tokPos; return finishToken(_question); + + // '0x' is a hexadecimal number. + case 48: // '0' + if (next === 120 || next === 88) return readHexNumber(); + // Anything else beginning with a digit is an integer, octal + // number, or float. + case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9 + return readNumber(String.fromCharCode(code)); + + // Quotes produce strings. + case 34: case 39: // '"', "'" + return readString(code); + + // Operators are parsed inline in tiny state machines. '=' (61) is + // often referred to. `finishOp` simply skips the amount of + // characters it is given as second argument, and returns a token + // of the type given by its first argument. + + case 47: // '/' + if (tokRegexpAllowed) {++tokPos; return readRegexp();} + if (next === 61) return finishOp(_assign, 2); + return finishOp(_slash, 1); + + case 37: case 42: // '%*' + if (next === 61) return finishOp(_assign, 2); + return finishOp(_bin10, 1); + + case 124: case 38: // '|&' + if (next === code) return finishOp(code === 124 ? _bin1 : _bin2, 2); + if (next === 61) return finishOp(_assign, 2); + return finishOp(code === 124 ? _bin3 : _bin5, 1); + + case 94: // '^' + if (next === 61) return finishOp(_assign, 2); + return finishOp(_bin4, 1); + + case 43: case 45: // '+-' + if (next === code) return finishOp(_incdec, 2); + if (next === 61) return finishOp(_assign, 2); + return finishOp(_plusmin, 1); + + case 60: case 62: // '<>' + var size = 1; + if (next === code) { + size = code === 62 && input.charCodeAt(tokPos+2) === 62 ? 3 : 2; + if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1); + return finishOp(_bin8, size); + } + if (next === 61) + size = input.charCodeAt(tokPos+2) === 61 ? 3 : 2; + return finishOp(_bin7, size); + + case 61: case 33: // '=!' + if (next === 61) return finishOp(_bin6, input.charCodeAt(tokPos+2) === 61 ? 3 : 2); + return finishOp(code === 61 ? _eq : _prefix, 1); + + case 126: // '~' + return finishOp(_prefix, 1); + } + + // If we are here, we either found a non-ASCII identifier + // character, or something that's entirely disallowed. + var ch = String.fromCharCode(code); + if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord(); + raise(tokPos, "Unexpected character '" + ch + "'"); + } + + function finishOp(type, size) { + var str = input.slice(tokPos, tokPos + size); + tokPos += size; + finishToken(type, str); + } + + // Parse a regular expression. Some context-awareness is necessary, + // since a '/' inside a '[]' set does not end the expression. + + function readRegexp() { + var content = "", escaped, inClass, start = tokPos; + for (;;) { + if (tokPos >= inputLen) raise(start, "Unterminated regular expression"); + var ch = input.charAt(tokPos); + if (newline.test(ch)) raise(start, "Unterminated regular expression"); + if (!escaped) { + if (ch === "[") inClass = true; + else if (ch === "]" && inClass) inClass = false; + else if (ch === "/" && !inClass) break; + escaped = ch === "\\"; + } else escaped = false; + ++tokPos; + } + var content = input.slice(start, tokPos); + ++tokPos; + // Need to use `readWord1` because '\uXXXX' sequences are allowed + // here (don't ask). + var mods = readWord1(); + if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regexp flag"); + return finishToken(_regexp, new RegExp(content, mods)); + } + + // Read an integer in the given radix. Return null if zero digits + // were read, the integer value otherwise. When `len` is given, this + // will return `null` unless the integer has exactly `len` digits. + + function readInt(radix, len) { + var start = tokPos, total = 0; + for (;;) { + var code = input.charCodeAt(tokPos), val; + if (code >= 97) val = code - 97 + 10; // a + else if (code >= 65) val = code - 65 + 10; // A + else if (code >= 48 && code <= 57) val = code - 48; // 0-9 + else val = Infinity; + if (val >= radix) break; + ++tokPos; + total = total * radix + val; + } + if (tokPos === start || len != null && tokPos - start !== len) return null; + + return total; + } + + function readHexNumber() { + tokPos += 2; // 0x + var val = readInt(16); + if (val == null) raise(tokStart + 2, "Expected hexadecimal number"); + if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number"); + return finishToken(_num, val); + } + + // Read an integer, octal integer, or floating-point number. + + function readNumber(ch) { + var start = tokPos, isFloat = ch === "."; + if (!isFloat && readInt(10) == null) raise(start, "Invalid number"); + if (isFloat || input.charAt(tokPos) === ".") { + var next = input.charAt(++tokPos); + if (next === "-" || next === "+") ++tokPos; + if (readInt(10) === null && ch === ".") raise(start, "Invalid number"); + isFloat = true; + } + if (/e/i.test(input.charAt(tokPos))) { + var next = input.charAt(++tokPos); + if (next === "-" || next === "+") ++tokPos; + if (readInt(10) === null) raise(start, "Invalid number") + isFloat = true; + } + if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number"); + + var str = input.slice(start, tokPos), val; + if (isFloat) val = parseFloat(str); + else if (ch !== "0" || str.length === 1) val = parseInt(str, 10); + else if (/[89]/.test(str) || strict) raise(start, "Invalid number"); + else val = parseInt(str, 8); + return finishToken(_num, val); + } + + // Read a string value, interpreting backslash-escapes. + + function readString(quote) { + tokPos++; + var str = []; + for (;;) { + if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant"); + var ch = input.charCodeAt(tokPos); + if (ch === quote) { + ++tokPos; + return finishToken(_string, String.fromCharCode.apply(null, str)); + } + if (ch === 92) { // '\' + ch = input.charCodeAt(++tokPos); + var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3)); + if (octal) octal = octal[0]; + while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, octal.length - 1); + if (octal === "0") octal = null; + ++tokPos; + if (octal) { + if (strict) raise(tokPos - 2, "Octal literal in strict mode"); + str.push(parseInt(octal, 8)); + tokPos += octal.length - 1; + } else { + switch (ch) { + case 110: str.push(10); break; // 'n' -> '\n' + case 114: str.push(13); break; // 'r' -> '\r' + case 120: str.push(readHexChar(2)); break; // 'x' + case 117: str.push(readHexChar(4)); break; // 'u' + case 85: str.push(readHexChar(8)); break; // 'U' + case 116: str.push(9); break; // 't' -> '\t' + case 98: str.push(8); break; // 'b' -> '\b' + case 118: str.push(11); break; // 'v' -> '\u000b' + case 102: str.push(12); break; // 'f' -> '\f' + case 48: str.push(0); break; // 0 -> '\0' + case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos; // '\r\n' + case 10: break; // ' \n' + default: str.push(ch); break; + } + } + } else { + if (ch === 13 || ch === 10 || ch === 8232 || ch === 8329) raise(tokStart, "Unterminated string constant"); + if (ch !== 92) str.push(ch); // '\' + ++tokPos; + } + } + } + + // Used to read character escape sequences ('\x', '\u', '\U'). + + function readHexChar(len) { + var n = readInt(16, len); + if (n === null) raise(tokStart, "Bad character escape sequence"); + return n; + } + + // Used to signal to callers of `readWord1` whether the word + // contained any escape sequences. This is needed because words with + // escape sequences must not be interpreted as keywords. + + var containsEsc; + + // Read an identifier, and return it as a string. Sets `containsEsc` + // to whether the word contained a '\u' escape. + // + // Only builds up the word character-by-character when it actually + // containeds an escape, as a micro-optimization. + + function readWord1() { + containsEsc = false; + var word, first = true, start = tokPos; + for (;;) { + var ch = input.charCodeAt(tokPos); + if (isIdentifierChar(ch)) { + if (containsEsc) word += input.charAt(tokPos); + ++tokPos; + } else if (ch === 92) { // "\" + if (!containsEsc) word = input.slice(start, tokPos); + containsEsc = true; + if (input.charCodeAt(++tokPos) != 117) // "u" + raise(tokPos, "Expecting Unicode escape sequence \\uXXXX"); + ++tokPos; + var esc = readHexChar(4); + var escStr = String.fromCharCode(esc); + if (!escStr) raise(tokPos - 1, "Invalid Unicode escape"); + if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc))) + raise(tokPos - 4, "Invalid Unicode escape"); + word += escStr; + } else { + break; + } + first = false; + } + return containsEsc ? word : input.slice(start, tokPos); + } + + // Read an identifier or keyword token. Will check for reserved + // words when necessary. + + function readWord() { + var word = readWord1(); + var type = _name; + if (!containsEsc) { + if (isKeyword(word)) type = keywordTypes[word]; + else if (options.forbidReserved && + (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(word) || + strict && isStrictReservedWord(word)) + raise(tokStart, "The keyword '" + word + "' is reserved"); + } + return finishToken(type, word); + } + + // ## Parser + + // A recursive descent parser operates by defining functions for all + // syntactic elements, and recursively calling those, each function + // advancing the input stream and returning an AST node. Precedence + // of constructs (for example, the fact that `!x[1]` means `!(x[1])` + // instead of `(!x)[1]` is handled by the fact that the parser + // function that parses unary prefix operators is called first, and + // in turn calls the function that parses `[]` subscripts — that + // way, it'll receive the node for `x[1]` already parsed, and wraps + // *that* in the unary operator node. + // + // Acorn uses an [operator precedence parser][opp] to handle binary + // operator precedence, because it is much more compact than using + // the technique outlined above, which uses different, nesting + // functions to specify precedence, for all of the ten binary + // precedence levels that JavaScript defines. + // + // [opp]: http://en.wikipedia.org/wiki/Operator-precedence_parser + + // ### Parser utilities + + // Continue to the next token. + + function next() { + lastStart = tokStart; + lastEnd = tokEnd; + lastEndLoc = tokEndLoc; + readToken(); + } + + // Enter strict mode. Re-reads the next token to please pedantic + // tests ("use strict"; 010; -- should fail). + + function setStrict(strct) { + strict = strct; + tokPos = lastEnd; + skipSpace(); + readToken(); + } + + // Start an AST node, attaching a start offset and optionally a + // `commentsBefore` property to it. + + function startNode() { + var node = {type: null, start: tokStart, end: null}; + if (options.trackComments && tokCommentsBefore) { + node.commentsBefore = tokCommentsBefore; + tokCommentsBefore = null; + } + if (options.locations) + node.loc = {start: tokStartLoc, end: null, source: sourceFile}; + if (options.ranges) + node.range = [tokStart, 0]; + return node; + } + + // Start a node whose start offset/comments information should be + // based on the start of another node. For example, a binary + // operator node is only started after its left-hand side has + // already been parsed. + + function startNodeFrom(other) { + var node = {type: null, start: other.start}; + if (other.commentsBefore) { + node.commentsBefore = other.commentsBefore; + other.commentsBefore = null; + } + if (options.locations) + node.loc = {start: other.loc.start, end: null, source: other.loc.source}; + if (options.ranges) + node.range = [other.range[0], 0]; + + return node; + } + + // Finish an AST node, adding `type`, `end`, and `commentsAfter` + // properties. + // + // We keep track of the last node that we finished, in order + // 'bubble' `commentsAfter` properties up to the biggest node. I.e. + // in '`1 + 1 // foo', the comment should be attached to the binary + // operator node, not the second literal node. + + var lastFinishedNode; + + function finishNode(node, type) { + node.type = type; + node.end = lastEnd; + if (options.trackComments) { + if (tokCommentsAfter) { + node.commentsAfter = tokCommentsAfter; + tokCommentsAfter = null; + } else if (lastFinishedNode && lastFinishedNode.end === lastEnd) { + node.commentsAfter = lastFinishedNode.commentsAfter; + lastFinishedNode.commentsAfter = null; + } + lastFinishedNode = node; + } + if (options.locations) + node.loc.end = lastEndLoc; + if (options.ranges) + node.range[1] = lastEnd; + return node; + } + + // Test whether a statement node is the string literal `"use strict"`. + + function isUseStrict(stmt) { + return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && + stmt.expression.type === "Literal" && stmt.expression.value === "use strict"; + } + + // Predicate that tests whether the next token is of the given + // type, and if yes, consumes it as a side effect. + + function eat(type) { + if (tokType === type) { + next(); + return true; + } + } + + // Test whether a semicolon can be inserted at the current position. + + function canInsertSemicolon() { + return !options.strictSemicolons && + (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart))); + } + + // Consume a semicolon, or, failing that, see if we are allowed to + // pretend that there is a semicolon at this position. + + function semicolon() { + if (!eat(_semi) && !canInsertSemicolon()) unexpected(); + } + + // Expect a token of a given type. If found, consume it, otherwise, + // raise an unexpected token error. + + function expect(type) { + if (tokType === type) next(); + else unexpected(); + } + + // Raise an unexpected token error. + + function unexpected() { + raise(tokStart, "Unexpected token"); + } + + // Verify that a node is an lval — something that can be assigned + // to. + + function checkLVal(expr) { + if (expr.type !== "Identifier" && expr.type !== "MemberExpression") + raise(expr.start, "Assigning to rvalue"); + if (strict && expr.type === "Identifier" && isStrictBadIdWord(expr.name)) + raise(expr.start, "Assigning to " + expr.name + " in strict mode"); + } + + // ### Statement parsing + + // Parse a program. Initializes the parser, reads any number of + // statements, and wraps them in a Program node. Optionally takes a + // `program` argument. If present, the statements will be appended + // to its body instead of creating a new node. + + function parseTopLevel(program) { + initTokenState(); + lastStart = lastEnd = tokPos; + if (options.locations) lastEndLoc = curLineLoc(); + inFunction = strict = null; + labels = []; + readToken(); + + var node = program || startNode(), first = true; + if (!program) node.body = []; + while (tokType !== _eof) { + var stmt = parseStatement(); + node.body.push(stmt); + if (first && isUseStrict(stmt)) setStrict(true); + first = false; + } + return finishNode(node, "Program"); + }; + + var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"}; + + // Parse a single statement. + // + // If expecting a statement and finding a slash operator, parse a + // regular expression literal. This is to handle cases like + // `if (foo) /blah/.exec(foo);`, where looking at the previous token + // does not help. + + function parseStatement() { + if (tokType === _slash) + readToken(true); + + var starttype = tokType, node = startNode(); + + // Most types of statements are recognized by the keyword they + // start with. Many are trivial to parse, some require a bit of + // complexity. + + switch (starttype) { + case _break: case _continue: + next(); + var isBreak = starttype === _break; + if (eat(_semi) || canInsertSemicolon()) node.label = null; + else if (tokType !== _name) unexpected(); + else { + node.label = parseIdent(); + semicolon(); + } + + // Verify that there is an actual destination to break or + // continue to. + for (var i = 0; i < labels.length; ++i) { + var lab = labels[i]; + if (node.label == null || lab.name === node.label.name) { + if (lab.kind != null && (isBreak || lab.kind === "loop")) break; + if (node.label && isBreak) break; + } + } + if (i === labels.length) raise(node.start, "Unsyntactic " + starttype.keyword); + return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement"); + + case _debugger: + next(); + return finishNode(node, "DebuggerStatement"); + + case _do: + next(); + labels.push(loopLabel); + node.body = parseStatement(); + labels.pop(); + expect(_while); + node.test = parseParenExpression(); + semicolon(); + return finishNode(node, "DoWhileStatement"); + + // Disambiguating between a `for` and a `for`/`in` loop is + // non-trivial. Basically, we have to parse the init `var` + // statement or expression, disallowing the `in` operator (see + // the second parameter to `parseExpression`), and then check + // whether the next token is `in`. When there is no init part + // (semicolon immediately after the opening parenthesis), it is + // a regular `for` loop. + + case _for: + next(); + labels.push(loopLabel); + expect(_parenL); + if (tokType === _semi) return parseFor(node, null); + if (tokType === _var) { + var init = startNode(); + next(); + parseVar(init, true); + if (init.declarations.length === 1 && eat(_in)) + return parseForIn(node, init); + return parseFor(node, init); + } + var init = parseExpression(false, true); + if (eat(_in)) {checkLVal(init); return parseForIn(node, init);} + return parseFor(node, init); + + case _function: + next(); + return parseFunction(node, true); + + case _if: + next(); + node.test = parseParenExpression(); + node.consequent = parseStatement(); + node.alternate = eat(_else) ? parseStatement() : null; + return finishNode(node, "IfStatement"); + + case _return: + if (!inFunction) raise(tokStart, "'return' outside of function"); + next(); + + // In `return` (and `break`/`continue`), the keywords with + // optional arguments, we eagerly look for a semicolon or the + // possibility to insert one. + + if (eat(_semi) || canInsertSemicolon()) node.argument = null; + else { node.argument = parseExpression(); semicolon(); } + return finishNode(node, "ReturnStatement"); + + case _switch: + next(); + node.discriminant = parseParenExpression(); + node.cases = []; + expect(_braceL); + labels.push(switchLabel); + + // Statements under must be grouped (by label) in SwitchCase + // nodes. `cur` is used to keep the node that we are currently + // adding statements to. + + for (var cur, sawDefault; tokType != _braceR;) { + if (tokType === _case || tokType === _default) { + var isCase = tokType === _case; + if (cur) finishNode(cur, "SwitchCase"); + node.cases.push(cur = startNode()); + cur.consequent = []; + next(); + if (isCase) cur.test = parseExpression(); + else { + if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true; + cur.test = null; + } + expect(_colon); + } else { + if (!cur) unexpected(); + cur.consequent.push(parseStatement()); + } + } + if (cur) finishNode(cur, "SwitchCase"); + next(); // Closing brace + labels.pop(); + return finishNode(node, "SwitchStatement"); + + case _throw: + next(); + if (newline.test(input.slice(lastEnd, tokStart))) + raise(lastEnd, "Illegal newline after throw"); + node.argument = parseExpression(); + return finishNode(node, "ThrowStatement"); + + case _try: + next(); + node.block = parseBlock(); + node.handlers = []; + while (tokType === _catch) { + var clause = startNode(); + next(); + expect(_parenL); + clause.param = parseIdent(); + if (strict && isStrictBadIdWord(clause.param.name)) + raise(clause.param.start, "Binding " + clause.param.name + " in strict mode"); + expect(_parenR); + clause.guard = null; + clause.body = parseBlock(); + node.handlers.push(finishNode(clause, "CatchClause")); + } + node.finalizer = eat(_finally) ? parseBlock() : null; + if (!node.handlers.length && !node.finalizer) + raise(node.start, "Missing catch or finally clause"); + return finishNode(node, "TryStatement"); + + case _var: + next(); + node = parseVar(node); + semicolon(); + return node; + + case _while: + next(); + node.test = parseParenExpression(); + labels.push(loopLabel); + node.body = parseStatement(); + labels.pop(); + return finishNode(node, "WhileStatement"); + + case _with: + if (strict) raise(tokStart, "'with' in strict mode"); + next(); + node.object = parseParenExpression(); + node.body = parseStatement(); + return finishNode(node, "WithStatement"); + + case _braceL: + return parseBlock(); + + case _semi: + next(); + return finishNode(node, "EmptyStatement"); + + // If the statement does not start with a statement keyword or a + // brace, it's an ExpressionStatement or LabeledStatement. We + // simply start parsing an expression, and afterwards, if the + // next token is a colon and the expression was a simple + // Identifier node, we switch to interpreting it as a label. + + default: + var maybeName = tokVal, expr = parseExpression(); + if (starttype === _name && expr.type === "Identifier" && eat(_colon)) { + for (var i = 0; i < labels.length; ++i) + if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared"); + var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null; + labels.push({name: maybeName, kind: kind}); + node.body = parseStatement(); + node.label = expr; + return finishNode(node, "LabeledStatement"); + } else { + node.expression = expr; + semicolon(); + return finishNode(node, "ExpressionStatement"); + } + } + } + + // Used for constructs like `switch` and `if` that insist on + // parentheses around their expression. + + function parseParenExpression() { + expect(_parenL); + var val = parseExpression(); + expect(_parenR); + return val; + } + + // Parse a semicolon-enclosed block of statements, handling `"use + // strict"` declarations when `allowStrict` is true (used for + // function bodies). + + function parseBlock(allowStrict) { + var node = startNode(), first = true, strict = false, oldStrict; + node.body = []; + expect(_braceL); + while (!eat(_braceR)) { + var stmt = parseStatement(); + node.body.push(stmt); + if (first && isUseStrict(stmt)) { + oldStrict = strict; + setStrict(strict = true); + } + first = false + } + if (strict && !oldStrict) setStrict(false); + return finishNode(node, "BlockStatement"); + } + + // Parse a regular `for` loop. The disambiguation code in + // `parseStatement` will already have parsed the init statement or + // expression. + + function parseFor(node, init) { + node.init = init; + expect(_semi); + node.test = tokType === _semi ? null : parseExpression(); + expect(_semi); + node.update = tokType === _parenR ? null : parseExpression(); + expect(_parenR); + node.body = parseStatement(); + labels.pop(); + return finishNode(node, "ForStatement"); + } + + // Parse a `for`/`in` loop. + + function parseForIn(node, init) { + node.left = init; + node.right = parseExpression(); + expect(_parenR); + node.body = parseStatement(); + labels.pop(); + return finishNode(node, "ForInStatement"); + } + + // Parse a list of variable declarations. + + function parseVar(node, noIn) { + node.declarations = []; + node.kind = "var"; + for (;;) { + var decl = startNode(); + decl.id = parseIdent(); + if (strict && isStrictBadIdWord(decl.id.name)) + raise(decl.id.start, "Binding " + decl.id.name + " in strict mode"); + decl.init = eat(_eq) ? parseExpression(true, noIn) : null; + node.declarations.push(finishNode(decl, "VariableDeclarator")); + if (!eat(_comma)) break; + } + return finishNode(node, "VariableDeclaration"); + } + + // ### Expression parsing + + // These nest, from the most general expression type at the top to + // 'atomic', nondivisible expression types at the bottom. Most of + // the functions will simply let the function(s) below them parse, + // and, *if* the syntactic construct they handle is present, wrap + // the AST node that the inner parser gave them in another node. + + // Parse a full expression. The arguments are used to forbid comma + // sequences (in argument lists, array literals, or object literals) + // or the `in` operator (in for loops initalization expressions). + + function parseExpression(noComma, noIn) { + var expr = parseMaybeAssign(noIn); + if (!noComma && tokType === _comma) { + var node = startNodeFrom(expr); + node.expressions = [expr]; + while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn)); + return finishNode(node, "SequenceExpression"); + } + return expr; + } + + // Parse an assignment expression. This includes applications of + // operators like `+=`. + + function parseMaybeAssign(noIn) { + var left = parseMaybeConditional(noIn); + if (tokType.isAssign) { + var node = startNodeFrom(left); + node.operator = tokVal; + node.left = left; + next(); + node.right = parseMaybeAssign(noIn); + checkLVal(left); + return finishNode(node, "AssignmentExpression"); + } + return left; + } + + // Parse a ternary conditional (`?:`) operator. + + function parseMaybeConditional(noIn) { + var expr = parseExprOps(noIn); + if (eat(_question)) { + var node = startNodeFrom(expr); + node.test = expr; + node.consequent = parseExpression(true); + expect(_colon); + node.alternate = parseExpression(true, noIn); + return finishNode(node, "ConditionalExpression"); + } + return expr; + } + + // Start the precedence parser. + + function parseExprOps(noIn) { + return parseExprOp(parseMaybeUnary(noIn), -1, noIn); + } + + // Parse binary operators with the operator precedence parsing + // algorithm. `left` is the left-hand side of the operator. + // `minPrec` provides context that allows the function to stop and + // defer further parser to one of its callers when it encounters an + // operator that has a lower precedence than the set it is parsing. + + function parseExprOp(left, minPrec, noIn) { + var prec = tokType.binop; + if (prec != null && (!noIn || tokType !== _in)) { + if (prec > minPrec) { + var node = startNodeFrom(left); + node.left = left; + node.operator = tokVal; + next(); + node.right = parseExprOp(parseMaybeUnary(noIn), prec, noIn); + var node = finishNode(node, /&&|\|\|/.test(node.operator) ? "LogicalExpression" : "BinaryExpression"); + return parseExprOp(node, minPrec, noIn); + } + } + return left; + } + + // Parse unary operators, both prefix and postfix. + + function parseMaybeUnary(noIn) { + if (tokType.prefix) { + var node = startNode(), update = tokType.isUpdate; + node.operator = tokVal; + node.prefix = true; + next(); + node.argument = parseMaybeUnary(noIn); + if (update) checkLVal(node.argument); + else if (strict && node.operator === "delete" && + node.argument.type === "Identifier") + raise(node.start, "Deleting local variable in strict mode"); + return finishNode(node, update ? "UpdateExpression" : "UnaryExpression"); + } + var expr = parseExprSubscripts(); + while (tokType.postfix && !canInsertSemicolon()) { + var node = startNodeFrom(expr); + node.operator = tokVal; + node.prefix = false; + node.argument = expr; + checkLVal(expr); + next(); + expr = finishNode(node, "UpdateExpression"); + } + return expr; + } + + // Parse call, dot, and `[]`-subscript expressions. + + function parseExprSubscripts() { + return parseSubscripts(parseExprAtom()); + } + + function parseSubscripts(base, noCalls) { + if (eat(_dot)) { + var node = startNodeFrom(base); + node.object = base; + node.property = parseIdent(true); + node.computed = false; + return parseSubscripts(finishNode(node, "MemberExpression"), noCalls); + } else if (eat(_bracketL)) { + var node = startNodeFrom(base); + node.object = base; + node.property = parseExpression(); + node.computed = true; + expect(_bracketR); + return parseSubscripts(finishNode(node, "MemberExpression"), noCalls); + } else if (!noCalls && eat(_parenL)) { + var node = startNodeFrom(base); + node.callee = base; + node.arguments = parseExprList(_parenR, false); + return parseSubscripts(finishNode(node, "CallExpression"), noCalls); + } else return base; + } + + // Parse an atomic expression — either a single token that is an + // expression, an expression started by a keyword like `function` or + // `new`, or an expression wrapped in punctuation like `()`, `[]`, + // or `{}`. + + function parseExprAtom() { + switch (tokType) { + case _this: + var node = startNode(); + next(); + return finishNode(node, "ThisExpression"); + case _name: + return parseIdent(); + case _num: case _string: case _regexp: + var node = startNode(); + node.value = tokVal; + node.raw = input.slice(tokStart, tokEnd); + next(); + return finishNode(node, "Literal"); + + case _null: case _true: case _false: + var node = startNode(); + node.value = tokType.atomValue; + next(); + return finishNode(node, "Literal"); + + case _parenL: + next(); + var val = parseExpression(); + expect(_parenR); + return val; + + case _bracketL: + var node = startNode(); + next(); + node.elements = parseExprList(_bracketR, true, true); + return finishNode(node, "ArrayExpression"); + + case _braceL: + return parseObj(); + + case _function: + var node = startNode(); + next(); + return parseFunction(node, false); + + case _new: + return parseNew(); + + default: + unexpected(); + } + } + + // New's precedence is slightly tricky. It must allow its argument + // to be a `[]` or dot subscript expression, but not a call — at + // least, not without wrapping it in parentheses. Thus, it uses the + + function parseNew() { + var node = startNode(); + next(); + node.callee = parseSubscripts(parseExprAtom(false), true); + if (eat(_parenL)) node.arguments = parseExprList(_parenR, false); + else node.arguments = []; + return finishNode(node, "NewExpression"); + } + + // Parse an object literal. + + function parseObj() { + var node = startNode(), first = true, sawGetSet = false; + node.properties = []; + next(); + while (!eat(_braceR)) { + if (!first) { + expect(_comma); + if (options.allowTrailingCommas && eat(_braceR)) break; + } else first = false; + + var prop = {key: parsePropertyName()}, isGetSet = false, kind; + if (eat(_colon)) { + prop.value = parseExpression(true); + kind = prop.kind = "init"; + } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" && + (prop.key.name === "get" || prop.key.name === "set")) { + isGetSet = sawGetSet = true; + kind = prop.kind = prop.key.name; + prop.key = parsePropertyName(); + if (!tokType === _parenL) unexpected(); + prop.value = parseFunction(startNode(), false); + } else unexpected(); + + // getters and setters are not allowed to clash — either with + // each other or with an init property — and in strict mode, + // init properties are also not allowed to be repeated. + + if (prop.key.type === "Identifier" && (strict || sawGetSet)) { + for (var i = 0; i < node.properties.length; ++i) { + var other = node.properties[i]; + if (other.key.name === prop.key.name) { + var conflict = kind == other.kind || isGetSet && other.kind === "init" || + kind === "init" && (other.kind === "get" || other.kind === "set"); + if (conflict && !strict && kind === "init" && other.kind === "init") conflict = false; + if (conflict) raise(prop.key.start, "Redefinition of property"); + } + } + } + node.properties.push(prop); + } + return finishNode(node, "ObjectExpression"); + } + + function parsePropertyName() { + if (tokType === _num || tokType === _string) return parseExprAtom(); + return parseIdent(true); + } + + // Parse a function declaration or literal (depending on the + // `isStatement` parameter). + + function parseFunction(node, isStatement) { + if (tokType === _name) node.id = parseIdent(); + else if (isStatement) unexpected(); + else node.id = null; + node.params = []; + var first = true; + expect(_parenL); + while (!eat(_parenR)) { + if (!first) expect(_comma); else first = false; + node.params.push(parseIdent()); + } + + // Start a new scope with regard to labels and the `inFunction` + // flag (restore them to their old value afterwards). + var oldInFunc = inFunction, oldLabels = labels; + inFunction = true; labels = []; + node.body = parseBlock(true); + inFunction = oldInFunc; labels = oldLabels; + + // If this is a strict mode function, verify that argument names + // are not repeated, and it does not try to bind the words `eval` + // or `arguments`. + if (strict || node.body.body.length && isUseStrict(node.body.body[0])) { + for (var i = node.id ? -1 : 0; i < node.params.length; ++i) { + var id = i < 0 ? node.id : node.params[i]; + if (isStrictReservedWord(id.name) || isStrictBadIdWord(id.name)) + raise(id.start, "Defining '" + id.name + "' in strict mode"); + if (i >= 0) for (var j = 0; j < i; ++j) if (id.name === node.params[j].name) + raise(id.start, "Argument name clash in strict mode"); + } + } + + return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression"); + } + + // Parses a comma-separated list of expressions, and returns them as + // an array. `close` is the token type that ends the list, and + // `allowEmpty` can be turned on to allow subsequent commas with + // nothing in between them to be parsed as `null` (which is needed + // for array literals). + + function parseExprList(close, allowTrailingComma, allowEmpty) { + var elts = [], first = true; + while (!eat(close)) { + if (!first) { + expect(_comma); + if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break; + } else first = false; + + if (allowEmpty && tokType === _comma) elts.push(null); + else elts.push(parseExpression(true)); + } + return elts; + } + + // Parse the next token as an identifier. If `liberal` is true (used + // when parsing properties), it will also convert keywords into + // identifiers. + + function parseIdent(liberal) { + var node = startNode(); + node.name = tokType === _name ? tokVal : (liberal && !options.forbidReserved && tokType.keyword) || unexpected(); + next(); + return finishNode(node, "Identifier"); + } + +})(typeof exports === "undefined" ? (window.acorn = {}) : exports); diff --git a/lib/codemirror-3.1/test/lint/lint.js b/lib/codemirror-3.1/test/lint/lint.js new file mode 100644 index 0000000000000000000000000000000000000000..b1b9381dd20444a6becd3141ac0c5ba5bebfdc8f --- /dev/null +++ b/lib/codemirror-3.1/test/lint/lint.js @@ -0,0 +1,108 @@ +/* + Simple linter, based on the Acorn [1] parser module + + All of the existing linters either cramp my style or have huge + dependencies (Closure). So here's a very simple, non-invasive one + that only spots + + - missing semicolons and trailing commas + - variables or properties that are reserved words + - assigning to a variable you didn't declare + + [1]: https://github.com/marijnh/acorn/ +*/ + +var fs = require("fs"), acorn = require("./acorn.js"), walk = require("./walk.js"); + +var scopePasser = walk.make({ + ScopeBody: function(node, prev, c) { c(node, node.scope); } +}); + +function checkFile(fileName) { + var file = fs.readFileSync(fileName, "utf8"); + var badChar = file.match(/[\x00-\x08\x0b\x0c\x0e-\x19\uFEFF]/); + if (badChar) + fail("Undesirable character " + badChar[0].charCodeAt(0) + " at position " + badChar.index, + {source: fileName}); + + try { + var parsed = acorn.parse(file, { + locations: true, + ecmaVersion: 3, + strictSemicolons: true, + allowTrailingCommas: false, + forbidReserved: true, + sourceFile: fileName + }); + } catch (e) { + fail(e.message, {source: fileName}); + return; + } + + var scopes = []; + + walk.simple(parsed, { + ScopeBody: function(node, scope) { + node.scope = scope; + scopes.push(scope); + } + }, walk.scopeVisitor, {vars: Object.create(null)}); + + var ignoredGlobals = Object.create(null); + + function inScope(name, scope) { + for (var cur = scope; cur; cur = cur.prev) + if (name in cur.vars) return true; + } + function checkLHS(node, scope) { + if (node.type == "Identifier" && !(node.name in ignoredGlobals) && + !inScope(node.name, scope)) { + ignoredGlobals[node.name] = true; + fail("Assignment to global variable", node.loc); + } + } + + walk.simple(parsed, { + UpdateExpression: function(node, scope) {checkLHS(node.argument, scope);}, + AssignmentExpression: function(node, scope) {checkLHS(node.left, scope);}, + Identifier: function(node, scope) { + // Mark used identifiers + for (var cur = scope; cur; cur = cur.prev) + if (node.name in cur.vars) { + cur.vars[node.name].used = true; + return; + } + }, + FunctionExpression: function(node) { + if (node.id) fail("Named function expression", node.loc); + } + }, scopePasser); + + for (var i = 0; i < scopes.length; ++i) { + var scope = scopes[i]; + for (var name in scope.vars) { + var info = scope.vars[name]; + if (!info.used && info.type != "catch clause" && info.type != "function name" && name.charAt(0) != "_") + fail("Unused " + info.type + " " + name, info.node.loc); + } + } +} + +var failed = false; +function fail(msg, pos) { + if (pos.start) msg += " (" + pos.start.line + ":" + pos.start.column + ")"; + console.log(pos.source.match(/[^\/]+$/)[0] + ": " + msg); + failed = true; +} + +function checkDir(dir) { + fs.readdirSync(dir).forEach(function(file) { + var fname = dir + "/" + file; + if (/\.js$/.test(file)) checkFile(fname); + else if (fs.lstatSync(fname).isDirectory()) checkDir(fname); + }); +} + +exports.checkDir = checkDir; +exports.checkFile = checkFile; +exports.success = function() { return !failed; }; diff --git a/lib/codemirror-3.1/test/lint/parse-js.js b/lib/codemirror-3.1/test/lint/parse-js.js new file mode 100644 index 0000000000000000000000000000000000000000..c165a273f3ee61cfb83c38cb71a987c2b0a36cdc --- /dev/null +++ b/lib/codemirror-3.1/test/lint/parse-js.js @@ -0,0 +1,1372 @@ +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + + This version is suitable for Node.js. With minimal changes (the + exports stuff) it should work on any JS platform. + + This file contains the tokenizer/parser. It is a port to JavaScript + of parse-js [1], a JavaScript parser library written in Common Lisp + by Marijn Haverbeke. Thank you Marijn! + + [1] http://marijn.haverbeke.nl/parse-js/ + + Exported functions: + + - tokenizer(code) -- returns a function. Call the returned + function to fetch the next token. + + - parse(code) -- returns an AST of the given JavaScript code. + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2010 (c) Mihai Bazon + Based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + * Redistributions of source code must retain the above + copyright notice, this list of conditions and the following + disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials + provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY + EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + SUCH DAMAGE. + + ***********************************************************************/ + +/* -----[ Tokenizer (constants) ]----- */ + +var KEYWORDS = array_to_hash([ + "break", + "case", + "catch", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "finally", + "for", + "function", + "if", + "in", + "instanceof", + "new", + "return", + "switch", + "throw", + "try", + "typeof", + "var", + "void", + "while", + "with" +]); + +var RESERVED_WORDS = array_to_hash([ + "abstract", + "boolean", + "byte", + "char", + "class", + "double", + "enum", + "export", + "extends", + "final", + "float", + "goto", + "implements", + "import", + "int", + "interface", + "long", + "native", + "package", + "private", + "protected", + "public", + "short", + "static", + "super", + "synchronized", + "throws", + "transient", + "volatile" +]); + +var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([ + "return", + "new", + "delete", + "throw", + "else", + "case" +]); + +var KEYWORDS_ATOM = array_to_hash([ + "false", + "null", + "true", + "undefined" +]); + +var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^")); + +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; +var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; + +var OPERATORS = array_to_hash([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "/=", + "*=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "||" +]); + +var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000")); + +var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:")); + +var PUNC_CHARS = array_to_hash(characters("[]{}(),;:")); + +var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy")); + +/* -----[ Tokenizer ]----- */ + +var UNICODE = { // Unicode 6.1 + letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\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\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\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\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\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-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\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\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\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-\\u209C\\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\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\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-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\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\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\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]"), + combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), + connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"), + digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]") +}; + +function is_letter(ch) { + return UNICODE.letter.test(ch); +}; + +function is_digit(ch) { + ch = ch.charCodeAt(0); + return ch >= 48 && ch <= 57; +}; + +function is_unicode_digit(ch) { + return UNICODE.digit.test(ch); +} + +function is_alphanumeric_char(ch) { + return is_digit(ch) || is_letter(ch); +}; + +function is_unicode_combining_mark(ch) { + return UNICODE.combining_mark.test(ch); +}; + +function is_unicode_connector_punctuation(ch) { + return UNICODE.connector_punctuation.test(ch); +}; + +function is_identifier_start(ch) { + return ch == "$" || ch == "_" || is_letter(ch); +}; + +function is_identifier_char(ch) { + return is_identifier_start(ch) + || is_unicode_combining_mark(ch) + || is_unicode_digit(ch) + || is_unicode_connector_punctuation(ch) + || ch == "\u200c" // zero-width non-joiner + || ch == "\u200d" // zero-width joiner (in my ECMA-262 PDF, this is also 200c) + ; +}; + +function parse_js_number(num) { + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else if (RE_DEC_NUMBER.test(num)) { + return parseFloat(num); + } +}; + +function JS_Parse_Error(message, line, col, pos) { + this.message = message; + this.line = line + 1; + this.col = col + 1; + this.pos = pos + 1; + this.stack = new Error().stack; +}; + +JS_Parse_Error.prototype.toString = function() { + return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack; +}; + +function js_error(message, line, col, pos) { + throw new JS_Parse_Error(message, line, col, pos); +}; + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +}; + +var EX_EOF = {}; + +function tokenizer($TEXT) { + + var S = { + text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''), + pos : 0, + tokpos : 0, + line : 0, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + comments_before : [] + }; + + function peek() { return S.text.charAt(S.pos); }; + + function next(signal_eof, in_string) { + var ch = S.text.charAt(S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (ch == "\n") { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + } else { + ++S.col; + } + return ch; + }; + + function eof() { + return !S.peek(); + }; + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + }; + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + }; + + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) || + (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) || + (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value))); + var ret = { + type : type, + value : value, + line : S.tokline, + col : S.tokcol, + pos : S.tokpos, + endpos : S.pos, + nlb : S.newline_before + }; + if (!is_comment) { + ret.comments_before = S.comments_before; + S.comments_before = []; + // make note of any newlines in the comments that came before + for (var i = 0, len = ret.comments_before.length; i < len; i++) { + ret.nlb = ret.nlb || ret.comments_before[i].nlb; + } + } + S.newline_before = false; + return ret; + }; + + function skip_whitespace() { + while (HOP(WHITESPACE_CHARS, peek())) + next(); + }; + + function read_while(pred) { + var ret = "", ch = peek(), i = 0; + while (ch && pred(ch, i++)) { + ret += next(); + ch = peek(); + } + return ret; + }; + + function parse_error(err) { + js_error(err, S.tokline, S.tokcol, S.tokpos); + }; + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; + var num = read_while(function(ch, i){ + if (ch == "x" || ch == "X") { + if (has_x) return false; + return has_x = true; + } + if (!has_x && (ch == "E" || ch == "e")) { + if (has_e) return false; + return has_e = after_e = true; + } + if (ch == "-") { + if (after_e || (i == 0 && !prefix)) return true; + return false; + } + if (ch == "+") return after_e; + after_e = false; + if (ch == ".") { + if (!has_dot && !has_x && !has_e) + return has_dot = true; + return false; + } + return is_alphanumeric_char(ch); + }); + if (prefix) + num = prefix + num; + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + }; + + function read_escaped_char(in_string) { + var ch = next(true, in_string); + switch (ch) { + case "n" : return "\n"; + case "r" : return "\r"; + case "t" : return "\t"; + case "b" : return "\b"; + case "v" : return "\u000b"; + case "f" : return "\f"; + case "0" : return "\0"; + case "x" : return String.fromCharCode(hex_bytes(2)); + case "u" : return String.fromCharCode(hex_bytes(4)); + case "\n": return ""; + default : return ch; + } + }; + + function hex_bytes(n) { + var num = 0; + for (; n > 0; --n) { + var digit = parseInt(next(true), 16); + if (isNaN(digit)) + parse_error("Invalid hex-character pattern in string"); + num = (num << 4) | digit; + } + return num; + }; + + function read_string() { + return with_eof_error("Unterminated string constant", function(){ + var quote = next(), ret = ""; + for (;;) { + var ch = next(true); + if (ch == "\\") { + // read OctalEscapeSequence (XXX: deprecated if "strict mode") + // https://github.com/mishoo/UglifyJS/issues/178 + var octal_len = 0, first = null; + ch = read_while(function(ch){ + if (ch >= "0" && ch <= "7") { + if (!first) { + first = ch; + return ++octal_len; + } + else if (first <= "3" && octal_len <= 2) return ++octal_len; + else if (first >= "4" && octal_len <= 1) return ++octal_len; + } + return false; + }); + if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8)); + else ch = read_escaped_char(true); + } + else if (ch == quote) break; + ret += ch; + } + return token("string", ret); + }); + }; + + function read_line_comment() { + next(); + var i = find("\n"), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + return token("comment1", ret, true); + }; + + function read_multiline_comment() { + next(); + return with_eof_error("Unterminated multiline comment", function(){ + var i = find("*/", true), + text = S.text.substring(S.pos, i); + S.pos = i + 2; + S.line += text.split("\n").length - 1; + S.newline_before = S.newline_before || text.indexOf("\n") >= 0; + + // https://github.com/mishoo/UglifyJS/issues/#issue/100 + if (/^@cc_on/i.test(text)) { + warn("WARNING: at line " + S.line); + warn("*** Found \"conditional comment\": " + text); + warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer."); + } + + return token("comment2", text, true); + }); + }; + + function read_name() { + var backslash = false, name = "", ch, escaped = false, hex; + while ((ch = peek()) != null) { + if (!backslash) { + if (ch == "\\") escaped = backslash = true, next(); + else if (is_identifier_char(ch)) name += next(); + else break; + } + else { + if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); + ch = read_escaped_char(); + if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); + name += ch; + backslash = false; + } + } + if (HOP(KEYWORDS, name) && escaped) { + hex = name.charCodeAt(0).toString(16).toUpperCase(); + name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); + } + return name; + }; + + function read_regexp(regexp) { + return with_eof_error("Unterminated regular expression", function(){ + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (prev_backslash) { + regexp += "\\" + ch; + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + regexp += ch; + } else if (ch == "]" && in_class) { + in_class = false; + regexp += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + regexp += ch; + } + var mods = read_name(); + return token("regexp", [ regexp, mods ]); + }); + }; + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (HOP(OPERATORS, bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + }; + return token("operator", grow(prefix || next())); + }; + + function handle_slash() { + next(); + var regex_allowed = S.regex_allowed; + switch (peek()) { + case "/": + S.comments_before.push(read_line_comment()); + S.regex_allowed = regex_allowed; + return next_token(); + case "*": + S.comments_before.push(read_multiline_comment()); + S.regex_allowed = regex_allowed; + return next_token(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + }; + + function handle_dot() { + next(); + return is_digit(peek()) + ? read_num(".") + : token("punc", "."); + }; + + function read_word() { + var word = read_name(); + return !HOP(KEYWORDS, word) + ? token("name", word) + : HOP(OPERATORS, word) + ? token("operator", word) + : HOP(KEYWORDS_ATOM, word) + ? token("atom", word) + : token("keyword", word); + }; + + function with_eof_error(eof_error, cont) { + try { + return cont(); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + skip_whitespace(); + start_token(); + var ch = peek(); + if (!ch) return token("eof"); + if (is_digit(ch)) return read_num(); + if (ch == '"' || ch == "'") return read_string(); + if (HOP(PUNC_CHARS, ch)) return token("punc", next()); + if (ch == ".") return handle_dot(); + if (ch == "/") return handle_slash(); + if (HOP(OPERATOR_CHARS, ch)) return read_operator(); + if (ch == "\\" || is_identifier_start(ch)) return read_word(); + parse_error("Unexpected character '" + ch + "'"); + }; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + return next_token; + +}; + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = array_to_hash([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = array_to_hash([ "--", "++" ]); + +var ASSIGNMENT = (function(a, ret, i){ + while (i < a.length) { + ret[a[i]] = a[i].substr(0, a[i].length - 1); + i++; + } + return ret; +})( + ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="], + { "=": true }, + 0 +); + +var PRECEDENCE = (function(a, ret){ + for (var i = 0, n = 1; i < a.length; ++i, ++n) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = n; + } + } + return ret; +})( + [ + ["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"] + ], + {} +); + +var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); + +var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function NodeWithToken(str, start, end) { + this.name = str; + this.start = start; + this.end = end; +}; + +NodeWithToken.prototype.toString = function() { return this.name; }; + +function parse($TEXT, exigent_mode, embed_tokens) { + + var S = { + input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT, + token : null, + prev : null, + peeked : null, + in_function : 0, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + }; + + function peek() { return S.peeked || (S.peeked = S.input()); }; + + function next() { + S.prev = S.token; + if (S.peeked) { + S.token = S.peeked; + S.peeked = null; + } else { + S.token = S.input(); + } + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + }; + + function prev() { + return S.prev; + }; + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + }; + + function token_error(token, msg) { + croak(msg, token.line, token.col); + }; + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + }; + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type); + }; + + function expect(punc) { return expect_token("punc", punc); }; + + function can_insert_semicolon() { + return !exigent_mode && ( + S.token.nlb || is("eof") || is("punc", "}") + ); + }; + + function semicolon() { + if (is("punc", ";")) next(); + else if (!can_insert_semicolon()) unexpected(); + }; + + function as() { + return slice(arguments); + }; + + function parenthesised() { + expect("("); + var ex = expression(); + expect(")"); + return ex; + }; + + function add_tokens(str, start, end) { + return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end); + }; + + function maybe_embed_tokens(parser) { + if (embed_tokens) return function() { + var start = S.token; + var ast = parser.apply(this, arguments); + ast[0] = add_tokens(ast[0], start, prev()); + return ast; + }; + else return parser; + }; + + var statement = maybe_embed_tokens(function() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + switch (S.token.type) { + case "string": + var dir = S.in_directives, stat = simple_statement(); + if (dir && stat[1][0] == "string" && !is("punc", ",")) + return as("directive", stat[1][1]); + return stat; + case "num": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + return is_token(peek(), "punc", ":") + ? labeled_statement(prog1(S.token.value, next, next)) + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return as("block", block_()); + case "[": + case "(": + return simple_statement(); + case ";": + next(); + return as("block"); + default: + unexpected(); + } + + case "keyword": + switch (prog1(S.token.value, next)) { + case "break": + return break_cont("break"); + + case "continue": + return break_cont("continue"); + + case "debugger": + semicolon(); + return as("debugger"); + + case "do": + return (function(body){ + expect_token("keyword", "while"); + return as("do", prog1(parenthesised, semicolon), body); + })(in_loop(statement)); + + case "for": + return for_(); + + case "function": + return function_(true); + + case "if": + return if_(); + + case "return": + if (S.in_function == 0) + croak("'return' outside of function"); + return as("return", + is("punc", ";") + ? (next(), null) + : can_insert_semicolon() + ? null + : prog1(expression, semicolon)); + + case "switch": + return as("switch", parenthesised(), switch_block_()); + + case "throw": + if (S.token.nlb) + croak("Illegal newline after 'throw'"); + return as("throw", prog1(expression, semicolon)); + + case "try": + return try_(); + + case "var": + return prog1(var_, semicolon); + + case "const": + return prog1(const_, semicolon); + + case "while": + return as("while", parenthesised(), in_loop(statement)); + + case "with": + return as("with", parenthesised(), statement()); + + default: + unexpected(); + } + } + }); + + function labeled_statement(label) { + S.labels.push(label); + var start = S.token, stat = statement(); + if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0])) + unexpected(start); + S.labels.pop(); + return as("label", label, stat); + }; + + function simple_statement() { + return as("stat", prog1(expression, semicolon)); + }; + + function break_cont(type) { + var name; + if (!can_insert_semicolon()) { + name = is("name") ? S.token.value : null; + } + if (name != null) { + next(); + if (!member(name, S.labels)) + croak("Label " + name + " without matching loop or statement"); + } + else if (S.in_loop == 0) + croak(type + " not inside a loop or switch"); + semicolon(); + return as(type, name); + }; + + function for_() { + expect("("); + var init = null; + if (!is("punc", ";")) { + init = is("keyword", "var") + ? (next(), var_(true)) + : expression(true, true); + if (is("operator", "in")) { + if (init[0] == "var" && init[1].length > 1) + croak("Only one variable declaration allowed in for..in loop"); + return for_in(init); + } + } + return regular_for(init); + }; + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(); + expect(";"); + var step = is("punc", ")") ? null : expression(); + expect(")"); + return as("for", init, test, step, in_loop(statement)); + }; + + function for_in(init) { + var lhs = init[0] == "var" ? as("name", init[1][0]) : init; + next(); + var obj = expression(); + expect(")"); + return as("for-in", init, lhs, obj, in_loop(statement)); + }; + + var function_ = function(in_statement) { + var name = is("name") ? prog1(S.token.value, next) : null; + if (in_statement && !name) + unexpected(); + expect("("); + return as(in_statement ? "defun" : "function", + name, + // arguments + (function(first, a){ + while (!is("punc", ")")) { + if (first) first = false; else expect(","); + if (!is("name")) unexpected(); + a.push(S.token.value); + next(); + } + next(); + return a; + })(true, []), + // body + (function(){ + ++S.in_function; + var loop = S.in_loop; + S.in_directives = true; + S.in_loop = 0; + var a = block_(); + --S.in_function; + S.in_loop = loop; + return a; + })()); + }; + + function if_() { + var cond = parenthesised(), body = statement(), belse; + if (is("keyword", "else")) { + next(); + belse = statement(); + } + return as("if", cond, body, belse); + }; + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + }; + + var switch_block_ = curry(in_loop, function(){ + expect("{"); + var a = [], cur = null; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + next(); + cur = []; + a.push([ expression(), cur ]); + expect(":"); + } + else if (is("keyword", "default")) { + next(); + expect(":"); + cur = []; + a.push([ null, cur ]); + } + else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + next(); + return a; + }); + + function try_() { + var body = block_(), bcatch, bfinally; + if (is("keyword", "catch")) { + next(); + expect("("); + if (!is("name")) + croak("Name expected"); + var name = S.token.value; + next(); + expect(")"); + bcatch = [ name, block_() ]; + } + if (is("keyword", "finally")) { + next(); + bfinally = block_(); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return as("try", body, bcatch, bfinally); + }; + + function vardefs(no_in) { + var a = []; + for (;;) { + if (!is("name")) + unexpected(); + var name = S.token.value; + next(); + if (is("operator", "=")) { + next(); + a.push([ name, expression(false, no_in) ]); + } else { + a.push([ name ]); + } + if (!is("punc", ",")) + break; + next(); + } + return a; + }; + + function var_(no_in) { + return as("var", vardefs(no_in)); + }; + + function const_() { + return as("const", vardefs()); + }; + + function new_() { + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")"); + } else { + args = []; + } + return subscripts(as("new", newexp, args), true); + }; + + var expr_atom = maybe_embed_tokens(function(allow_calls) { + if (is("operator", "new")) { + next(); + return new_(); + } + if (is("punc")) { + switch (S.token.value) { + case "(": + next(); + return subscripts(prog1(expression, curry(expect, ")")), allow_calls); + case "[": + next(); + return subscripts(array_(), allow_calls); + case "{": + next(); + return subscripts(object_(), allow_calls); + } + unexpected(); + } + if (is("keyword", "function")) { + next(); + return subscripts(function_(false), allow_calls); + } + if (HOP(ATOMIC_START_TOKEN, S.token.type)) { + var atom = S.token.type == "regexp" + ? as("regexp", S.token.value[0], S.token.value[1]) + : as(S.token.type, S.token.value); + return subscripts(prog1(atom, next), allow_calls); + } + unexpected(); + }); + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push([ "atom", "undefined" ]); + } else { + a.push(expression(false)); + } + } + next(); + return a; + }; + + function array_() { + return as("array", expr_list("]", !exigent_mode, true)); + }; + + function object_() { + var first = true, a = []; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!exigent_mode && is("punc", "}")) + // allow trailing comma + break; + var type = S.token.type; + var name = as_property_name(); + if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) { + a.push([ as_name(), function_(false), name ]); + } else { + expect(":"); + a.push([ name, expression(false) ]); + } + // FIXME [!!] Line not in original parse-js, + // added to be able to warn about unquoted + // keyword properties + a[a.length - 1].type = type; + } + next(); + return as("object", a); + }; + + function as_property_name() { + switch (S.token.type) { + case "num": + case "string": + return prog1(S.token.value, next); + } + return as_name(); + }; + + function as_name() { + switch (S.token.type) { + case "name": + case "operator": + case "keyword": + case "atom": + return prog1(S.token.value, next); + default: + unexpected(); + } + }; + + function subscripts(expr, allow_calls) { + if (is("punc", ".")) { + next(); + return subscripts(as("dot", expr, as_name()), allow_calls); + } + if (is("punc", "[")) { + next(); + return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls); + } + if (allow_calls && is("punc", "(")) { + next(); + return subscripts(as("call", expr, expr_list(")")), true); + } + return expr; + }; + + function maybe_unary(allow_calls) { + if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) { + return make_unary("unary-prefix", + prog1(S.token.value, next), + maybe_unary(allow_calls)); + } + var val = expr_atom(allow_calls); + while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) { + val = make_unary("unary-postfix", S.token.value, val); + next(); + } + return val; + }; + + function make_unary(tag, op, expr) { + if ((op == "++" || op == "--") && !is_assignable(expr)) + croak("Invalid use of " + op + " operator"); + return as(tag, op, expr); + }; + + function expr_op(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op && op == "in" && no_in) op = null; + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && prec > min_prec) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(as("binary", op, left, right), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true), 0, no_in); + }; + + function maybe_conditional(no_in) { + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return as("conditional", expr, yes, expression(false, no_in)); + } + return expr; + }; + + function is_assignable(expr) { + if (!exigent_mode) return true; + switch (expr[0]+"") { + case "dot": + case "sub": + case "new": + case "call": + return true; + case "name": + return expr[1] != "this"; + } + }; + + function maybe_assign(no_in) { + var left = maybe_conditional(no_in), val = S.token.value; + if (is("operator") && HOP(ASSIGNMENT, val)) { + if (is_assignable(left)) { + next(); + return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in)); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = maybe_embed_tokens(function(commas, no_in) { + if (arguments.length == 0) + commas = true; + var expr = maybe_assign(no_in); + if (commas && is("punc", ",")) { + next(); + return as("seq", expr, expression(true, no_in)); + } + return expr; + }); + + function in_loop(cont) { + try { + ++S.in_loop; + return cont(); + } finally { + --S.in_loop; + } + }; + + return as("toplevel", (function(a){ + while (!is("eof")) + a.push(statement()); + return a; + })([])); + +}; + +/* -----[ Utilities ]----- */ + +function curry(f) { + var args = slice(arguments, 1); + return function() { return f.apply(this, args.concat(slice(arguments))); }; +}; + +function prog1(ret) { + if (ret instanceof Function) + ret = ret(); + for (var i = 1, n = arguments.length; --n > 0; ++i) + arguments[i](); + return ret; +}; + +function array_to_hash(a) { + var ret = {}; + for (var i = 0; i < a.length; ++i) + ret[a[i]] = true; + return ret; +}; + +function slice(a, start) { + return Array.prototype.slice.call(a, start || 0); +}; + +function characters(str) { + return str.split(""); +}; + +function member(name, array) { + for (var i = array.length; --i >= 0;) + if (array[i] == name) + return true; + return false; +}; + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +}; + +var warn = function() {}; + +/* -----[ Exports ]----- */ + +exports.tokenizer = tokenizer; +exports.parse = parse; +exports.slice = slice; +exports.curry = curry; +exports.member = member; +exports.array_to_hash = array_to_hash; +exports.PRECEDENCE = PRECEDENCE; +exports.KEYWORDS_ATOM = KEYWORDS_ATOM; +exports.RESERVED_WORDS = RESERVED_WORDS; +exports.KEYWORDS = KEYWORDS; +exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN; +exports.OPERATORS = OPERATORS; +exports.is_alphanumeric_char = is_alphanumeric_char; +exports.is_identifier_start = is_identifier_start; +exports.is_identifier_char = is_identifier_char; +exports.set_logger = function(logger) { + warn = logger; +}; + +// Local variables: +// js-indent-level: 8 +// End: diff --git a/lib/codemirror-3.1/test/lint/walk.js b/lib/codemirror-3.1/test/lint/walk.js new file mode 100644 index 0000000000000000000000000000000000000000..97321acfc49bd3c7142e9ccdb45bbbafd5da4561 --- /dev/null +++ b/lib/codemirror-3.1/test/lint/walk.js @@ -0,0 +1,216 @@ +// AST walker module for Mozilla Parser API compatible trees + +(function(exports) { + "use strict"; + + // A simple walk is one where you simply specify callbacks to be + // called on specific nodes. The last two arguments are optional. A + // simple use would be + // + // walk.simple(myTree, { + // Expression: function(node) { ... } + // }); + // + // to do something with all expressions. All Parser API node types + // can be used to identify node types, as well as Expression, + // Statement, and ScopeBody, which denote categories of nodes. + // + // The base argument can be used to pass a custom (recursive) + // walker, and state can be used to give this walked an initial + // state. + exports.simple = function(node, visitors, base, state) { + if (!base) base = exports; + function c(node, st, override) { + var type = override || node.type, found = visitors[type]; + if (found) found(node, st); + base[type](node, st, c); + } + c(node, state); + }; + + // A recursive walk is one where your functions override the default + // walkers. They can modify and replace the state parameter that's + // threaded through the walk, and can opt how and whether to walk + // their child nodes (by calling their third argument on these + // nodes). + exports.recursive = function(node, state, funcs, base) { + var visitor = exports.make(funcs, base); + function c(node, st, override) { + visitor[override || node.type](node, st, c); + } + c(node, state); + }; + + // Used to create a custom walker. Will fill in all missing node + // type properties with the defaults. + exports.make = function(funcs, base) { + if (!base) base = exports; + var visitor = {}; + for (var type in base) + visitor[type] = funcs.hasOwnProperty(type) ? funcs[type] : base[type]; + return visitor; + }; + + function skipThrough(node, st, c) { c(node, st); } + function ignore(node, st, c) {} + + // Node walkers. + + exports.Program = exports.BlockStatement = function(node, st, c) { + for (var i = 0; i < node.body.length; ++i) + c(node.body[i], st, "Statement"); + }; + exports.Statement = skipThrough; + exports.EmptyStatement = ignore; + exports.ExpressionStatement = function(node, st, c) { + c(node.expression, st, "Expression"); + }; + exports.IfStatement = function(node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Statement"); + if (node.alternate) c(node.alternate, st, "Statement"); + }; + exports.LabeledStatement = function(node, st, c) { + c(node.body, st, "Statement"); + }; + exports.BreakStatement = exports.ContinueStatement = ignore; + exports.WithStatement = function(node, st, c) { + c(node.object, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.SwitchStatement = function(node, st, c) { + c(node.discriminant, st, "Expression"); + for (var i = 0; i < node.cases.length; ++i) { + var cs = node.cases[i]; + if (cs.test) c(cs.test, st, "Expression"); + for (var j = 0; j < cs.consequent.length; ++j) + c(cs.consequent[j], st, "Statement"); + } + }; + exports.ReturnStatement = function(node, st, c) { + if (node.argument) c(node.argument, st, "Expression"); + }; + exports.ThrowStatement = function(node, st, c) { + c(node.argument, st, "Expression"); + }; + exports.TryStatement = function(node, st, c) { + c(node.block, st, "Statement"); + for (var i = 0; i < node.handlers.length; ++i) + c(node.handlers[i].body, st, "ScopeBody"); + if (node.finalizer) c(node.finalizer, st, "Statement"); + }; + exports.WhileStatement = function(node, st, c) { + c(node.test, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.DoWhileStatement = exports.WhileStatement; + exports.ForStatement = function(node, st, c) { + if (node.init) c(node.init, st, "ForInit"); + if (node.test) c(node.test, st, "Expression"); + if (node.update) c(node.update, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.ForInStatement = function(node, st, c) { + c(node.left, st, "ForInit"); + c(node.right, st, "Expression"); + c(node.body, st, "Statement"); + }; + exports.ForInit = function(node, st, c) { + if (node.type == "VariableDeclaration") c(node, st); + else c(node, st, "Expression"); + }; + exports.DebuggerStatement = ignore; + + exports.FunctionDeclaration = function(node, st, c) { + c(node, st, "Function"); + }; + exports.VariableDeclaration = function(node, st, c) { + for (var i = 0; i < node.declarations.length; ++i) { + var decl = node.declarations[i]; + if (decl.init) c(decl.init, st, "Expression"); + } + }; + + exports.Function = function(node, st, c) { + c(node.body, st, "ScopeBody"); + }; + exports.ScopeBody = function(node, st, c) { + c(node, st, "Statement"); + }; + + exports.Expression = skipThrough; + exports.ThisExpression = ignore; + exports.ArrayExpression = function(node, st, c) { + for (var i = 0; i < node.elements.length; ++i) { + var elt = node.elements[i]; + if (elt) c(elt, st, "Expression"); + } + }; + exports.ObjectExpression = function(node, st, c) { + for (var i = 0; i < node.properties.length; ++i) + c(node.properties[i].value, st, "Expression"); + }; + exports.FunctionExpression = exports.FunctionDeclaration; + exports.SequenceExpression = function(node, st, c) { + for (var i = 0; i < node.expressions.length; ++i) + c(node.expressions[i], st, "Expression"); + }; + exports.UnaryExpression = exports.UpdateExpression = function(node, st, c) { + c(node.argument, st, "Expression"); + }; + exports.BinaryExpression = exports.AssignmentExpression = exports.LogicalExpression = function(node, st, c) { + c(node.left, st, "Expression"); + c(node.right, st, "Expression"); + }; + exports.ConditionalExpression = function(node, st, c) { + c(node.test, st, "Expression"); + c(node.consequent, st, "Expression"); + c(node.alternate, st, "Expression"); + }; + exports.NewExpression = exports.CallExpression = function(node, st, c) { + c(node.callee, st, "Expression"); + if (node.arguments) for (var i = 0; i < node.arguments.length; ++i) + c(node.arguments[i], st, "Expression"); + }; + exports.MemberExpression = function(node, st, c) { + c(node.object, st, "Expression"); + if (node.computed) c(node.property, st, "Expression"); + }; + exports.Identifier = exports.Literal = ignore; + + // A custom walker that keeps track of the scope chain and the + // variables defined in it. + function makeScope(prev) { + return {vars: Object.create(null), prev: prev}; + } + exports.scopeVisitor = exports.make({ + Function: function(node, scope, c) { + var inner = makeScope(scope); + for (var i = 0; i < node.params.length; ++i) + inner.vars[node.params[i].name] = {type: "argument", node: node.params[i]}; + if (node.id) { + var decl = node.type == "FunctionDeclaration"; + (decl ? scope : inner).vars[node.id.name] = + {type: decl ? "function" : "function name", node: node.id}; + } + c(node.body, inner, "ScopeBody"); + }, + TryStatement: function(node, scope, c) { + c(node.block, scope, "Statement"); + for (var i = 0; i < node.handlers.length; ++i) { + var handler = node.handlers[i], inner = makeScope(scope); + inner.vars[handler.param.name] = {type: "catch clause", node: handler.param}; + c(handler.body, inner, "ScopeBody"); + } + if (node.finalizer) c(node.finalizer, scope, "Statement"); + }, + VariableDeclaration: function(node, scope, c) { + for (var i = 0; i < node.declarations.length; ++i) { + var decl = node.declarations[i]; + scope.vars[decl.id.name] = {type: "var", node: decl.id}; + if (decl.init) c(decl.init, scope, "Expression"); + } + } + }); + +})(typeof exports == "undefined" ? acorn.walk = {} : exports); diff --git a/lib/codemirror-3.1/test/mode_test.css b/lib/codemirror-3.1/test/mode_test.css new file mode 100644 index 0000000000000000000000000000000000000000..1ac66737fb96a1df888ff48a49defb0a3b914a57 --- /dev/null +++ b/lib/codemirror-3.1/test/mode_test.css @@ -0,0 +1,10 @@ +.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; +} diff --git a/lib/codemirror-3.1/test/mode_test.js b/lib/codemirror-3.1/test/mode_test.js new file mode 100644 index 0000000000000000000000000000000000000000..51e51b9525c8299ae7fc670cffb2a48a58d689c1 --- /dev/null +++ b/lib/codemirror-3.1/test/mode_test.js @@ -0,0 +1,192 @@ +/** + * 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, text); + plain += text; + } + } + return {tokens: tokens, plain: plain}; + } + + test.mode = function(name, mode, tokens) { + var data = parseTokens(tokens); + return test(mode.name + "_" + name, function() { + return compare(data.plain, data.tokens, mode); + }); + }; + + function compare(text, expected, mode) { + + var expectedOutput = []; + for (var i = 0; i < expected.length; i += 2) { + var sty = expected[i]; + if (sty && sty.indexOf(" ")) sty = sty.split(' ').sort().join(' '); + expectedOutput.push(sty, expected[i + 1]); + } + + var observedOutput = highlight(text, mode); + + var pass, passStyle = ""; + pass = highlightOutputsEqual(expectedOutput, observedOutput); + passStyle = pass ? 'mt-pass' : 'mt-fail'; + + var s = ''; + if (pass) { + s += '
    '; + s += '
    ' + text + '
    '; + s += '
    '; + s += prettyPrintOutputTable(observedOutput); + s += '
    '; + s += '
    '; + return s; + } else { + s += '
    '; + s += '
    ' + text + '
    '; + s += '
    '; + s += 'expected:'; + s += prettyPrintOutputTable(expectedOutput); + s += 'observed:'; + s += prettyPrintOutputTable(observedOutput); + s += '
    '; + s += '
    '; + throw s; + } + } + + /** + * Emulation of CodeMirror's internal highlight routine for testing. Multi-line + * input is supported. + * + * @param string to highlight + * + * @param mode the mode that will do the actual highlighting + * + * @return array of [style, token] pairs + */ + 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; + var stream = new CodeMirror.StringStream(line); + if (line == "" && mode.blankLine) mode.blankLine(state); + /* Start copied code from CodeMirror.highlight */ + while (!stream.eol()) { + var style = mode.token(stream, state), substr = stream.current(); + if (style && style.indexOf(" ") > -1) style = style.split(' ').sort().join(' '); + + stream.start = stream.pos; + if (pos && st[pos-2] == style && !newLine) { + st[pos-1] += substr; + } else if (substr) { + st[pos++] = style; st[pos++] = substr; + } + // Give up when line is ridiculously long + if (stream.pos > 5000) { + st[pos++] = null; st[pos++] = this.text.slice(stream.pos); + break; + } + newLine = false; + } + } + + return st; + } + + /** + * Compare two arrays of output from highlight. + * + * @param o1 array of [style, token] pairs + * + * @param o2 array of [style, token] pairs + * + * @return boolean; true iff outputs equal + */ + function highlightOutputsEqual(o1, o2) { + if (o1.length != o2.length) return false; + for (var i = 0; i < o1.length; ++i) + if (o1[i] != o2[i]) return false; + return true; + } + + /** + * Print tokens and corresponding styles in a table. Spaces in the token are + * replaced with 'interpunct' dots (·). + * + * @param output array of [style, token] pairs + * + * @return html string + */ + function prettyPrintOutputTable(output) { + var s = ''; + s += ''; + for (var i = 0; i < output.length; i += 2) { + var style = output[i], val = output[i+1]; + s += + ''; + } + s += ''; + for (var i = 0; i < output.length; i += 2) { + s += ''; + } + s += '
    ' + + '' + + val.replace(/ /g,'\xb7') + + '' + + '
    ' + output[i] + '
    '; + return s; + } +})(); diff --git a/lib/codemirror-3.1/test/phantom_driver.js b/lib/codemirror-3.1/test/phantom_driver.js new file mode 100644 index 0000000000000000000000000000000000000000..dbad08db6334004729626bff6274cfa30ee798c4 --- /dev/null +++ b/lib/codemirror-3.1/test/phantom_driver.js @@ -0,0 +1,31 @@ +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); + } +} diff --git a/lib/codemirror-3.1/test/run.js b/lib/codemirror-3.1/test/run.js new file mode 100644 index 0000000000000000000000000000000000000000..5588d6f3883a49ab854a0e0fd92da5ec60f2e594 --- /dev/null +++ b/lib/codemirror-3.1/test/run.js @@ -0,0 +1,33 @@ +#!/usr/bin/env node + +var lint = require("./lint/lint"); + +lint.checkDir("mode"); +lint.checkDir("lib"); +lint.checkDir("addon"); + +var ok = lint.success(); + +var files = new (require('node-static').Server)('.'); + +var server = require('http').createServer(function (req, res) { + req.addListener('end', function () { + files.serve(req, res); + }); +}).addListener('error', function (err) { + throw err; +}).listen(3000, function () { + var child_process = require('child_process'); + child_process.exec("which phantomjs", function (err) { + if (err) { + console.error("PhantomJS is not installed. Download from http://phantomjs.org"); + process.exit(1); + } + var cmd = 'phantomjs test/phantom_driver.js'; + child_process.exec(cmd, function (err, stdout) { + server.close(); + console.log(stdout); + process.exit(err || !ok ? 1 : 0); + }); + }); +}); diff --git a/lib/codemirror-3.1/test/test.js b/lib/codemirror-3.1/test/test.js new file mode 100644 index 0000000000000000000000000000000000000000..80770ef422d7696c2a6e8aca338cc101040032d1 --- /dev/null +++ b/lib/codemirror-3.1/test/test.js @@ -0,0 +1,1345 @@ +var Pos = CodeMirror.Pos; + +function forEach(arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[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 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); + +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"); + eqPos(cm.getCursor(false), Pos(2, 2)); + eqPos(cm.getCursor(true), Pos(0, 4)); + cm.setSelection(Pos(1, 0)); + is(!cm.somethingSelected()); + eq(cm.getSelection(), ""); + eqPos(cm.getCursor(true), Pos(1, 0)); + cm.replaceSelection("abc"); + eq(cm.getSelection(), "abc"); + eq(cm.getValue(), "111111\nabc222222\n333333"); + cm.replaceSelection("def", "end"); + eq(cm.getSelection(), ""); + eqPos(cm.getCursor(true), Pos(1, 3)); + cm.setCursor(Pos(2, 1)); + eqPos(cm.getCursor(true), Pos(2, 1)); + cm.setCursor(1, 2); + eqPos(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)); + eqPos(cm.getCursor("head"), Pos(3, 5)); + eqPos(cm.getCursor("anchor"), Pos(3, 5)); + cm.setSelection(Pos(2, 5), Pos(5, 5)); + eqPos(cm.getCursor("head"), Pos(5, 5)); + eqPos(cm.getCursor("anchor"), Pos(2, 5)); + eqPos(cm.getCursor("start"), Pos(2, 5)); + eqPos(cm.getCursor("end"), Pos(5, 5)); + cm.setSelection(Pos(5, 5), Pos(2, 5)); + eqPos(cm.getCursor("head"), Pos(2, 5)); + eqPos(cm.getCursor("anchor"), Pos(5, 5)); + eqPos(cm.getCursor("start"), Pos(2, 5)); + eqPos(cm.getCursor("end"), Pos(5, 5)); + cm.extendSelection(Pos(3, 2)); + eqPos(cm.getCursor("head"), Pos(3, 2)); + eqPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(6, 2)); + eqPos(cm.getCursor("head"), Pos(6, 2)); + eqPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(6, 3), Pos(6, 4)); + eqPos(cm.getCursor("head"), Pos(6, 4)); + eqPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(0, 3), Pos(0, 4)); + eqPos(cm.getCursor("head"), Pos(0, 3)); + eqPos(cm.getCursor("anchor"), Pos(5, 5)); + cm.extendSelection(Pos(4, 5), Pos(6, 5)); + eqPos(cm.getCursor("head"), Pos(6, 5)); + eqPos(cm.getCursor("anchor"), Pos(4, 5)); + cm.setExtending(false); + cm.extendSelection(Pos(0, 3), Pos(0, 4)); + eqPos(cm.getCursor("head"), Pos(0, 4)); + eqPos(cm.getCursor("anchor"), Pos(0, 3)); +}); + +testCM("lines", function(cm) { + eq(cm.getLine(0), "111111"); + eq(cm.getLine(1), "222222"); + eq(cm.getLine(-1), null); + cm.removeLine(1); + cm.setLine(1, "abc"); + 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}); + +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.enterMode = "keep"; + 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("enterMode"), "keep"); + 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 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)); + var pos = cm.coordsChar({left: coords.left, top: coords.top + 5}); + eqPos(pos, Pos(line, ch)); + } + } +}); + +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.setLine(0, "def"); + 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: 2}); + +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(); + eqPos(cm.getCursor(true), Pos(0, 2)); + eqPos(cm.getCursor(false), Pos(0, 4)); + cm.setCursor(Pos(1, 0)); + cm.redo(); + eqPos(cm.getCursor(true), Pos(0, 2)); + eqPos(cm.getCursor(false), Pos(0, 2)); +}, {value: "abcdefgh\n"}); + +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(); + eqPos(f && f.from, p(test.f)); eqPos(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(); + eqPos(bookmark.find(), Pos(1, 5), "still there"); + cm.undo(); + var m1Pos = marker1.find(), m2Pos = marker2.find(); + eqPos(m1Pos.from, Pos(0, 1)); eqPos(m1Pos.to, Pos(0, 3)); + eqPos(m2Pos.from, Pos(0, 0)); eqPos(m2Pos.to, Pos(2, 1)); + eqPos(bookmark.find(), Pos(1, 5)); + cm.redo(); cm.redo(); + eq(bookmark.find(), null); + cm.undo(); + eqPos(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("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(); + eqPos(mBefore.find().from, Pos(0, 0)); + eqPos(mBefore.find().to, Pos(0, 1)); + eqPos(mAfter.find().from, Pos(3, 3)); + eqPos(mAfter.find().to, Pos(3, 4)); + eqPos(mAround.find().from, Pos(0, 2)); + eqPos(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("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)); + eqPos(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"); + eqPos(br.find(), Pos(0, 2)); + eqPos(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 + eqPos(br.find(), Pos(0, 1)); + eqPos(bl.find(), Pos(0, 1)); +}, {value: "abcdef"}); + +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("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("selectionPos", function(cm) { + 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.setLine(1, "hello"); + cm.setLine(0, "goop"); + 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); + eqPos(cm.getCursor(), Pos(5, 0)); + cm.setLine(3, "abcdefg"); + cm.setCursor(Pos(3, 6)); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), Pos(5, 4)); + cm.setLine(3, "ab"); + cm.setCursor(Pos(3, 2)); + CodeMirror.commands.goLineDown(cm); + eqPos(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); + eqPos(cm.coordsChar(pos_1_3), Pos(3, 3)); + m1.clear(); + var m1 = cm.markText(Pos(0, 0), Pos(1, 1), opts); + var m2 = cm.markText(Pos(1, 1), Pos(2, 0), opts); + eqPos(cm.coordsChar(pos_1_3), Pos(3, 3)); + m1.clear(); m2.clear(); + var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts); + eqPos(cm.coordsChar(pos_1_3), Pos(3, 3)); +}, {value: "123456\nabcdef\nghijkl\nmnopqr\n"}); + +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++;}); + eqPos(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); + eqPos(cm.getCursor(true), Pos(10, 0)); + eqPos(cm.getCursor(false), Pos(10, 4)); +}); + + +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) { + 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); + eqPos(cm.getCursor(), Pos(6, 2)); + CodeMirror.commands.goCharLeft(cm); + eqPos(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("x"), + clearOnEnter: true + }); + var cleared = 0; + CodeMirror.on(range, "clear", function(){++cleared;}); + cm.setCursor(0, 3); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), Pos(6, 2)); + CodeMirror.commands.goCharLeft(cm); + eqPos(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); + eqPos(cm.getCursor(), Pos(1, 3)); +}, 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); + eqPos(cm.getCursor(), Pos(2, 3)); + inner0.clear(); + CodeMirror.commands.goCharLeft(cm); + eqPos(cm.getCursor(), Pos(0, 1)); + outer.clear(); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), Pos(0, 2)); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), Pos(1, 8)); + inner2.clear(); + CodeMirror.commands.goCharLeft(cm); + eqPos(cm.getCursor(), Pos(1, 7)); + cm.setCursor(0, 5); + CodeMirror.commands.goCharRight(cm); + eqPos(cm.getCursor(), Pos(0, 6)); + CodeMirror.commands.goCharRight(cm); + eqPos(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("inlineWidget", function(cm) { + var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")}); + cm.setCursor(0, 2); + CodeMirror.commands.goLineDown(cm); + eqPos(cm.getCursor(), Pos(1, 4)); + cm.setCursor(0, 2); + cm.replaceSelection("hi"); + eqPos(w.find(), Pos(0, 2)); + cm.setCursor(0, 1); + cm.replaceSelection("ay"); + eqPos(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); + eqPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5})); + }); +}, null, ie_lt8); + +testCM("measureEndOfLine", function(cm) { + 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, "not at right"); + endPos = cm.charCoords(Pos(0, 18)); + eqPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18)); +}, {mode: "text/html", value: "", lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("scrollVerticallyAndHorizontally", function(cm) { + 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"); + eqPos(cm.getCursor(), Pos(0, 26)); +}, {lineWrapping: true}, ie_lt8 || opera_lt10); + +testCM("clickTab", function(cm) { + var p0 = cm.charCoords(Pos(0, 0)); + eqPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0)); + eqPos(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.setLine(0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah"); + is(sc.scrollWidth > baseWidth, "scrollbar present"); + cm.setLine(0, "foo"); + eq(sc.scrollWidth, baseWidth, "scrollbar gone"); + cm.setLine(0, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah"); + cm.setLine(1, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh"); + is(sc.scrollWidth > baseWidth, "present again"); + var curWidth = sc.scrollWidth; + cm.setLine(0, "foo"); + 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"); + eqPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), Pos(0, 7)); + cm.execCommand("goWordLeft"); + eqPos(cm.getCursor(), Pos(0, 5)); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), Pos(0, 12)); + cm.execCommand("goWordLeft"); + eqPos(cm.getCursor(), Pos(0, 9)); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), Pos(1, 9)); + cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), Pos(1, 13)); + cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); + eqPos(cm.getCursor(), Pos(2, 0)); +}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"}); + +testCM("charMovementCommands", function(cm) { + cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft"); + eqPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goCharRight"); cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(0, 2)); + cm.setCursor(Pos(1, 0)); + cm.execCommand("goColumnLeft"); + eqPos(cm.getCursor(), Pos(1, 0)); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), Pos(0, 5)); + cm.execCommand("goColumnRight"); + eqPos(cm.getCursor(), Pos(0, 5)); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(1, 0)); + cm.execCommand("goLineEnd"); + eqPos(cm.getCursor(), Pos(1, 5)); + cm.execCommand("goLineStartSmart"); + eqPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineStartSmart"); + eqPos(cm.getCursor(), Pos(1, 0)); + cm.setCursor(Pos(2, 0)); + cm.execCommand("goCharRight"); cm.execCommand("goColumnRight"); + eqPos(cm.getCursor(), Pos(2, 0)); +}, {value: "line1\n ine2\n"}); + +testCM("verticalMovementCommands", function(cm) { + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goLineDown"); + if (!phantom) // This fails in PhantomJS, though not in a real Webkit + eqPos(cm.getCursor(), Pos(1, 0)); + cm.setCursor(Pos(1, 12)); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), Pos(2, 5)); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), Pos(3, 0)); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), Pos(2, 5)); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), Pos(1, 12)); + cm.execCommand("goPageDown"); + eqPos(cm.getCursor(), Pos(5, 0)); + cm.execCommand("goPageDown"); cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), Pos(5, 0)); + cm.execCommand("goPageUp"); + eqPos(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("rtlMovement", function(cm) { + forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج", + "خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر"], function(line) { + var inv = line.charAt(0) == "خ"; + cm.setValue(line + "\n"); cm.execCommand(inv ? "goLineEnd" : "goLineStart"); + var cursor = byClassName(cm.getWrapperElement(), "CodeMirror-cursor")[0]; + var prevX = cursor.offsetLeft, prevY = cursor.offsetTop; + for (var i = 0; i <= line.length; ++i) { + cm.execCommand("goCharRight"); + 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(inv ? "goLineStart" : "goLineEnd"); + prevX = cursor.offsetLeft; + for (var i = 0; i < line.length; ++i) { + cm.execCommand("goCharLeft"); + is(cursor.offsetLeft < prevX, "moved left"); + prevX = cursor.offsetLeft; + } + }); +}, {rtlMoveVisually: true}); + +// Verify that updating a line clears its bidi ordering +testCM("bidiUpdate", function(cm) { + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("خحج", "start"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(0, 4)); +}, {value: "abcd\n"}); + +testCM("movebyTextUnit", function(cm) { + cm.setValue("בְּרֵאשִ\ńéée\n"); + cm.execCommand("goLineEnd"); + for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(0, 0)); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(1, 0)); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(1, 3)); + cm.execCommand("goCharRight"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(1, 6)); +}); + +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) { + 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"); + eqPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineUp"); + eqPos(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("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) { + var longLine = "abcdef ghiklmnop qrstuvw xyz "; + longLine += longLine; longLine += longLine; longLine += longLine; + cm.setLine(2, longLine); + cm.setSize("200px", null); + cm.getWrapperElement().style.lineHeight = 2; + cm.refresh(); + cm.setCursor(Pos(0, 1)); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineDown"); + eq(cm.getCursor().line, 2); + is(cm.getCursor().ch > 1); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), Pos(2, 1)); + cm.execCommand("goLineUp"); + eqPos(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"); + eqPos(cm.getCursor(), Pos(1, 2)); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), Pos(0, 2)); +}, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"}); + +testCM("addLineClass", function(cm) { + function cls(line, text, bg, wrap) { + var i = cm.lineInfo(line); + eq(i.textClass, text); + eq(i.bgClass, bg); + eq(i.wrapClass, wrap); + } + cm.addLineClass(0, "text", "foo"); + cm.addLineClass(0, "text", "bar"); + cm.addLineClass(1, "background", "baz"); + cm.addLineClass(1, "wrap", "foo"); + cls(0, "foo bar", null, null); + cls(1, null, "baz", "foo"); + var lines = cm.display.lineDiv; + eq(byClassName(lines, "foo").length, 2); + eq(byClassName(lines, "bar").length, 1); + eq(byClassName(lines, "baz").length, 1); + cm.removeLineClass(0, "text", "foo"); + cls(0, "bar", null, null); + cm.removeLineClass(0, "text", "foo"); + cls(0, "bar", null, null); + cm.removeLineClass(0, "text", "bar"); + cls(0, null, null, null); + cm.addLineClass(1, "wrap", "quux"); + cls(1, null, "baz", "foo quux"); + cm.removeLineClass(1, "wrap"); + cls(1, null, "baz", null); +}, {value: "hohoho\n"}); + +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"); + eqPos(cm.getCursor(), Pos(0, 5)); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), Pos(0, 1)); + m.clear(); + m = atom(0, 0, 0, 5, true); + eqPos(cm.getCursor(), Pos(0, 5), "pushed out"); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), Pos(0, 5)); + m.clear(); + m = atom(8, 4, 9, 10, false, true); + cm.setCursor(Pos(9, 8)); + eqPos(cm.getCursor(), Pos(8, 4), "set"); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(8, 4), "char right"); + cm.execCommand("goLineDown"); + eqPos(cm.getCursor(), Pos(8, 4), "line down"); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), Pos(8, 3)); + m.clear(); + m = atom(1, 1, 3, 8); + cm.setCursor(Pos(2, 0)); + eqPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goCharRight"); + eqPos(cm.getCursor(), Pos(3, 8)); + cm.execCommand("goLineUp"); + eqPos(cm.getCursor(), Pos(1, 1)); + cm.execCommand("goLineDown"); + eqPos(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("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"); + eqPos(cm.getCursor(), Pos(0, 2)); + eq(cm.getLine(0), "abcde"); + cm.execCommand("selectAll"); + cm.replaceSelection("oops"); + eq(cm.getValue(), "oopsbcd"); + cm.undo(); + eqPos(m.find().from, Pos(0, 1)); + eqPos(m.find().to, Pos(0, 4)); + m.clear(); + cm.setCursor(Pos(0, 2)); + cm.replaceSelection("hi"); + eq(cm.getLine(0), "abhicde"); + eqPos(cm.getCursor(), Pos(0, 4)); + m = mark(0, 2, 2, 2, true); + cm.setSelection(Pos(1, 1), Pos(2, 4)); + cm.replaceSelection("t", "end"); + eqPos(cm.getCursor(), Pos(2, 3)); + eq(cm.getLine(2), "klto"); + cm.execCommand("goCharLeft"); + cm.execCommand("goCharLeft"); + eqPos(cm.getCursor(), Pos(0, 2)); + cm.setSelection(Pos(0, 1), Pos(0, 3)); + cm.replaceSelection("xx"); + eqPos(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"); + eq(cm.isClean(), false); + cm.undo(); + eq(cm.isClean(), true); + cm.replaceSelection("boo"); + cm.replaceSelection("baz"); + 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("addKeyMap", function(cm) { + function sendKey(code) { + cm.triggerOnKeyDown({type: "keydown", keyCode: code, + preventDefault: function(){}, stopPropagation: function(){}}); + } + + sendKey(39); + eqPos(cm.getCursor(), Pos(0, 1)); + var test = 0; + var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }} + cm.addKeyMap(map1); + sendKey(39); + eqPos(cm.getCursor(), Pos(0, 1)); + eq(test, 1); + cm.addKeyMap(map2); + sendKey(39); + eq(test, 2); + cm.removeKeyMap(map1); + sendKey(39); + eq(test, 12); + cm.removeKeyMap(map2); + sendKey(39); + eq(test, 12); + eqPos(cm.getCursor(), Pos(0, 2)); + cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"}); + sendKey(39); + eq(test, 55); + cm.removeKeyMap("mymap"); + sendKey(39); + eqPos(cm.getCursor(), Pos(0, 3)); +}, {value: "abc"}); + +testCM("findPosH", function(cm) { + forEach([{from: Pos(0, 0), to: Pos(0, 1), by: 1}, + {from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true}, + {from: Pos(0, 0), to: Pos(0, 4), by: 1, unit: "word"}, + {from: Pos(0, 0), to: Pos(0, 8), by: 2, unit: "word"}, + {from: Pos(0, 0), to: Pos(2, 0), by: 20, unit: "word", hitSide: true}, + {from: Pos(0, 7), to: Pos(0, 5), by: -1, unit: "word"}, + {from: Pos(0, 4), to: Pos(0, 8), by: 1, unit: "word"}, + {from: Pos(1, 0), to: Pos(1, 18), by: 3, unit: "word"}, + {from: Pos(1, 22), to: Pos(1, 5), by: -3, unit: "word"}, + {from: Pos(1, 15), to: Pos(1, 10), by: -5}, + {from: Pos(1, 15), to: Pos(1, 10), by: -5, unit: "column"}, + {from: Pos(1, 15), to: Pos(1, 0), by: -50, unit: "column", hitSide: true}, + {from: Pos(1, 15), to: Pos(1, 24), by: 50, unit: "column", hitSide: true}, + {from: Pos(1, 15), to: Pos(2, 0), by: 50, hitSide: true}], function(t) { + var r = cm.findPosH(t.from, t.by, t.unit || "char"); + eqPos(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("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, sel) { + sel.head = notAtEnd(cm, sel.head); + sel.anchor = notAtEnd(cm, sel.anchor); + }); + + addDoc(cm, 10, 10); + cm.execCommand("goLineEnd"); + eqPos(cm.getCursor(), Pos(0, 9)); + cm.execCommand("selectAll"); + eqPos(cm.getCursor("start"), Pos(0, 0)); + eqPos(cm.getCursor("end"), Pos(9, 9)); +}); \ No newline at end of file diff --git a/lib/codemirror-3.1/test/vim_test.js b/lib/codemirror-3.1/test/vim_test.js new file mode 100644 index 0000000000000000000000000000000000000000..52d9ea3909d2118f81eef5c775e439f82f06a497 --- /dev/null +++ b/lib/codemirror-3.1/test/vim_test.js @@ -0,0 +1,1047 @@ +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' + +' return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\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 word1 = { + start: { line: wordLine.line, ch: 1 }, + end: { line: wordLine.line, ch: 5 } +}; +var word2 = { + start: { line: wordLine.line, ch: word1.end.ch + 2 }, + end: { line: wordLine.line, ch: word1.end.ch + 4 } +}; +var word3 = { + start: { line: bigWordLine.line, ch: 1 }, + end: { line: bigWordLine.line, ch: 5 } +}; +var bigWord1 = word1; +var bigWord2 = word2; +var bigWord3 = { + start: { line: bigWordLine.line, ch: 1 }, + end: { line: bigWordLine.line, ch: 7 } +}; +var bigWord4 = { + start: { line: bigWordLine.line, ch: bigWord1.end.ch + 3 }, + end: { line: bigWordLine.line, ch: bigWord1.end.ch + 7 } +} +var oChars = [ { line: charLine.line, ch: 1 }, + { line: charLine.line, ch: 3 }, + { line: charLine.line, ch: 7 } ]; +var pChars = [ { line: charLine.line, ch: 2 }, + { line: charLine.line, ch: 4 }, + { line: charLine.line, ch: 6 }, + { line: charLine.line, ch: 8 } ]; +var numChars = [ { line: charLine.line, ch: 10 }, + { line: charLine.line, ch: 12 }, + { line: charLine.line, ch: 14 }, + { line: charLine.line, ch: 16 }, + { line: charLine.line, ch: 18 }]; +var parens1 = { + start: { line: bracesLine.line, ch: 1 }, + end: { line: bracesLine.line, ch: 3 } +}; +var squares1 = { + start: { line: bracesLine.line, ch: 5 }, + end: { line: bracesLine.line, ch: 7 } +}; +var curlys1 = { + start: { line: bracesLine.line, ch: 9 }, + end: { line: bracesLine.line, ch: 11 } +}; + +function copyCursor(cur) { + return { ch: cur.ch, line: cur.line }; +} + +function testVim(name, run, opts, expectedFail) { + var vimOpts = { + lineNumbers: true, + keyMap: 'vim', + 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); + CodeMirror.Vim.maybeInitState(cm); + var vim = cm.vimState; + + function doKeysFn(cm) { + return function(args) { + if (args instanceof Array) { + arguments = args; + } + for (var i = 0; i < arguments.length; i++) { + CodeMirror.Vim.handleKey(cm, arguments[i]); + } + } + } + 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); + } + eqPos(pos, cm.getCursor()); + } + } + function fakeOpenDialog(result) { + return function(text, callback) { + return callback(result); + } + } + var helpers = { + doKeys: doKeysFn(cm), + doEx: doExFn(cm), + assertCursorAt: assertCursorAtFn(cm), + fakeOpenDialog: fakeOpenDialog, + getRegisterController: function() { + return CodeMirror.Vim.getRegisterController(); + } + } + CodeMirror.Vim.clearVimGlobalState_(); + var successful = false; + try { + run(cm, vim, helpers); + successful = true; + } finally { + if ((debug && !successful) || verbose) { + place.style.visibility = "visible"; + } else { + place.removeChild(cm.getWrapperElement()); + } + } + }, expectedFail); +}; + +/** + * @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 = { line: 0, ch: 0 }; + } + cm.setCursor(startPos); + helpers.doKeys(keys); + helpers.assertCursorAt(endPos); + }); +}; + +function makeCursor(line, ch) { + return { line: line, ch: ch }; +}; + +function offsetCursor(cur, offsetLine, offsetCh) { + return { line: cur.line + offsetLine, ch: 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('k', 'k', offsetCursor(word3.end, -1, 0), word3.end); +testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4)); +testMotion('w', 'w', word1.start); +testMotion('w_repeat', ['2', 'w'], word2.start); +testMotion('w_wrap', ['w'], word3.start, word2.start); +testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument); +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('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('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('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(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); +// 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) { + var startPos = { line: 0, ch: 0 }; + cm.setCursor(startPos); + helpers.doKeys(['$']); + helpers.doKeys(['j']); + // After moving to Eol and then down, we should be at Eol of line 2 + helpers.assertCursorAt({ line: 1, ch: lines[1].length - 1 }); + helpers.doKeys(['j']); + // After moving down, we should be at Eol of line 3 + helpers.assertCursorAt({ line: 2, ch: 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({ line: 3, ch: 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({ line: 5, ch: 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('}', 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' }); + +// 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.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 ' }); +testVim('dl_eol', function(cm, vim, helpers) { + var curStart = makeCursor(0, 6); + cm.setCursor(curStart); + helpers.doKeys('d', 'l'); + eq(' word1', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq(' ', register.text); + is(!register.linewise); + helpers.assertCursorAt(0, 6); +}, { 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.text); + is(!register.linewise); + eqPos(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.text); + is(!register.linewise); + eqPos(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.text); + 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(' word1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.text); + is(!register.linewise); + helpers.assertCursorAt(0, 3); +}, { 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.text); + 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(' word1 ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('', register.text); + is(!register.linewise); + helpers.assertCursorAt(0, 3); +}, { 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.text); + is(!register.linewise); + eqPos(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.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1 word2' }); +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. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1 ', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { 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. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', 'w'); + eq(' \nword2', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +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. + var curStart = makeCursor(0, 1); + cm.setCursor(curStart); + helpers.doKeys('d', '2', 'w'); + eq(' ', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('word1\nword2', register.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2' }); +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.text); + is(!register.linewise); + eqPos(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.text); + is(!register.linewise); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\nword2 ' }); +testVim('dd', function(cm, vim, helpers) { + cm.setCursor(0, 3); + var expectedBuffer = cm.getRange({ line: 0, ch: 0 }, + { line: 1, ch: 0 }); + var expectedLineCount = cm.lineCount() - 1; + helpers.doKeys('d', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + 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({ line: 0, ch: 0 }, + { line: 2, ch: 0 }); + var expectedLineCount = cm.lineCount() - 2; + helpers.doKeys('2', 'd', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + 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({ line: 0, ch: 0 }, + { line: 2, ch: 0 }); + var expectedLineCount = cm.lineCount() - 2; + helpers.doKeys('d', '2', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + 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({ line: 0, ch: 0 }, + { line: 6, ch: 0 }); + var expectedLineCount = cm.lineCount() - 6; + helpers.doKeys('2', 'd', '3', 'd'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + is(register.linewise); + helpers.assertCursorAt(0, lines[6].textStart); +}); +// 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.text); + is(!register.linewise); + eqPos(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({ line: 0, ch: 0 }, + { line: 6, ch: 0 }); + var expectedLineCount = cm.lineCount(); + helpers.doKeys('2', 'y', '3', 'y'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + is(register.linewise); + eqPos(curStart, cm.getCursor()); +}); +// 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_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.text); + is(!register.linewise); + eqPos(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({ line: 0, ch: 0 }, + { line: 6, ch: 0 }); + var expectedLineCount = cm.lineCount() - 5; + helpers.doKeys('2', 'c', '3', 'c'); + eq(expectedLineCount, cm.lineCount()); + var register = helpers.getRegisterController().getRegister(); + eq(expectedBuffer, register.text); + is(register.linewise); + helpers.assertCursorAt(0, lines[0].textStart); + eq('vim-insert', cm.getOption('keyMap')); +}); +// 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.text); + is(!register.linewise); + eqPos(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.text); + is(!register.linewise); + eqPos(curStart, cm.getCursor()); +}, { value: ' word1\nword2\nword3\nword4\nword5\nword6' }); +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.text); + 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.text); + 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.text); + 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.text); + is(!register.linewise); + helpers.assertCursorAt(0, 1); +}, { value: ' word1\n word2\nword3 ', indentUnit: 2 }); + +// Operator-motion tests +testVim('D', function(cm, vim, helpers) { + var curStart = makeCursor(0, 3); + cm.setCursor(curStart); + helpers.doKeys('D'); + eq(' wo\nword2\n word3', cm.getValue()); + var register = helpers.getRegisterController().getRegister(); + eq('rd1', register.text); + is(!register.linewise); + helpers.assertCursorAt(0, 3); +}, { 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.text); + is(!register.linewise); + helpers.assertCursorAt(0, 3); + 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('rd1', register.text); + is(!register.linewise); + helpers.assertCursorAt(0, 3); +}, { value: ' word1\nword2\n word3' }); + +// Action tests +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('i', function(cm, vim, helpers) { + cm.setCursor(0, 1); + helpers.doKeys('i'); + helpers.assertCursorAt(0, 1); + eq('vim-insert', cm.getOption('keyMap')); +}); +testVim('A', function(cm, vim, helpers) { + cm.setCursor(0, 0); + helpers.doKeys('A'); + helpers.assertCursorAt(0, lines[0].length); + eq('vim-insert', cm.getOption('keyMap')); +}); +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('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', 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').set('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').set('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', 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', cm.getValue()); + helpers.assertCursorAt(0, 3); +}, { value: 'wordet' }); +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(0, 0); + helpers.doKeys('`', 't'); + helpers.assertCursorAt(2, 2); +}); +testVim('visual', function(cm, vim, helpers) { + helpers.doKeys('l', 'v', 'l', 'l'); + helpers.assertCursorAt(0, 3); + eqPos(makeCursor(0, 1), cm.getCursor('anchor')); + helpers.doKeys('d'); + eq('15', cm.getValue()); +}, { value: '12345' }); +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_marks', function(cm, vim, helpers) { + helpers.doKeys('l', 'v', 'l', 'l', 'v'); + // Test visual mode marks + cm.setCursor(0, 0); + helpers.doKeys('\'', '<'); + helpers.assertCursorAt(0, 1); + helpers.doKeys('\'', '>'); + helpers.assertCursorAt(0, 3); +}); +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()); +}, { value: ' 1\n 2\n 3\n 4\n 5' }); +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('? 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' }); +//:noh should clear highlighting of search-results but allow to resume search through n +testVim('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('*', 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('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_substitute_same_line', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('s/one/two'); + eq('one one\n two two', cm.getValue()); +}, { value: 'one one\n one one'}); +testVim('ex_substitute_global', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('%s/one/two'); + 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'); + eq('0\n0\n0\n4', cm.getValue()); +}, { value: '1\n2\n3\n4' }); +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'); + eq('1\n0\n0\n0\n5', cm.getValue()); +}, { value: '1\n2\n3\n4\n5' }); +testVim('ex_substitute_capture', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('s/(\\d+)/$1$1/') + eq('a1111 a1212 a1313', cm.getValue()); +}, { value: 'a11 a12 a13' }); +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'); + eq('abb ab2 ab3', cm.getValue()); +}, { value: 'a11 a12 a13' }); +testVim('ex_substitute_count', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('s/\\d/0/i 2'); + eq('1\n0\n0\n4', cm.getValue()); +}, { value: '1\n2\n3\n4' }); +testVim('ex_substitute_count_with_range', function(cm, vim, helpers) { + cm.setCursor(1, 0); + helpers.doEx('1,3s/\\d/0/ 3'); + eq('1\n2\n0\n0', cm.getValue()); +}, { value: '1\n2\n3\n4' }); +// TODO: Reset key maps after each test. +testVim('ex_map_key2key', function(cm, vim, helpers) { + helpers.doEx('map a x'); + helpers.doKeys('a'); + helpers.assertCursorAt(0, 0); + eq('bc', cm.getValue()); +}, { 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); +}); +testVim('ex_map_ex2key:', function(cm, vim, helpers) { + helpers.doEx('map :del x'); + helpers.doEx('del'); + helpers.assertCursorAt(0, 0); + eq('bc', cm.getValue()); +}, { 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); +}); +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); +}); +// 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('Ctrl-Enter','Space'); + is(res,'Mapping to key failed'); +}); +// 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()); +}, { value: 'abc' }); diff --git a/lib/codemirror-3.1/theme/ambiance-mobile.css b/lib/codemirror-3.1/theme/ambiance-mobile.css new file mode 100644 index 0000000000000000000000000000000000000000..35b3750c1b3795b11e38f906d5a32a41462cc911 --- /dev/null +++ b/lib/codemirror-3.1/theme/ambiance-mobile.css @@ -0,0 +1,6 @@ +.cm-s-ambiance.CodeMirror { + -webkit-box-shadow: none; + -moz-box-shadow: none; + -o-box-shadow: none; + box-shadow: none; +} diff --git a/lib/codemirror-3.1/theme/ambiance.css b/lib/codemirror-3.1/theme/ambiance.css new file mode 100644 index 0000000000000000000000000000000000000000..beec553851a9788de14dbea06ca21f6abc12adf6 --- /dev/null +++ b/lib/codemirror-3.1/theme/ambiance.css @@ -0,0 +1,76 @@ +/* ambiance theme for codemirror */ + +/* Color scheme */ + +.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 { 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-error { color: #AF2018; } +.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-header {color: blue;} +.cm-s-ambiance .cm-quote { color: #24C2C7; } +.cm-s-ambiance .cm-hr { color: pink; } +.cm-s-ambiance .cm-link { color: #F4C20B; } +.cm-s-ambiance .cm-special { color: #FF9D00; } + +.cm-s-ambiance .CodeMirror-matchingbracket { color: #0f0; } +.cm-s-ambiance .CodeMirror-nonmatchingbracket { color: #f22; } + +.cm-s-ambiance .CodeMirror-selected { + background: rgba(255, 255, 255, 0.15); +} +.cm-s-ambiance .CodeMirror-focused .CodeMirror-selected { + background: rgba(255, 255, 255, 0.10); +} + +/* Editor styling */ + +.cm-s-ambiance.CodeMirror { + line-height: 1.40em; + font-family: Monaco, Menlo,"Andale Mono","lucida console","Courier New",monospace !important; + color: #E6E1DC; + background-color: #202020; + -webkit-box-shadow: inset 0 0 10px black; + -moz-box-shadow: inset 0 0 10px black; + -o-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: #222; + padding: 0 5px; +} + +.cm-s-ambiance .CodeMirror-lines .CodeMirror-cursor { + border-left: 1px solid #7991E8; +} + +.cm-s-ambiance .activeline { + 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"); +} diff --git a/lib/codemirror-3.1/theme/blackboard.css b/lib/codemirror-3.1/theme/blackboard.css new file mode 100644 index 0000000000000000000000000000000000000000..f2bde690c8528a8f6cd47d3ce0e0d2c56b62e222 --- /dev/null +++ b/lib/codemirror-3.1/theme/blackboard.css @@ -0,0 +1,25 @@ +/* Port of TextMate's Blackboard theme */ + +.cm-s-blackboard.CodeMirror { background: #0C1021; color: #F8F8F8; } +.cm-s-blackboard .CodeMirror-selected { background: #253B76 !important; } +.cm-s-blackboard .CodeMirror-gutters { background: #0C1021; border-right: 0; } +.cm-s-blackboard .CodeMirror-linenumber { color: #888; } +.cm-s-blackboard .CodeMirror-cursor { border-left: 1px solid #A7A7A7 !important; } + +.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-error { background: #9D1E15; color: #F8F8F8; } +.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; } diff --git a/lib/codemirror-3.1/theme/cobalt.css b/lib/codemirror-3.1/theme/cobalt.css new file mode 100644 index 0000000000000000000000000000000000000000..6095799f364dba2c3c876b0d875dd2364b0e21c1 --- /dev/null +++ b/lib/codemirror-3.1/theme/cobalt.css @@ -0,0 +1,18 @@ +.cm-s-cobalt.CodeMirror { background: #002240; color: white; } +.cm-s-cobalt div.CodeMirror-selected { background: #b36539 !important; } +.cm-s-cobalt .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-cobalt .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-cobalt .CodeMirror-cursor { border-left: 1px solid white !important; } + +.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 { color: white; } +.cm-s-cobalt span.cm-error { color: #9d1e15; } +.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; } diff --git a/lib/codemirror-3.1/theme/eclipse.css b/lib/codemirror-3.1/theme/eclipse.css new file mode 100644 index 0000000000000000000000000000000000000000..47d66a012e6f0b765ad64e6807c24ffbffa83658 --- /dev/null +++ b/lib/codemirror-3.1/theme/eclipse.css @@ -0,0 +1,25 @@ +.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 {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-error {color: #f00;} +.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 .CodeMirror-matchingbracket { + border:1px solid grey; + color:black !important;; +} diff --git a/lib/codemirror-3.1/theme/elegant.css b/lib/codemirror-3.1/theme/elegant.css new file mode 100644 index 0000000000000000000000000000000000000000..d0ce0cb566b9fb4334fdbaede603aa72ece2800f --- /dev/null +++ b/lib/codemirror-3.1/theme/elegant.css @@ -0,0 +1,10 @@ +.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-error {background-color: #fdd;} +.cm-s-elegant span.cm-link {color: #762;} diff --git a/lib/codemirror-3.1/theme/erlang-dark.css b/lib/codemirror-3.1/theme/erlang-dark.css new file mode 100644 index 0000000000000000000000000000000000000000..ea9c26c44da21c9847eb2384b19da7907dae84fa --- /dev/null +++ b/lib/codemirror-3.1/theme/erlang-dark.css @@ -0,0 +1,21 @@ +.cm-s-erlang-dark.CodeMirror { background: #002240; color: white; } +.cm-s-erlang-dark div.CodeMirror-selected { background: #b36539 !important; } +.cm-s-erlang-dark .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-erlang-dark .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-erlang-dark .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-erlang-dark span.cm-atom { color: #845dc4; } +.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: #eeaaaa; } +.cm-s-erlang-dark span.cm-comment { color: #7777ff; } +.cm-s-erlang-dark span.cm-def { color: #ee77aa; } +.cm-s-erlang-dark span.cm-error { color: #9d1e15; } +.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: #dd1111; } +.cm-s-erlang-dark span.cm-string { color: #3ad900; } +.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: #ee00ee; } diff --git a/lib/codemirror-3.1/theme/lesser-dark.css b/lib/codemirror-3.1/theme/lesser-dark.css new file mode 100644 index 0000000000000000000000000000000000000000..67f71ad7272b4947b2b0ac26a85952ee219b80c9 --- /dev/null +++ b/lib/codemirror-3.1/theme/lesser-dark.css @@ -0,0 +1,44 @@ +/* +http://lesscss.org/ dark theme +Ported to CodeMirror by Peter Kroon +*/ +.cm-s-lesser-dark { + line-height: 1.3em; +} +.cm-s-lesser-dark { + font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', 'Monaco', Courier, monospace !important; +} + +.cm-s-lesser-dark.CodeMirror { background: #262626; color: #EBEFE7; text-shadow: 0 -1px 1px #262626; } +.cm-s-lesser-dark div.CodeMirror-selected {background: #45443B !important;} /* 33322B*/ +.cm-s-lesser-dark .CodeMirror-cursor { border-left: 1px solid white !important; } +.cm-s-lesser-dark pre { padding: 0 8px; }/*editable code holder*/ + +div.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-linenumber { color: #777; } + +.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 { 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-error { color: #9d1e15; } +.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: #00c;} +.cm-s-lesser-dark span.cm-header {color: #a0a;} +.cm-s-lesser-dark span.cm-quote {color: #090;} +.cm-s-lesser-dark span.cm-hr {color: #999;} +.cm-s-lesser-dark span.cm-link {color: #00c;} diff --git a/lib/codemirror-3.1/theme/monokai.css b/lib/codemirror-3.1/theme/monokai.css new file mode 100644 index 0000000000000000000000000000000000000000..a0b3c7c0afeba20b004492b77091948d9bd4b59c --- /dev/null +++ b/lib/codemirror-3.1/theme/monokai.css @@ -0,0 +1,28 @@ +/* Based on Sublime Text's Monokai theme */ + +.cm-s-monokai.CodeMirror {background: #272822; color: #f8f8f2;} +.cm-s-monokai div.CodeMirror-selected {background: #49483E !important;} +.cm-s-monokai .CodeMirror-gutters {background: #272822; border-right: 0px;} +.cm-s-monokai .CodeMirror-linenumber {color: #d0d0d0;} +.cm-s-monokai .CodeMirror-cursor {border-left: 1px solid #f8f8f0 !important;} + +.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-property, .cm-s-monokai span.cm-attribute {color: #a6e22e;} +.cm-s-monokai span.cm-keyword {color: #f92672;} +.cm-s-monokai span.cm-string {color: #e6db74;} + +.cm-s-monokai span.cm-variable {color: #a6e22e;} +.cm-s-monokai span.cm-variable-2 {color: #9effff;} +.cm-s-monokai span.cm-def {color: #fd971f;} +.cm-s-monokai span.cm-error {background: #f92672; color: #f8f8f0;} +.cm-s-monokai span.cm-bracket {color: #f8f8f2;} +.cm-s-monokai span.cm-tag {color: #f92672;} +.cm-s-monokai span.cm-link {color: #ae81ff;} + +.cm-s-monokai .CodeMirror-matchingbracket { + text-decoration: underline; + color: white !important; +} diff --git a/lib/codemirror-3.1/theme/neat.css b/lib/codemirror-3.1/theme/neat.css new file mode 100644 index 0000000000000000000000000000000000000000..8a307f802c4b24d14b75f04fb2cb679080d1b75c --- /dev/null +++ b/lib/codemirror-3.1/theme/neat.css @@ -0,0 +1,9 @@ +.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; } diff --git a/lib/codemirror-3.1/theme/night.css b/lib/codemirror-3.1/theme/night.css new file mode 100644 index 0000000000000000000000000000000000000000..8804a399a189efc06c01fcc9bca41549d3f28e92 --- /dev/null +++ b/lib/codemirror-3.1/theme/night.css @@ -0,0 +1,21 @@ +/* Loosely based on the Midnight Textmate theme */ + +.cm-s-night.CodeMirror { background: #0a001f; color: #f8f8f8; } +.cm-s-night div.CodeMirror-selected { background: #447 !important; } +.cm-s-night .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } +.cm-s-night .CodeMirror-linenumber { color: #f8f8f8; } +.cm-s-night .CodeMirror-cursor { border-left: 1px solid white !important; } + +.cm-s-night span.cm-comment { color: #6900a1; } +.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 { color: white; } +.cm-s-night span.cm-error { color: #9d1e15; } +.cm-s-night span.cm-bracket { color: #8da6ce; } +.cm-s-night span.cm-comment { color: #6900a1; } +.cm-s-night span.cm-builtin, .cm-s-night span.cm-special { color: #ff9e59; } +.cm-s-night span.cm-link { color: #845dc4; } diff --git a/lib/codemirror-3.1/theme/rubyblue.css b/lib/codemirror-3.1/theme/rubyblue.css new file mode 100644 index 0000000000000000000000000000000000000000..8817de07bf6a39fdaf744f4a687a268cf4a753dc --- /dev/null +++ b/lib/codemirror-3.1/theme/rubyblue.css @@ -0,0 +1,21 @@ +.cm-s-rubyblue { font:13px/1.4em Trebuchet, Verdana, sans-serif; } /* - customized editor font - */ + +.cm-s-rubyblue.CodeMirror { background: #112435; color: white; } +.cm-s-rubyblue div.CodeMirror-selected { background: #38566F !important; } +.cm-s-rubyblue .CodeMirror-gutters { background: #1F4661; border-right: 7px solid #3E7087; } +.cm-s-rubyblue .CodeMirror-linenumber { color: white; } +.cm-s-rubyblue .CodeMirror-cursor { border-left: 1px solid white !important; } + +.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 { color: white; } +.cm-s-rubyblue span.cm-error { color: #AF2018; } +.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; } diff --git a/lib/codemirror-3.1/theme/solarized.css b/lib/codemirror-3.1/theme/solarized.css new file mode 100644 index 0000000000000000000000000000000000000000..06a6c7fa1b7d85c7fc3443077456c6b61156a0e0 --- /dev/null +++ b/lib/codemirror-3.1/theme/solarized.css @@ -0,0 +1,207 @@ +/* +Solarized theme for code-mirror +http://ethanschoonover.com/solarized +*/ + +/* +Solarized color pallet +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; + font-family: Menlo,Monaco,"Andale Mono","lucida console","Courier New",monospace !important; + 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-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: #268bd2; } +.cm-s-solarized .cm-variable-2 { color: #b58900; } +.cm-s-solarized .cm-variable-3 { 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-error, +.cm-s-solarized .cm-invalidchar { + color: #586e75; + border-bottom: 1px dotted #dc322f; +} +.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-header { color: #586e75; } +.cm-s-solarized .cm-quote { color: #93a1a1; } +.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-strong { color: #eee; } +.cm-s-solarized .cm-tab:before { + content: "➤"; /*visualize tab character*/ + color: #586e75; +} + +.cm-s-solarized.cm-s-dark .CodeMirror-focused .CodeMirror-selected { + background: #386774; + color: inherit; +} + +.cm-s-solarized.cm-s-dark ::selection { + background: #386774; + color: inherit; +} + +.cm-s-solarized.cm-s-dark .CodeMirror-selected { + background: #586e75; +} + +.cm-s-solarized.cm-s-light .CodeMirror-focused .CodeMirror-selected { + background: #eee8d5; + color: inherit; +} + +.cm-s-solarized.cm-s-light ::selection { + background: #eee8d5; + color: inherit; +} + +.cm-s-solarized.cm-s-light .CodeMirror-selected { + background: #93a1a1; +} + + + +/* 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; +} + +/* Gutter border and some shadow from it */ +.cm-s-solarized .CodeMirror-gutters { + padding: 0 15px 0 10px; + box-shadow: 0 10px 20px black; + border-right: 1px solid; +} + +/* Gutter colors and line number styling based of color scheme (dark / light) */ + +/* Dark */ +.cm-s-solarized.cm-s-dark .CodeMirror-gutters { + background-color: #073642; + border-color: #00232c; +} + +.cm-s-solarized.cm-s-dark .CodeMirror-linenumber { + text-shadow: #021014 0 -1px; +} + +/* Light */ +.cm-s-solarized.cm-s-light .CodeMirror-gutters { + background-color: #eee8d5; + border-color: #eee8d5; +} + +/* Common */ +.cm-s-solarized .CodeMirror-linenumber { + color: #586e75; +} + +.cm-s-solarized .CodeMirror-gutter .CodeMirror-gutter-text { + color: #586e75; +} + +.cm-s-solarized .CodeMirror-lines { + padding-left: 5px; +} + +.cm-s-solarized .CodeMirror-lines .CodeMirror-cursor { + border-left: 1px solid #819090; +} + +/* +Active line. Negative margin compensates left padding of the text in the +view-port +*/ +.cm-s-solarized .activeline { + margin-left: -20px; +} + +.cm-s-solarized.cm-s-dark .activeline { + background: rgba(255, 255, 255, 0.05); + +} +.cm-s-solarized.cm-s-light .activeline { + background: rgba(0, 0, 0, 0.05); +} + +/* +View-port and gutter both get little noise background to give it a real feel. +*/ +.cm-s-solarized.CodeMirror, +.cm-s-solarized .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"); +} diff --git a/lib/codemirror-3.1/theme/twilight.css b/lib/codemirror-3.1/theme/twilight.css new file mode 100644 index 0000000000000000000000000000000000000000..fd8944ba8daeb613c7938a27ce1bd2376e41a16d --- /dev/null +++ b/lib/codemirror-3.1/theme/twilight.css @@ -0,0 +1,26 @@ +.cm-s-twilight.CodeMirror { background: #141414; color: #f7f7f7; } /**/ +.cm-s-twilight .CodeMirror-selected { background: #323232 !important; } /**/ + +.cm-s-twilight .CodeMirror-gutters { background: #222; border-right: 1px solid #aaa; } +.cm-s-twilight .CodeMirror-linenumber { color: #aaa; } +.cm-s-twilight .CodeMirror-cursor { border-left: 1px solid white !important; } + +.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 { 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-error { border-bottom: 1px solid red; } +.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; } /**/ + diff --git a/lib/codemirror-3.1/theme/vibrant-ink.css b/lib/codemirror-3.1/theme/vibrant-ink.css new file mode 100644 index 0000000000000000000000000000000000000000..22024a489a70246df6e20e91ecbb3296c234ba8f --- /dev/null +++ b/lib/codemirror-3.1/theme/vibrant-ink.css @@ -0,0 +1,27 @@ +/* Taken from the popular Visual Studio Vibrant Ink Schema */ + +.cm-s-vibrant-ink.CodeMirror { background: black; color: white; } +.cm-s-vibrant-ink .CodeMirror-selected { background: #35493c !important; } + +.cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; } +.cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; } +.cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white !important; } + +.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-cobalt span.cm-tag { color: #FFC66D } +.cm-s-vibrant-ink span.cm-variable-3, .cm-s-cobalt span.cm-def { 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-error { border-bottom: 1px solid red; } +.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; } diff --git a/lib/codemirror-3.1/theme/xq-dark.css b/lib/codemirror-3.1/theme/xq-dark.css new file mode 100644 index 0000000000000000000000000000000000000000..fd9bb12abc00c0e5500429b15ff46689d365e81b --- /dev/null +++ b/lib/codemirror-3.1/theme/xq-dark.css @@ -0,0 +1,46 @@ +/* +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 span.CodeMirror-selected { background: #a8f !important; } +.cm-s-xq-dark .CodeMirror-gutters { background: #0a001f; border-right: 1px solid #aaa; } +.cm-s-xq-dark .CodeMirror-linenumber { color: #f8f8f8; } +.cm-s-xq-dark .CodeMirror-cursor { border-left: 1px solid white !important; } + +.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 {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-error {color: #f00;} +.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;} diff --git a/lib/es5-shim.map b/lib/es5-shim.map new file mode 100644 index 0000000000000000000000000000000000000000..6cd93ffbb68fb9ebb1faf2c48e42418ab79734b0 --- /dev/null +++ b/lib/es5-shim.map @@ -0,0 +1,3 @@ + + +
    {"version": 3,"sources": ["es5-shim.js"],"names": ["definition","define","YUI","add","Empty","Function","prototype","bind","that","target","this","TypeError","args","_Array_slice_","call","arguments","binder","bound","result","apply","concat","Object","boundLength","Math","max","length","boundArgs","i","push","join","prototypeOfArray","Array","prototypeOfObject","slice","_toString","toString","owns","hasOwnProperty","defineGetter","defineSetter","lookupGetter","lookupSetter","supportsAccessors","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__","splice","array_splice","array_push","array_unshift","unshift","makeArray","l","a","array","lengthBefore","start","deleteCount","addElementsCount","isArray","obj","boxedString","splitString","boxedForEach","forEach","item","fun","object","toObject","self","split","thisp","map","filter","value","every","some","reduce","reduceRight","indexOf","sought","toInteger","lastIndexOf","min","abs","keys","hasDontEnumBug","dontEnums","dontEnumsLength","key","name","ii","dontEnum","negativeDate","negativeYearString","Date","toISOString","year","month","isFinite","RangeError","getUTCFullYear","getUTCMonth","floor","getUTCDate","getUTCHours","getUTCMinutes","getUTCSeconds","getUTCMilliseconds","dateToJSONIsSupported","toJSON","NaN","e","o","tv","toPrimitive","toISO","parse","NativeDate","Y","M","D","h","m","s","ms","date","String","constructor","isoDateExpression","RegExp","months","dayFromMonth","t","toUTC","Number","now","UTC","string","match","exec","day","hour","minute","second","millisecond","isLocalTime","Boolean","signOffset","hourOffset","minuteOffset","getTime","toFixed","base","size","data","multiply","n","c","divide","pow","x","acc","log","fractionDigits","f","z","j","k","string_split","compliantExecNpcg","separator","limit","output","flags","ignoreCase","multiline","extended","sticky","lastLastIndex","source","separator2","lastIndex","lastLength","index","replace","test","substr","string_substr","ws","trim","trimBeginRegexp","trimEndRegexp","isPrimitive","input","type","val","valueOf"],"mappings": "CAMA,SAAWA,YAEP,SAAWC,SAAU,WAAY,CAC7BA,OAAOD,gBAEJ,UAAWE,MAAO,WAAY,CACjCA,IAAIC,IAAI,MAAOH,gBAEZ,CACHA,gBAEL,WAmBH,QAASI,UAET,IAAKC,SAASC,UAAUC,KAAM,CAC1BF,SAASC,UAAUC,KAAO,QAASA,MAAKC,MAEpC,GAAIC,QAASC,IAEb,UAAWD,SAAU,WAAY,CAC7B,KAAM,IAAIE,WAAU,kDAAoDF,QAK5E,GAAIG,MAAOC,cAAcC,KAAKC,UAAW,EAUzC,IAAIC,QAAS,WAET,GAAIN,eAAgBO,OAAO,CAiBvB,GAAIC,QAAST,OAAOU,MAChBT,KACAE,KAAKQ,OAAOP,cAAcC,KAAKC,YAEnC,IAAIM,OAAOH,UAAYA,OAAQ,CAC3B,MAAOA,QAEX,MAAOR,UAEJ,CAoBH,MAAOD,QAAOU,MACVX,KACAI,KAAKQ,OAAOP,cAAcC,KAAKC,cAa3C,IAAIO,aAAcC,KAAKC,IAAI,EAAGf,OAAOgB,OAASb,KAAKa,OAInD,IAAIC,aACJ,KAAK,GAAIC,GAAI,EAAGA,EAAIL,YAAaK,IAAK,CAClCD,UAAUE,KAAK,IAAMD,GASzB,GAAIV,OAAQZ,SAAS,SAAU,mBAAqBqB,UAAUG,KAAK,KAAO,0CAA0Cb,OAEpH,IAAIP,OAAOH,UAAW,CAClBF,MAAME,UAAYG,OAAOH,SACzBW,OAAMX,UAAY,GAAIF,MAEtBA,OAAME,UAAY,KAwBtB,MAAOW,QAQf,GAAIH,MAAOT,SAASC,UAAUQ,IAC9B,IAAIgB,kBAAmBC,MAAMzB,SAC7B,IAAI0B,mBAAoBX,OAAOf,SAC/B,IAAIO,eAAgBiB,iBAAiBG,KAErC,IAAIC,WAAYpB,KAAKP,KAAKyB,kBAAkBG,SAC5C,IAAIC,MAAOtB,KAAKP,KAAKyB,kBAAkBK,eAGvC,IAAIC,aACJ,IAAIC,aACJ,IAAIC,aACJ,IAAIC,aACJ,IAAIC,kBACJ,IAAKA,kBAAoBN,KAAKJ,kBAAmB,oBAAsB,CACnEM,aAAexB,KAAKP,KAAKyB,kBAAkBW,iBAC3CJ,cAAezB,KAAKP,KAAKyB,kBAAkBY,iBAC3CJ,cAAe1B,KAAKP,KAAKyB,kBAAkBa,iBAC3CJ,cAAe3B,KAAKP,KAAKyB,kBAAkBc,kBAa/C,IAAK,EAAE,GAAGC,OAAO,GAAGtB,QAAU,EAAG,CAC7B,GAAIuB,cAAejB,MAAMzB,UAAUyC,MACnC,IAAIE,YAAalB,MAAMzB,UAAUsB,IACjC,IAAIsB,eAAgBnB,MAAMzB,UAAU6C,OAEpC,IAAI,WACA,QAASC,WAAUC,GACf,GAAIC,KACJ,OAAOD,IAAK,CACRC,EAAEH,QAAQE,GAEd,MAAOC,GAGX,GAAIC,UACEC,YAGND,OAAMR,OAAOxC,KAAKgD,MAAO,EAAG,GAAGpC,MAAM,KAAMiC,UAAU,IACrDG,OAAMR,OAAOxC,KAAKgD,MAAO,EAAG,GAAGpC,MAAM,KAAMiC,UAAU,IAErDI,cAAeD,MAAM9B,MACrB8B,OAAMR,OAAO,EAAG,EAAG,MAEnB,IAAIS,aAAe,GAAKD,MAAM9B,OAAQ,CAClC,MAAO,UAKV,CACDM,MAAMzB,UAAUyC,OAAS,SAASU,MAAOC,aACrC,IAAK3C,UAAUU,OAAQ,CACnB,aACG,CACH,MAAOuB,cAAa7B,MAAMT,MACtB+C,YAAe,GAAI,EAAIA,MACvBC,kBAAqB,GAAKhD,KAAKe,OAASgC,MAASC,aACnDtC,OAAOP,cAAcC,KAAKC,UAAW,WAI9C,CACDgB,MAAMzB,UAAUyC,OAAS,SAASU,MAAOC,aACrC,GAAIxC,QACEN,KAAOC,cAAcC,KAAKC,UAAW,GACrC4C,iBAAmB/C,KAAKa,MAG9B,KAAKV,UAAUU,OAAQ,CACnB,SAGJ,GAAIgC,YAAe,GAAG,CAClBA,MAAQ,EAEZ,GAAIC,kBAAqB,GAAG,CACxBA,YAAchD,KAAKe,OAASgC,MAGhC,GAAIE,iBAAmB,EAAG,CACtB,GAAID,aAAe,EAAG,CAClB,GAAID,OAAS/C,KAAKe,OAAQ,CACtBwB,WAAW9B,MAAMT,KAAME,KACvB,UAGJ,GAAI6C,OAAS,EAAG,CACZP,cAAc/B,MAAMT,KAAME,KAC1B,WAKRM,OAASL,cAAcC,KAAKJ,KAAM+C,MAAOA,MAAQC,YACjD9C,MAAKgB,KAAKT,MAAMP,KAAMC,cAAcC,KAAKJ,KAAM+C,MAAQC,YAAahD,KAAKe,QACzEb,MAAKuC,QAAQhC,MAAMP,KAAMC,cAAcC,KAAKJ,KAAM,EAAG+C,OAGrD7C,MAAKuC,QAAQ,EAAGzC,KAAKe,OAErBuB,cAAa7B,MAAMT,KAAME,KAEzB,OAAOM,QAGX,MAAO8B,cAAalC,KAAKJ,KAAM+C,MAAOC,eAWlD,MAAOP,QAAQ,IAAM,EAAG,CACpB,GAAID,eAAgBnB,MAAMzB,UAAU6C,OACpCpB,OAAMzB,UAAU6C,QAAU,WACtBD,cAAc/B,MAAMT,KAAMK,UAC1B,OAAOL,MAAKe,QAOpB,IAAKM,MAAM6B,QAAS,CAChB7B,MAAM6B,QAAU,QAASA,SAAQC,KAC7B,MAAO3B,WAAU2B,MAAQ,kBAsBjC,GAAIC,aAAczC,OAAO,KACrB0C,YAAcD,YAAY,IAAM,OAAS,IAAKA,aAElD,IAAIE,cAAe,IACnB,IAAIjC,MAAMzB,UAAU2D,QAAS,CACzBlC,MAAMzB,UAAU2D,QAAQnD,KAAK,MAAO,SAASoD,KAAMvC,EAAGkC,KAClD,SAAWA,OAAQ,SAAUG,aAAe,QAIpD,IAAKjC,MAAMzB,UAAU2D,UAAYD,aAAc,CAC3CjC,MAAMzB,UAAU2D,QAAU,QAASA,SAAQE,KACvC,GAAIC,QAASC,SAAS3D,MAClB4D,KAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXH,OACJI,MAAQzD,UAAU,GAClBY,GAAK,EACLF,OAAS6C,KAAK7C,SAAW,CAG7B,IAAIS,UAAUiC,MAAQ,oBAAqB,CACvC,KAAM,IAAIxD,WAGd,QAASgB,EAAIF,OAAQ,CACjB,GAAIE,IAAK2C,MAAM,CAIXH,IAAIrD,KAAK0D,MAAOF,KAAK3C,GAAIA,EAAGyC,WAS5C,IAAKrC,MAAMzB,UAAUmE,IAAK,CACtB1C,MAAMzB,UAAUmE,IAAM,QAASA,KAAIN,KAC/B,GAAIC,QAASC,SAAS3D,MAClB4D,KAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXH,OACJ3C,OAAS6C,KAAK7C,SAAW,EACzBP,OAASa,MAAMN,QACf+C,MAAQzD,UAAU,EAGtB,IAAImB,UAAUiC,MAAQ,oBAAqB,CACvC,KAAM,IAAIxD,WAAUwD,IAAM,sBAG9B,IAAK,GAAIxC,GAAI,EAAGA,EAAIF,OAAQE,IAAK,CAC7B,GAAIA,IAAK2C,MACLpD,OAAOS,GAAKwC,IAAIrD,KAAK0D,MAAOF,KAAK3C,GAAIA,EAAGyC,QAEhD,MAAOlD,SAOf,IAAKa,MAAMzB,UAAUoE,OAAQ,CACzB3C,MAAMzB,UAAUoE,OAAS,QAASA,QAAOP,KACrC,GAAIC,QAASC,SAAS3D,MAClB4D,KAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACPH,OACR3C,OAAS6C,KAAK7C,SAAW,EACzBP,UACAyD,MACAH,MAAQzD,UAAU,EAGtB,IAAImB,UAAUiC,MAAQ,oBAAqB,CACvC,KAAM,IAAIxD,WAAUwD,IAAM,sBAG9B,IAAK,GAAIxC,GAAI,EAAGA,EAAIF,OAAQE,IAAK,CAC7B,GAAIA,IAAK2C,MAAM,CACXK,MAAQL,KAAK3C,EACb,IAAIwC,IAAIrD,KAAK0D,MAAOG,MAAOhD,EAAGyC,QAAS,CACnClD,OAAOU,KAAK+C,SAIxB,MAAOzD,SAOf,IAAKa,MAAMzB,UAAUsE,MAAO,CACxB7C,MAAMzB,UAAUsE,MAAQ,QAASA,OAAMT,KACnC,GAAIC,QAASC,SAAS3D,MAClB4D,KAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXH,OACJ3C,OAAS6C,KAAK7C,SAAW,EACzB+C,MAAQzD,UAAU,EAGtB,IAAImB,UAAUiC,MAAQ,oBAAqB,CACvC,KAAM,IAAIxD,WAAUwD,IAAM,sBAG9B,IAAK,GAAIxC,GAAI,EAAGA,EAAIF,OAAQE,IAAK,CAC7B,GAAIA,IAAK2C,QAASH,IAAIrD,KAAK0D,MAAOF,KAAK3C,GAAIA,EAAGyC,QAAS,CACnD,MAAO,QAGf,MAAO,OAOf,IAAKrC,MAAMzB,UAAUuE,KAAM,CACvB9C,MAAMzB,UAAUuE,KAAO,QAASA,MAAKV,KACjC,GAAIC,QAASC,SAAS3D,MAClB4D,KAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXH,OACJ3C,OAAS6C,KAAK7C,SAAW,EACzB+C,MAAQzD,UAAU,EAGtB,IAAImB,UAAUiC,MAAQ,oBAAqB,CACvC,KAAM,IAAIxD,WAAUwD,IAAM,sBAG9B,IAAK,GAAIxC,GAAI,EAAGA,EAAIF,OAAQE,IAAK,CAC7B,GAAIA,IAAK2C,OAAQH,IAAIrD,KAAK0D,MAAOF,KAAK3C,GAAIA,EAAGyC,QAAS,CAClD,MAAO,OAGf,MAAO,QAOf,IAAKrC,MAAMzB,UAAUwE,OAAQ,CACzB/C,MAAMzB,UAAUwE,OAAS,QAASA,QAAOX,KACrC,GAAIC,QAASC,SAAS3D,MAClB4D,KAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXH,OACJ3C,OAAS6C,KAAK7C,SAAW,CAG7B,IAAIS,UAAUiC,MAAQ,oBAAqB,CACvC,KAAM,IAAIxD,WAAUwD,IAAM,sBAI9B,IAAK1C,QAAUV,UAAUU,QAAU,EAAG,CAClC,KAAM,IAAId,WAAU,+CAGxB,GAAIgB,GAAI,CACR,IAAIT,OACJ,IAAIH,UAAUU,QAAU,EAAG,CACvBP,OAASH,UAAU,OAChB,CACH,EAAG,CACC,GAAIY,IAAK2C,MAAM,CACXpD,OAASoD,KAAK3C,IACd,OAIJ,KAAMA,GAAKF,OAAQ,CACf,KAAM,IAAId,WAAU,sDAEnB,MAGb,KAAOgB,EAAIF,OAAQE,IAAK,CACpB,GAAIA,IAAK2C,MAAM,CACXpD,OAASiD,IAAIrD,SAAU,GAAGI,OAAQoD,KAAK3C,GAAIA,EAAGyC,SAItD,MAAOlD,SAOf,IAAKa,MAAMzB,UAAUyE,YAAa,CAC9BhD,MAAMzB,UAAUyE,YAAc,QAASA,aAAYZ,KAC/C,GAAIC,QAASC,SAAS3D,MAClB4D,KAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXH,OACJ3C,OAAS6C,KAAK7C,SAAW,CAG7B,IAAIS,UAAUiC,MAAQ,oBAAqB,CACvC,KAAM,IAAIxD,WAAUwD,IAAM,sBAI9B,IAAK1C,QAAUV,UAAUU,QAAU,EAAG,CAClC,KAAM,IAAId,WAAU,oDAGxB,GAAIO,QAAQS,EAAIF,OAAS,CACzB,IAAIV,UAAUU,QAAU,EAAG,CACvBP,OAASH,UAAU,OAChB,CACH,EAAG,CACC,GAAIY,IAAK2C,MAAM,CACXpD,OAASoD,KAAK3C,IACd,OAIJ,KAAMA,EAAI,EAAG,CACT,KAAM,IAAIhB,WAAU,2DAEnB,MAGb,GAAIgB,EAAI,EAAG,CACP,MAAOT,QAGX,EAAG,CACC,GAAIS,IAAKjB,MAAM,CACXQ,OAASiD,IAAIrD,SAAU,GAAGI,OAAQoD,KAAK3C,GAAIA,EAAGyC,eAE7CzC,IAET,OAAOT,SAOf,IAAKa,MAAMzB,UAAU0E,UAAa,EAAG,GAAGA,QAAQ,EAAG,KAAO,EAAI,CAC1DjD,MAAMzB,UAAU0E,QAAU,QAASA,SAAQC,QACvC,GAAIX,MAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXF,SAAS3D,MACbe,OAAS6C,KAAK7C,SAAW,CAE7B,KAAKA,OAAQ,CACT,OAAQ,EAGZ,GAAIE,GAAI,CACR,IAAIZ,UAAUU,OAAS,EAAG,CACtBE,EAAIuD,UAAUnE,UAAU,IAI5BY,EAAIA,GAAK,EAAIA,EAAIJ,KAAKC,IAAI,EAAGC,OAASE,EACtC,MAAOA,EAAIF,OAAQE,IAAK,CACpB,GAAIA,IAAK2C,OAAQA,KAAK3C,KAAOsD,OAAQ,CACjC,MAAOtD,IAGf,OAAQ,GAOhB,IAAKI,MAAMzB,UAAU6E,cAAiB,EAAG,GAAGA,YAAY,GAAI,KAAO,EAAI,CACnEpD,MAAMzB,UAAU6E,YAAc,QAASA,aAAYF,QAC/C,GAAIX,MAAOP,aAAe7B,UAAUxB,OAAS,kBACrCA,KAAK6D,MAAM,IACXF,SAAS3D,MACbe,OAAS6C,KAAK7C,SAAW,CAE7B,KAAKA,OAAQ,CACT,OAAQ,EAEZ,GAAIE,GAAIF,OAAS,CACjB,IAAIV,UAAUU,OAAS,EAAG,CACtBE,EAAIJ,KAAK6D,IAAIzD,EAAGuD,UAAUnE,UAAU,KAGxCY,EAAIA,GAAK,EAAIA,EAAIF,OAASF,KAAK8D,IAAI1D,EACnC,MAAOA,GAAK,EAAGA,IAAK,CAChB,GAAIA,IAAK2C,OAAQW,SAAWX,KAAK3C,GAAI,CACjC,MAAOA,IAGf,OAAQ,GAWhB,IAAKN,OAAOiE,KAAM,CAEd,GAAIC,gBAAiB,KACjBC,WACI,WACA,iBACA,UACA,iBACA,gBACA,uBACA,eAEJC,gBAAkBD,UAAU/D,MAEhC,KAAK,GAAIiE,QAAQvD,SAAY,MAAO,CAChCoD,eAAiB,MAGrBlE,OAAOiE,KAAO,QAASA,MAAKlB,QAExB,SACYA,SAAU,gBAAmBA,SAAU,YAC/CA,SAAW,KACb,CACE,KAAM,IAAIzD,WAAU,sCAGxB,GAAI2E,QACJ,KAAK,GAAIK,QAAQvB,QAAQ,CACrB,GAAIhC,KAAKgC,OAAQuB,MAAO,CACpBL,KAAK1D,KAAK+D,OAIlB,GAAIJ,eAAgB,CAChB,IAAK,GAAI5D,GAAI,EAAGiE,GAAKH,gBAAiB9D,EAAIiE,GAAIjE,IAAK,CAC/C,GAAIkE,UAAWL,UAAU7D,EACzB,IAAIS,KAAKgC,OAAQyB,UAAW,CACxBP,KAAK1D,KAAKiE,YAItB,MAAOP,OAiBf,GAAIQ,eAAgB,YAChBC,mBAAqB,SACzB,KACKC,KAAK1F,UAAU2F,aACf,GAAID,MAAKF,cAAcG,cAAcjB,QAAQe,uBAAyB,EACzE,CACEC,KAAK1F,UAAU2F,YAAc,QAASA,eAClC,GAAI/E,QAAQO,OAAQkD,MAAOuB,KAAMC,KACjC,KAAKC,SAAS1F,MAAO,CACjB,KAAM,IAAI2F,YAAW,0DAGzBH,KAAOxF,KAAK4F,gBAEZH,OAAQzF,KAAK6F,aAEbL,OAAQ3E,KAAKiF,MAAML,MAAQ,GAC3BA,QAASA,MAAQ,GAAK,IAAM,EAG5BjF,SAAUiF,MAAQ,EAAGzF,KAAK+F,aACtB/F,KAAKgG,cAAehG,KAAKiG,gBAAiBjG,KAAKkG,gBACnDV,OACKA,KAAO,EAAI,IAAOA,KAAO,KAAO,IAAM,KACtC,QAAU3E,KAAK8D,IAAIa,OACnBjE,MAAM,GAAKiE,MAAQA,MAAQ,MAAQ,GAAK,EAG7CzE,QAASP,OAAOO,MAChB,OAAOA,SAAU,CACbkD,MAAQzD,OAAOO,OAGf,IAAIkD,MAAQ,GAAI,CACZzD,OAAOO,QAAU,IAAMkD,OAI/B,MACIuB,MAAO,IAAMhF,OAAOe,MAAM,EAAG,GAAGJ,KAAK,KACrC,IAAMX,OAAOe,MAAM,GAAGJ,KAAK,KAAO,KACjC,MAAQnB,KAAKmG,sBAAsB5E,OAAO,GAAK,KAU5D,GAAI6E,uBAAwB,KAC5B,KACIA,sBACId,KAAK1F,UAAUyG,QACf,GAAIf,MAAKgB,KAAKD,WAAa,MAC3B,GAAIf,MAAKF,cAAciB,SAAS/B,QAAQe,uBAAyB,GACjEC,KAAK1F,UAAUyG,OAAOjG,MAClBmF,YAAa,WACT,MAAO,SAIrB,MAAOgB,IAET,IAAKH,sBAAuB,CACxBd,KAAK1F,UAAUyG,OAAS,QAASA,QAAOrB,KAOpC,GAAIwB,GAAI7F,OAAOX,MACXyG,GAAKC,YAAYF,GACjBG,KAEJ,UAAWF,MAAO,WAAaf,SAASe,IAAK,CACzC,MAAO,MAIXE,MAAQH,EAAEjB,WAEV,UAAWoB,QAAS,WAAY,CAC5B,KAAM,IAAI1G,WAAU,wCAIxB,MAAO0G,OAAMvG,KAAKoG,IAiB1B,IAAKlB,KAAKsB,OAAS,sBAAuB,CAGtCtB,KAAO,SAAUuB,YAGb,QAASvB,MAAKwB,EAAGC,EAAGC,EAAGC,EAAGC,EAAGC,EAAGC,IAC5B,GAAIrG,QAASV,UAAUU,MACvB,IAAIf,eAAgB6G,YAAY,CAC5B,GAAIQ,MAAOtG,QAAU,GAAKuG,OAAOR,KAAOA,EAEpC,GAAID,YAAWvB,KAAKsB,MAAME,IAG1B/F,QAAU,EAAI,GAAI8F,YAAWC,EAAGC,EAAGC,EAAGC,EAAGC,EAAGC,EAAGC,IAC/CrG,QAAU,EAAI,GAAI8F,YAAWC,EAAGC,EAAGC,EAAGC,EAAGC,EAAGC,GAC5CpG,QAAU,EAAI,GAAI8F,YAAWC,EAAGC,EAAGC,EAAGC,EAAGC,GACzCnG,QAAU,EAAI,GAAI8F,YAAWC,EAAGC,EAAGC,EAAGC,GACtClG,QAAU,EAAI,GAAI8F,YAAWC,EAAGC,EAAGC,GACnCjG,QAAU,EAAI,GAAI8F,YAAWC,EAAGC,GAChChG,QAAU,EAAI,GAAI8F,YAAWC,GACf,GAAID,WAEtBQ,MAAKE,YAAcjC,IACnB,OAAO+B,MAEX,MAAOR,YAAWpG,MAAMT,KAAMK,WAIlC,GAAImH,mBAAoB,GAAIC,QAAO,IAC/B,sBAEA,eACA,eACA,MACI,YACA,YACA,MACI,YACA,oBACJ,KACJ,IACI,KACA,MACI,SACA,WACA,YACJ,IACJ,WACJ,IAEA,IAAIC,SACA,EAAG,GAAI,GAAI,GAAI,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAG3D,SAASC,cAAanC,KAAMC,OACxB,GAAImC,GAAInC,MAAQ,EAAI,EAAI,CACxB,OACIiC,QAAOjC,OACP5E,KAAKiF,OAAON,KAAO,KAAOoC,GAAK,GAC/B/G,KAAKiF,OAAON,KAAO,KAAOoC,GAAK,KAC/B/G,KAAKiF,OAAON,KAAO,KAAOoC,GAAK,KAC/B,KAAOpC,KAAO,MAItB,QAASqC,OAAMD,GACX,MAAOE,QAAO,GAAIjB,YAAW,KAAM,EAAG,EAAG,EAAG,EAAG,EAAGe,IAItD,IAAK,GAAI5C,OAAO6B,YAAY,CACxBvB,KAAKN,KAAO6B,WAAW7B,KAI3BM,KAAKyC,IAAMlB,WAAWkB,GACtBzC,MAAK0C,IAAMnB,WAAWmB,GACtB1C,MAAK1F,UAAYiH,WAAWjH,SAC5B0F,MAAK1F,UAAU2H,YAAcjC,IAG7BA,MAAKsB,MAAQ,QAASA,OAAMqB,QACxB,GAAIC,OAAQV,kBAAkBW,KAAKF,OACnC,IAAIC,MAAO,CAIP,GAAI1C,MAAOsC,OAAOI,MAAM,IACpBzC,MAAQqC,OAAOI,MAAM,IAAM,GAAK,EAChCE,IAAMN,OAAOI,MAAM,IAAM,GAAK,EAC9BG,KAAOP,OAAOI,MAAM,IAAM,GAC1BI,OAASR,OAAOI,MAAM,IAAM,GAC5BK,OAAST,OAAOI,MAAM,IAAM,GAC5BM,YAAc3H,KAAKiF,MAAMgC,OAAOI,MAAM,IAAM,GAAK,KAIjDO,YAAcC,QAAQR,MAAM,KAAOA,MAAM,IACzCS,WAAaT,MAAM,KAAO,IAAM,GAAK,EACrCU,WAAad,OAAOI,MAAM,KAAO,GACjCW,aAAef,OAAOI,MAAM,KAAO,GACnC1H,MACJ,IACI6H,MACIC,OAAS,GAAKC,OAAS,GAAKC,YAAc,EAC1C,GAAK,KAETF,OAAS,IAAMC,OAAS,IAAMC,YAAc,KAC5C/C,OAAS,GAAKA,MAAQ,IAAMmD,WAAa,IACzCC,aAAe,IACfT,KAAO,GACPA,IACIT,aAAanC,KAAMC,MAAQ,GAC3BkC,aAAanC,KAAMC,OAEzB,CACEjF,SACKmH,aAAanC,KAAMC,OAAS2C,KAAO,GACpCC,KACAO,WAAaD,YACb,EACJnI,UACKA,OAAS8H,OAASO,aAAeF,YAAc,GAChDJ,QACA,IAAOC,WACX,IAAIC,YAAa,CACbjI,OAASqH,MAAMrH,QAEnB,IAAK,QAAWA,QAAUA,QAAU,OAAS,CACzC,MAAOA,SAGf,MAAO8F,KAEX,MAAOO,YAAWD,MAAMnG,MAAMT,KAAMK,WAGxC,OAAOiF,OACRA,MAKP,IAAKA,KAAKyC,IAAK,CACXzC,KAAKyC,IAAM,QAASA,OAChB,OAAO,GAAIzC,OAAOwD,WAY1B,IAAKhB,OAAOlI,UAAUmJ,SAAW,KAAUA,QAAQ,KAAO,SAAW,GAAMA,QAAQ,KAAO,KAAO,MAAQA,QAAQ,KAAO,QAAU,kBAAsBA,QAAQ,KAAO,sBAAuB,EAEzL,WACG,GAAIC,MAAMC,KAAMC,KAAMjI,CAEtB+H,MAAO,GACPC,MAAO,CACPC,OAAQ,EAAG,EAAG,EAAG,EAAG,EAAG,EAEvB,SAASC,UAASC,EAAGC,GACjB,GAAIpI,IAAK,CACT,SAASA,EAAIgI,KAAM,CACfI,GAAKD,EAAIF,KAAKjI,EACdiI,MAAKjI,GAAKoI,EAAIL,IACdK,GAAIxI,KAAKiF,MAAMuD,EAAIL,OAI3B,QAASM,QAAOF,GACZ,GAAInI,GAAIgI,KAAMI,EAAI,CAClB,SAASpI,GAAK,EAAG,CACboI,GAAKH,KAAKjI,EACViI,MAAKjI,GAAKJ,KAAKiF,MAAMuD,EAAID,EACzBC,GAAKA,EAAID,EAAKJ,MAItB,QAASvH,YACL,GAAIR,GAAIgI,IACR,IAAI9B,GAAI,EACR,SAASlG,GAAK,EAAG,CACb,GAAIkG,IAAM,IAAMlG,IAAM,GAAKiI,KAAKjI,KAAO,EAAG,CACtC,GAAI2G,GAAIN,OAAO4B,KAAKjI,GACpB,IAAIkG,IAAM,GAAI,CACVA,EAAIS,MACD,CACHT,GAAK,UAAU5F,MAAM,EAAG,EAAIqG,EAAE7G,QAAU6G,IAIpD,MAAOT,GAGX,QAASoC,KAAIC,EAAGJ,EAAGK,KACf,MAAQL,KAAM,EAAIK,IAAOL,EAAI,IAAM,EAAIG,IAAIC,EAAGJ,EAAI,EAAGK,IAAMD,GAAKD,IAAIC,EAAIA,EAAGJ,EAAI,EAAGK,KAGtF,QAASC,KAAIF,GACT,GAAIJ,GAAI,CACR,OAAOI,GAAK,KAAM,CACdJ,GAAK,EACLI,IAAK,KAET,MAAOA,GAAK,EAAG,CACXJ,GAAK,CACLI,IAAK,EAET,MAAOJ,GAGXtB,OAAOlI,UAAUmJ,QAAU,SAAUY,gBACjC,GAAIC,GAAGJ,EAAGrC,EAAGD,EAAGX,EAAGsD,EAAGC,EAAGC,CAGzBH,GAAI9B,OAAO6B,eACXC,GAAIA,IAAMA,EAAI,EAAI/I,KAAKiF,MAAM8D,EAE7B,IAAIA,EAAI,GAAKA,EAAI,GAAI,CACjB,KAAM,IAAIjE,YAAW,yDAGzB6D,EAAI1B,OAAO9H,KAGX,IAAIwJ,IAAMA,EAAG,CACT,MAAO,MAIX,GAAIA,IAAM,MAAQA,GAAK,KAAM,CACzB,MAAOlC,QAAOkC,GAGlBrC,EAAI,EAEJ,IAAIqC,EAAI,EAAG,CACPrC,EAAI,GACJqC,IAAKA,EAGTtC,EAAI,GAEJ,IAAIsC,EAAI,MAAO,CAGXjD,EAAImD,IAAIF,EAAID,IAAI,EAAG,GAAI,IAAM,EAC7BM,GAAKtD,EAAI,EAAIiD,EAAID,IAAI,GAAIhD,EAAG,GAAKiD,EAAID,IAAI,EAAGhD,EAAG,EAC/CsD,IAAK,gBACLtD,GAAI,GAAKA,CAIT,IAAIA,EAAI,EAAG,CACP4C,SAAS,EAAGU,EACZC,GAAIF,CAEJ,OAAOE,GAAK,EAAG,CACXX,SAAS,IAAK,EACdW,IAAK,EAGTX,SAASI,IAAI,GAAIO,EAAG,GAAI,EACxBA,GAAIvD,EAAI,CAER,OAAOuD,GAAK,GAAI,CACZR,OAAO,GAAK,GACZQ,IAAK,GAGTR,OAAO,GAAKQ,EACZX,UAAS,EAAG,EACZG,QAAO,EACPpC,GAAIzF,eACD,CACH0H,SAAS,EAAGU,EACZV,UAAS,IAAO5C,EAAI,EACpBW,GAAIzF,WAAa,yBAAyBF,MAAM,EAAG,EAAIqI,IAI/D,GAAIA,EAAI,EAAG,CACPG,EAAI7C,EAAEnG,MAEN,IAAIgJ,GAAKH,EAAG,CACR1C,EAAIC,EAAI,wBAAwB5F,MAAM,EAAGqI,EAAIG,EAAI,GAAK7C,MACnD,CACHA,EAAIC,EAAID,EAAE3F,MAAM,EAAGwI,EAAIH,GAAK,IAAM1C,EAAE3F,MAAMwI,EAAIH,QAE/C,CACH1C,EAAIC,EAAID,EAGZ,MAAOA,QA2BnB,GAAI8C,cAAe1C,OAAO1H,UAAUiE,KACpC,IACI,KAAKA,MAAM,WAAW9C,SAAW,GACjC,IAAI8C,MAAM,YAAY9C,SAAW,GACjC,QAAQ8C,MAAM,QAAQ,KAAO,KAC7B,GAAGA,MAAM,MAAM9C,QACf,IAAI8C,MAAM,QAAQ9C,OAAS,EAC7B,EACG,WACG,GAAIkJ,mBAAoB,OAAO9B,KAAK,IAAI,SAAY,EAEpDb,QAAO1H,UAAUiE,MAAQ,SAAUqG,UAAWC,OAC1C,GAAIlC,QAASjI,IACb,IAAIkK,gBAAmB,IAAKC,QAAU,EAClC,QAGJ,IAAIxJ,OAAOf,UAAU6B,SAASrB,KAAK8J,aAAe,kBAAmB,CACjE,MAAOF,cAAavJ,MAAMT,KAAMK,WAGpC,GAAI+J,WACAC,OAASH,UAAUI,WAAa,IAAM,KAC7BJ,UAAUK,UAAa,IAAM,KAC7BL,UAAUM,SAAa,IAAM,KAC7BN,UAAUO,OAAa,IAAM,IACtCC,cAAgB,EAEhBR,UAAY,GAAIzC,QAAOyC,UAAUS,OAAQN,MAAQ,KACjDO,WAAY1C,MAAO2C,UAAWC,UAClC7C,SAAU,EACV,KAAKgC,kBAAmB,CAEpBW,WAAa,GAAInD,QAAO,IAAMyC,UAAUS,OAAS,WAAYN,OASjEF,MAAQA,YAAe,IAClB,IAAM,EACPA,QAAU,CACd,OAAOjC,MAAQgC,UAAU/B,KAAKF,QAAS,CAEnC4C,UAAY3C,MAAM6C,MAAQ7C,MAAM,GAAGnH,MACnC,IAAI8J,UAAYH,cAAe,CAC3BN,OAAOlJ,KAAK+G,OAAO1G,MAAMmJ,cAAexC,MAAM6C,OAG9C,KAAKd,mBAAqB/B,MAAMnH,OAAS,EAAG,CACxCmH,MAAM,GAAG8C,QAAQJ,WAAY,WACzB,IAAK,GAAI3J,GAAI,EAAGA,EAAIZ,UAAUU,OAAS,EAAGE,IAAK,CAC3C,GAAIZ,UAAUY,SAAY,GAAG,CACzBiH,MAAMjH,OAAU,OAKhC,GAAIiH,MAAMnH,OAAS,GAAKmH,MAAM6C,MAAQ9C,OAAOlH,OAAQ,CACjDM,MAAMzB,UAAUsB,KAAKT,MAAM2J,OAAQlC,MAAM3G,MAAM,IAEnDuJ,WAAa5C,MAAM,GAAGnH,MACtB2J,eAAgBG,SAChB,IAAIT,OAAOrJ,QAAUoJ,MAAO,CACxB,OAGR,GAAID,UAAUW,YAAc3C,MAAM6C,MAAO,CACrCb,UAAUW,aAGlB,GAAIH,gBAAkBzC,OAAOlH,OAAQ,CACjC,GAAI+J,aAAeZ,UAAUe,KAAK,IAAK,CACnCb,OAAOlJ,KAAK,SAEb,CACHkJ,OAAOlJ,KAAK+G,OAAO1G,MAAMmJ,gBAE7B,MAAON,QAAOrJ,OAASoJ,MAAQC,OAAO7I,MAAM,EAAG4I,OAASC,gBAU7D,IAAI,IAAIvG,UAAW,GAAG,GAAG9C,OAAQ,CACpCuG,OAAO1H,UAAUiE,MAAQ,SAASqG,UAAWC,OACzC,GAAID,gBAAmB,IAAKC,QAAU,EAAG,QACzC,OAAOH,cAAavJ,MAAMT,KAAMK,YAUxC,GAAI,GAAG6K,QAAU,KAAKA,QAAQ,KAAO,IAAK,CACtC,GAAIC,eAAgB7D,OAAO1H,UAAUsL,MAOrC5D,QAAO1H,UAAUsL,OAAS,SAASnI,MAAOhC,QACtC,MAAOoK,eAAc/K,KACjBJ,KACA+C,MAAQ,GAAMA,MAAQ/C,KAAKe,OAASgC,OAAS,EAAI,EAAIA,MAASA,MAC9DhC,SAOZ,GAAIqK,IAAK,oDACL,qEACA,cACJ,KAAK9D,OAAO1H,UAAUyL,MAAQD,GAAGC,OAAQ,CAGrCD,GAAK,IAAMA,GAAK,GAChB,IAAIE,iBAAkB,GAAI7D,QAAO,IAAM2D,GAAKA,GAAK,KAC7CG,cAAgB,GAAI9D,QAAO2D,GAAKA,GAAK,KACzC9D,QAAO1H,UAAUyL,KAAO,QAASA,QAC7B,GAAIrL,WAAc,IAAKA,OAAS,KAAM,CAClC,KAAM,IAAIC,WAAU,iBAAiBD,KAAK,cAE9C,MAAOsH,QAAOtH,MACTgL,QAAQM,gBAAiB,IACzBN,QAAQO,cAAe,KAapC,QAAS/G,WAAU4E,GACfA,GAAKA,CACL,IAAIA,IAAMA,EAAG,CACTA,EAAI,MACD,IAAIA,IAAM,GAAKA,IAAO,EAAE,GAAMA,MAAQ,EAAE,GAAI,CAC/CA,GAAKA,EAAI,IAAM,GAAKvI,KAAKiF,MAAMjF,KAAK8D,IAAIyE,IAE5C,MAAOA,GAGX,QAASoC,aAAYC,OACjB,GAAIC,YAAcD,MAClB,OACIA,SAAU,MACVC,OAAS,aACTA,OAAS,WACTA,OAAS,UACTA,OAAS,SAIjB,QAAShF,aAAY+E,OACjB,GAAIE,KAAKC,QAASnK,QAClB,IAAI+J,YAAYC,OAAQ,CACpB,MAAOA,OAEXG,QAAUH,MAAMG,OAChB,UAAWA,WAAY,WAAY,CAC/BD,IAAMC,QAAQxL,KAAKqL,MACnB,IAAID,YAAYG,KAAM,CAClB,MAAOA,MAGflK,SAAWgK,MAAMhK,QACjB,UAAWA,YAAa,WAAY,CAChCkK,IAAMlK,SAASrB,KAAKqL,MACpB,IAAID,YAAYG,KAAM,CAClB,MAAOA,MAGf,KAAM,IAAI1L,WAKd,GAAI0D,UAAW,SAAU6C,GACrB,GAAIA,GAAK,KAAM,CACX,KAAM,IAAIvG,WAAU,iBAAiBuG,EAAE,cAE3C,MAAO7F,QAAO6F"}
    \ No newline at end of file diff --git a/lib/es5-shim.min.js b/lib/es5-shim.min.js new file mode 100644 index 0000000000000000000000000000000000000000..db8fb3e6d1133068f38c2cffa85be0abeb85bcfb --- /dev/null +++ b/lib/es5-shim.min.js @@ -0,0 +1,2 @@ +(function(definition){if(typeof define=="function"){define(definition)}else if(typeof YUI=="function"){YUI.add("es5",definition)}else{definition()}})(function(){function Empty(){}if(!Function.prototype.bind){Function.prototype.bind=function bind(that){var target=this;if(typeof target!="function"){throw new TypeError("Function.prototype.bind called on incompatible "+target)}var args=_Array_slice_.call(arguments,1);var binder=function(){if(this instanceof bound){var result=target.apply(this,args.concat(_Array_slice_.call(arguments)));if(Object(result)===result){return result}return this}else{return target.apply(that,args.concat(_Array_slice_.call(arguments)))}};var boundLength=Math.max(0,target.length-args.length);var boundArgs=[];for(var i=0;i0){if(deleteCount<=0){if(start==this.length){array_push.apply(this,args);return[]}if(start==0){array_unshift.apply(this,args);return[]}}result=_Array_slice_.call(this,start,start+deleteCount);args.push.apply(args,_Array_slice_.call(this,start+deleteCount,this.length));args.unshift.apply(args,_Array_slice_.call(this,0,start));args.unshift(0,this.length);array_splice.apply(this,args);return result}return array_splice.call(this,start,deleteCount)}}}if([].unshift(0)!=1){var array_unshift=Array.prototype.unshift;Array.prototype.unshift=function(){array_unshift.apply(this,arguments);return this.length}}if(!Array.isArray){Array.isArray=function isArray(obj){return _toString(obj)=="[object Array]"}}var boxedString=Object("a"),splitString=boxedString[0]!="a"||!(0 in boxedString);var boxedForEach=true;if(Array.prototype.forEach){Array.prototype.forEach.call("foo",function(item,i,obj){if(typeof obj!=="object")boxedForEach=false})}if(!Array.prototype.forEach||!boxedForEach){Array.prototype.forEach=function forEach(fun){var object=toObject(this),self=splitString&&_toString(this)=="[object String]"?this.split(""):object,thisp=arguments[1],i=-1,length=self.length>>>0;if(_toString(fun)!="[object Function]"){throw new TypeError}while(++i>>0,result=Array(length),thisp=arguments[1];if(_toString(fun)!="[object Function]"){throw new TypeError(fun+" is not a function")}for(var i=0;i>>0,result=[],value,thisp=arguments[1];if(_toString(fun)!="[object Function]"){throw new TypeError(fun+" is not a function")}for(var i=0;i>>0,thisp=arguments[1];if(_toString(fun)!="[object Function]"){throw new TypeError(fun+" is not a function")}for(var i=0;i>>0,thisp=arguments[1];if(_toString(fun)!="[object Function]"){throw new TypeError(fun+" is not a function")}for(var i=0;i>>0;if(_toString(fun)!="[object Function]"){throw new TypeError(fun+" is not a function")}if(!length&&arguments.length==1){throw new TypeError("reduce of empty array with no initial value")}var i=0;var result;if(arguments.length>=2){result=arguments[1]}else{do{if(i in self){result=self[i++];break}if(++i>=length){throw new TypeError("reduce of empty array with no initial value")}}while(true)}for(;i>>0;if(_toString(fun)!="[object Function]"){throw new TypeError(fun+" is not a function")}if(!length&&arguments.length==1){throw new TypeError("reduceRight of empty array with no initial value")}var result,i=length-1;if(arguments.length>=2){result=arguments[1]}else{do{if(i in self){result=self[i--];break}if(--i<0){throw new TypeError("reduceRight of empty array with no initial value")}}while(true)}if(i<0){return result}do{if(i in this){result=fun.call(void 0,result,self[i],i,object)}}while(i--);return result}}if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1){Array.prototype.indexOf=function indexOf(sought){var self=splitString&&_toString(this)=="[object String]"?this.split(""):toObject(this),length=self.length>>>0;if(!length){return-1}var i=0;if(arguments.length>1){i=toInteger(arguments[1])}i=i>=0?i:Math.max(0,length+i);for(;i>>0;if(!length){return-1}var i=length-1;if(arguments.length>1){i=Math.min(i,toInteger(arguments[1]))}i=i>=0?i:length-Math.abs(i);for(;i>=0;i--){if(i in self&&sought===self[i]){return i}}return-1}}if(!Object.keys){var hasDontEnumBug=true,dontEnums=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],dontEnumsLength=dontEnums.length;for(var key in{toString:null}){hasDontEnumBug=false}Object.keys=function keys(object){if(typeof object!="object"&&typeof object!="function"||object===null){throw new TypeError("Object.keys called on a non-object")}var keys=[];for(var name in object){if(owns(object,name)){keys.push(name)}}if(hasDontEnumBug){for(var i=0,ii=dontEnumsLength;i9999?"+":"")+("00000"+Math.abs(year)).slice(0<=year&&year<=9999?-4:-6);length=result.length;while(length--){value=result[length];if(value<10){result[length]="0"+value}}return year+"-"+result.slice(0,2).join("-")+"T"+result.slice(2).join(":")+"."+("000"+this.getUTCMilliseconds()).slice(-3)+"Z"}}var dateToJSONIsSupported=false;try{dateToJSONIsSupported=Date.prototype.toJSON&&new Date(NaN).toJSON()===null&&new Date(negativeDate).toJSON().indexOf(negativeYearString)!==-1&&Date.prototype.toJSON.call({toISOString:function(){return true}})}catch(e){}if(!dateToJSONIsSupported){Date.prototype.toJSON=function toJSON(key){var o=Object(this),tv=toPrimitive(o),toISO;if(typeof tv==="number"&&!isFinite(tv)){return null}toISO=o.toISOString;if(typeof toISO!="function"){throw new TypeError("toISOString property is not callable")}return toISO.call(o)}}if(!Date.parse||"Date.parse is buggy"){Date=function(NativeDate){function Date(Y,M,D,h,m,s,ms){var length=arguments.length;if(this instanceof NativeDate){var date=length==1&&String(Y)===Y?new NativeDate(Date.parse(Y)):length>=7?new NativeDate(Y,M,D,h,m,s,ms):length>=6?new NativeDate(Y,M,D,h,m,s):length>=5?new NativeDate(Y,M,D,h,m):length>=4?new NativeDate(Y,M,D,h):length>=3?new NativeDate(Y,M,D):length>=2?new NativeDate(Y,M):length>=1?new NativeDate(Y):new NativeDate;date.constructor=Date;return date}return NativeDate.apply(this,arguments)}var isoDateExpression=new RegExp("^"+"(\\d{4}|[+-]\\d{6})"+"(?:-(\\d{2})"+"(?:-(\\d{2})"+"(?:"+"T(\\d{2})"+":(\\d{2})"+"(?:"+":(\\d{2})"+"(?:(\\.\\d{1,}))?"+")?"+"("+"Z|"+"(?:"+"([-+])"+"(\\d{2})"+":(\\d{2})"+")"+")?)?)?)?"+"$");var months=[0,31,59,90,120,151,181,212,243,273,304,334,365];function dayFromMonth(year,month){var t=month>1?1:0;return months[month]+Math.floor((year-1969+t)/4)-Math.floor((year-1901+t)/100)+Math.floor((year-1601+t)/400)+365*(year-1970)}function toUTC(t){return Number(new NativeDate(1970,0,1,0,0,0,t))}for(var key in NativeDate){Date[key]=NativeDate[key]}Date.now=NativeDate.now;Date.UTC=NativeDate.UTC;Date.prototype=NativeDate.prototype;Date.prototype.constructor=Date;Date.parse=function parse(string){var match=isoDateExpression.exec(string);if(match){var year=Number(match[1]),month=Number(match[2]||1)-1,day=Number(match[3]||1)-1,hour=Number(match[4]||0),minute=Number(match[5]||0),second=Number(match[6]||0),millisecond=Math.floor(Number(match[7]||0)*1e3),isLocalTime=Boolean(match[4]&&!match[8]),signOffset=match[9]==="-"?1:-1,hourOffset=Number(match[10]||0),minuteOffset=Number(match[11]||0),result;if(hour<(minute>0||second>0||millisecond>0?24:25)&&minute<60&&second<60&&millisecond<1e3&&month>-1&&month<12&&hourOffset<24&&minuteOffset<60&&day>-1&&day=0){c+=data[i];data[i]=Math.floor(c/n);c=c%n*base}}function toString(){var i=size;var s="";while(--i>=0){if(s!==""||i===0||data[i]!==0){var t=String(data[i]);if(s===""){s=t}else{s+="0000000".slice(0,7-t.length)+t}}}return s}function pow(x,n,acc){return n===0?acc:n%2===1?pow(x,n-1,acc*x):pow(x*x,n/2,acc)}function log(x){var n=0;while(x>=4096){n+=12;x/=4096}while(x>=2){n+=1;x/=2}return n}Number.prototype.toFixed=function(fractionDigits){var f,x,s,m,e,z,j,k;f=Number(fractionDigits);f=f!==f?0:Math.floor(f);if(f<0||f>20){throw new RangeError("Number.toFixed called with invalid number of decimals")}x=Number(this);if(x!==x){return"NaN"}if(x<=-1e21||x>=1e21){return String(x)}s="";if(x<0){s="-";x=-x}m="0";if(x>1e-21){e=log(x*pow(2,69,1))-69;z=e<0?x*pow(2,-e,1):x/pow(2,e,1);z*=4503599627370496;e=52-e;if(e>0){multiply(0,z);j=f;while(j>=7){multiply(1e7,0);j-=7}multiply(pow(10,j,1),0);j=e-1;while(j>=23){divide(1<<23);j-=23}divide(1<0){k=m.length;if(k<=f){m=s+"0.0000000000000000000".slice(0,f-k+2)+m}else{m=s+m.slice(0,k-f)+"."+m.slice(k-f)}}else{m=s+m}return m}})()}var string_split=String.prototype.split;if("ab".split(/(?:ab)*/).length!==2||".".split(/(.?)(.?)/).length!==4||"tesst".split(/(s)*/)[1]==="t"||"".split(/.?/).length||".".split(/()()/).length>1){(function(){var compliantExecNpcg=/()??/.exec("")[1]===void 0;String.prototype.split=function(separator,limit){var string=this;if(separator===void 0&&limit===0)return[];if(Object.prototype.toString.call(separator)!=="[object RegExp]"){return string_split.apply(this,arguments)}var output=[],flags=(separator.ignoreCase?"i":"")+(separator.multiline?"m":"")+(separator.extended?"x":"")+(separator.sticky?"y":""),lastLastIndex=0,separator=new RegExp(separator.source,flags+"g"),separator2,match,lastIndex,lastLength;string+="";if(!compliantExecNpcg){separator2=new RegExp("^"+separator.source+"$(?!\\s)",flags)}limit=limit===void 0?-1>>>0:limit>>>0;while(match=separator.exec(string)){lastIndex=match.index+match[0].length;if(lastIndex>lastLastIndex){output.push(string.slice(lastLastIndex,match.index));if(!compliantExecNpcg&&match.length>1){match[0].replace(separator2,function(){for(var i=1;i1&&match.index=limit){break}}if(separator.lastIndex===match.index){separator.lastIndex++}}if(lastLastIndex===string.length){if(lastLength||!separator.test("")){output.push("")}}else{output.push(string.slice(lastLastIndex))}return output.length>limit?output.slice(0,limit):output}})()}else if("0".split(void 0,0).length){String.prototype.split=function(separator,limit){if(separator===void 0&&limit===0)return[];return string_split.apply(this,arguments)}}if("".substr&&"0b".substr(-1)!=="b"){var string_substr=String.prototype.substr;String.prototype.substr=function(start,length){return string_substr.call(this,start<0?(start=this.length+start)<0?0:start:start,length)}}var ws=" \n \f\r \xa0\u1680\u180e\u2000\u2001\u2002\u2003"+"\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028"+"\u2029\ufeff";if(!String.prototype.trim||ws.trim()){ws="["+ws+"]";var trimBeginRegexp=new RegExp("^"+ws+ws+"*"),trimEndRegexp=new RegExp(ws+ws+"*$");String.prototype.trim=function trim(){if(this===void 0||this===null){throw new TypeError("can't convert "+this+" to object")}return String(this).replace(trimBeginRegexp,"").replace(trimEndRegexp,"")}}function toInteger(n){n=+n;if(n!==n){n=0}else if(n!==0&&n!==1/0&&n!==-(1/0)){n=(n>0||-1)*Math.floor(Math.abs(n))}return n}function isPrimitive(input){var type=typeof input;return input===null||type==="undefined"||type==="boolean"||type==="number"||type==="string"}function toPrimitive(input){var val,valueOf,toString;if(isPrimitive(input)){return input}valueOf=input.valueOf;if(typeof valueOf==="function"){val=valueOf.call(input);if(isPrimitive(val)){return val}}toString=input.toString;if(typeof toString==="function"){val=toString.call(input);if(isPrimitive(val)){return val}}throw new TypeError}var toObject=function(o){if(o==null){throw new TypeError("can't convert "+o+" to object")}return Object(o)}}); +//# sourceMappingURL=es5-shim.map \ No newline at end of file diff --git a/lib/jquery.jplayer.min.js b/lib/jquery.jplayer.min.js new file mode 100644 index 0000000000000000000000000000000000000000..d0c723965ec2341fa9653672a0f06bbab4984766 --- /dev/null +++ b/lib/jquery.jplayer.min.js @@ -0,0 +1,107 @@ +/* + * jPlayer Plugin for jQuery JavaScript Library + * http://www.jplayer.org + * + * Copyright (c) 2009 - 2013 Happyworm Ltd + * Dual licensed under the MIT and GPL licenses. + * - http://www.opensource.org/licenses/mit-license.php + * - http://www.gnu.org/copyleft/gpl.html + * + * Author: Mark J Panaghiston + * Version: 2.3.0 + * Date: 20th April 2013 + */ +(function(b,f){"function"===typeof define&&define.amd?define(["jquery"],f):f(b.jQuery)})(this,function(b,f){b.fn.jPlayer=function(a){var c="string"===typeof a,d=Array.prototype.slice.call(arguments,1),e=this;a=!c&&d.length?b.extend.apply(null,[!0,a].concat(d)):a;if(c&&"_"===a.charAt(0))return e;c?this.each(function(){var c=b.data(this,"jPlayer"),h=c&&b.isFunction(c[a])?c[a].apply(c,d):c;if(h!==c&&h!==f)return e=h,!1}):this.each(function(){var c=b.data(this,"jPlayer");c?c.option(a||{}):b.data(this, +"jPlayer",new b.jPlayer(a,this))});return e};b.jPlayer=function(a,c){if(arguments.length){this.element=b(c);this.options=b.extend(!0,{},this.options,a);var d=this;this.element.bind("remove.jPlayer",function(){d.destroy()});this._init()}};b.jPlayer.emulateMethods="load play pause";b.jPlayer.emulateStatus="src readyState networkState currentTime duration paused ended playbackRate";b.jPlayer.emulateOptions="muted volume";b.jPlayer.reservedEvent="ready flashreset resize repeat error warning";b.jPlayer.event= +{};b.each("ready flashreset resize repeat click error warning loadstart progress suspend abort emptied stalled play pause loadedmetadata loadeddata waiting playing canplay canplaythrough seeking seeked timeupdate ended ratechange durationchange volumechange".split(" "),function(){b.jPlayer.event[this]="jPlayer_"+this});b.jPlayer.htmlEvent="loadstart abort emptied stalled loadedmetadata loadeddata canplay canplaythrough ratechange".split(" ");b.jPlayer.pause=function(){b.each(b.jPlayer.prototype.instances, +function(a,c){c.data("jPlayer").status.srcSet&&c.jPlayer("pause")})};b.jPlayer.timeFormat={showHour:!1,showMin:!0,showSec:!0,padHour:!1,padMin:!0,padSec:!0,sepHour:":",sepMin:":",sepSec:""};var l=function(){this.init()};l.prototype={init:function(){this.options={timeFormat:b.jPlayer.timeFormat}},time:function(a){var c=new Date(1E3*(a&&"number"===typeof a?a:0)),b=c.getUTCHours();a=this.options.timeFormat.showHour?c.getUTCMinutes():c.getUTCMinutes()+60*b;c=this.options.timeFormat.showMin?c.getUTCSeconds(): +c.getUTCSeconds()+60*a;b=this.options.timeFormat.padHour&&10>b?"0"+b:b;a=this.options.timeFormat.padMin&&10>a?"0"+a:a;c=this.options.timeFormat.padSec&&10>c?"0"+c:c;b=""+(this.options.timeFormat.showHour?b+this.options.timeFormat.sepHour:"");b+=this.options.timeFormat.showMin?a+this.options.timeFormat.sepMin:"";return b+=this.options.timeFormat.showSec?c+this.options.timeFormat.sepSec:""}};var m=new l;b.jPlayer.convertTime=function(a){return m.time(a)};b.jPlayer.uaBrowser=function(a){a=a.toLowerCase(); +var b=/(opera)(?:.*version)?[ \/]([\w.]+)/,d=/(msie) ([\w.]+)/,e=/(mozilla)(?:.*? rv:([\w.]+))?/;a=/(webkit)[ \/]([\w.]+)/.exec(a)||b.exec(a)||d.exec(a)||0>a.indexOf("compatible")&&e.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}};b.jPlayer.uaPlatform=function(a){var b=a.toLowerCase(),d=/(android)/,e=/(mobile)/;a=/(ipad|iphone|ipod|android|blackberry|playbook|windows ce|webos)/.exec(b)||[];b=/(ipad|playbook)/.exec(b)||!e.exec(b)&&d.exec(b)||[];a[1]&&(a[1]=a[1].replace(/\s/g,"_"));return{platform:a[1]|| +"",tablet:b[1]||""}};b.jPlayer.browser={};b.jPlayer.platform={};var j=b.jPlayer.uaBrowser(navigator.userAgent);j.browser&&(b.jPlayer.browser[j.browser]=!0,b.jPlayer.browser.version=j.version);j=b.jPlayer.uaPlatform(navigator.userAgent);j.platform&&(b.jPlayer.platform[j.platform]=!0,b.jPlayer.platform.mobile=!j.tablet,b.jPlayer.platform.tablet=!!j.tablet);b.jPlayer.getDocMode=function(){var a;b.jPlayer.browser.msie&&(document.documentMode?a=document.documentMode:(a=5,document.compatMode&&"CSS1Compat"=== +document.compatMode&&(a=7)));return a};b.jPlayer.browser.documentMode=b.jPlayer.getDocMode();b.jPlayer.nativeFeatures={init:function(){var a=document,b=a.createElement("video"),d={w3c:"fullscreenEnabled fullscreenElement requestFullscreen exitFullscreen fullscreenchange fullscreenerror".split(" "),moz:"mozFullScreenEnabled mozFullScreenElement mozRequestFullScreen mozCancelFullScreen mozfullscreenchange mozfullscreenerror".split(" "),webkit:" webkitCurrentFullScreenElement webkitRequestFullScreen webkitCancelFullScreen webkitfullscreenchange ".split(" "), +webkitVideo:"webkitSupportsFullscreen webkitDisplayingFullscreen webkitEnterFullscreen webkitExitFullscreen ".split(" ")},e=["w3c","moz","webkit","webkitVideo"],g,h;this.fullscreen=b={support:{w3c:!!a[d.w3c[0]],moz:!!a[d.moz[0]],webkit:"function"===typeof a[d.webkit[3]],webkitVideo:"function"===typeof b[d.webkitVideo[2]]},used:{}};g=0;for(h=e.length;g','','','',''];c=document.createElement('');for(var e=0;e= +a&&(b=!0);return b},_validString:function(a){return a&&"string"===typeof a},_limitValue:function(a,b,d){return ad?d:a},_urlNotSetError:function(a){this._error({type:b.jPlayer.error.URL_NOT_SET,context:a,message:b.jPlayer.errorMsg.URL_NOT_SET,hint:b.jPlayer.errorHint.URL_NOT_SET})},_flashError:function(a){var c;c=this.internal.ready?"FLASH_DISABLED":"FLASH";this._error({type:b.jPlayer.error[c],context:this.internal.flash.swf,message:b.jPlayer.errorMsg[c]+a.message,hint:b.jPlayer.errorHint[c]}); +this.internal.flash.jq.css({width:"1px",height:"1px"})},_error:function(a){this._trigger(b.jPlayer.event.error,a);this.options.errorAlerts&&this._alert("Error!"+(a.message?"\n\n"+a.message:"")+(a.hint?"\n\n"+a.hint:"")+"\n\nContext: "+a.context)},_warning:function(a){this._trigger(b.jPlayer.event.warning,f,a);this.options.warningAlerts&&this._alert("Warning!"+(a.message?"\n\n"+a.message:"")+(a.hint?"\n\n"+a.hint:"")+"\n\nContext: "+a.context)},_alert:function(a){alert("jPlayer "+this.version.script+ +" : id='"+this.internal.self.id+"' : "+a)},_emulateHtmlBridge:function(){var a=this;b.each(b.jPlayer.emulateMethods.split(/\s+/g),function(b,d){a.internal.domNode[d]=function(b){a[d](b)}});b.each(b.jPlayer.event,function(c,d){var e=!0;b.each(b.jPlayer.reservedEvent.split(/\s+/g),function(a,b){if(b===c)return e=!1});e&&a.element.bind(d+".jPlayer.jPlayerHtml",function(){a._emulateHtmlUpdate();var b=document.createEvent("Event");b.initEvent(c,!1,!0);a.internal.domNode.dispatchEvent(b)})})},_emulateHtmlUpdate:function(){var a= +this;b.each(b.jPlayer.emulateStatus.split(/\s+/g),function(b,d){a.internal.domNode[d]=a.status[d]});b.each(b.jPlayer.emulateOptions.split(/\s+/g),function(b,d){a.internal.domNode[d]=a.options[d]})},_destroyHtmlBridge:function(){var a=this;this.element.unbind(".jPlayerHtml");b.each((b.jPlayer.emulateMethods+" "+b.jPlayer.emulateStatus+" "+b.jPlayer.emulateOptions).split(/\s+/g),function(b,d){delete a.internal.domNode[d]})}};b.jPlayer.error={FLASH:"e_flash",FLASH_DISABLED:"e_flash_disabled",NO_SOLUTION:"e_no_solution", +NO_SUPPORT:"e_no_support",URL:"e_url",URL_NOT_SET:"e_url_not_set",VERSION:"e_version"};b.jPlayer.errorMsg={FLASH:"jPlayer's Flash fallback is not configured correctly, or a command was issued before the jPlayer Ready event. Details: ",FLASH_DISABLED:"jPlayer's Flash fallback has been disabled by the browser due to the CSS rules you have used. Details: ",NO_SOLUTION:"No solution can be found by jPlayer in this browser. Neither HTML nor Flash can be used.",NO_SUPPORT:"It is not possible to play any media format provided in setMedia() on this browser using your current options.", +URL:"Media URL could not be loaded.",URL_NOT_SET:"Attempt to issue media playback commands, while no media url is set.",VERSION:"jPlayer "+b.jPlayer.prototype.version.script+" needs Jplayer.swf version "+b.jPlayer.prototype.version.needFlash+" but found "};b.jPlayer.errorHint={FLASH:"Check your swfPath option and that Jplayer.swf is there.",FLASH_DISABLED:"Check that you have not display:none; the jPlayer entity or any ancestor.",NO_SOLUTION:"Review the jPlayer options: support and supplied.",NO_SUPPORT:"Video or audio formats defined in the supplied option are missing.", +URL:"Check media URL is valid.",URL_NOT_SET:"Use setMedia() to set the media URL.",VERSION:"Update jPlayer files."};b.jPlayer.warning={CSS_SELECTOR_COUNT:"e_css_selector_count",CSS_SELECTOR_METHOD:"e_css_selector_method",CSS_SELECTOR_STRING:"e_css_selector_string",OPTION_KEY:"e_option_key"};b.jPlayer.warningMsg={CSS_SELECTOR_COUNT:"The number of css selectors found did not equal one: ",CSS_SELECTOR_METHOD:"The methodName given in jPlayer('cssSelector') is not a valid jPlayer method.",CSS_SELECTOR_STRING:"The methodCssSelector given in jPlayer('cssSelector') is not a String or is empty.", +OPTION_KEY:"The option requested in jPlayer('option') is undefined."};b.jPlayer.warningHint={CSS_SELECTOR_COUNT:"Check your css selector and the ancestor.",CSS_SELECTOR_METHOD:"Check your method name.",CSS_SELECTOR_STRING:"Check your css selector is a string.",OPTION_KEY:"Check your option name."}}); \ No newline at end of file diff --git a/lib/rotjs-library/README.md b/lib/rotjs-library/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dbb3f3e93cdeb4ea63942e77222740805e154b3a --- /dev/null +++ b/lib/rotjs-library/README.md @@ -0,0 +1,6 @@ +rot.js +====== + +ROguelike Toolkit + +More info: http://ondras.github.com/rot.js diff --git a/lib/rotjs-library/TODO b/lib/rotjs-library/TODO new file mode 100644 index 0000000000000000000000000000000000000000..5616a2f422b9593fdfdcb8df52a6df7dfb17ffea --- /dev/null +++ b/lib/rotjs-library/TODO @@ -0,0 +1,2 @@ +remove FIXMEs +fix drawText on hexes, how? diff --git a/lib/rotjs-library/VERSION b/lib/rotjs-library/VERSION new file mode 100644 index 0000000000000000000000000000000000000000..671161376963b8be0f6403d2c541ac1e76d0d252 --- /dev/null +++ b/lib/rotjs-library/VERSION @@ -0,0 +1 @@ +0.4~dev diff --git a/lib/rotjs-library/doc/files.html b/lib/rotjs-library/doc/files.html new file mode 100644 index 0000000000000000000000000000000000000000..2979806fd6a47478d67c6e67a1b94ba0cfa0fb96 --- /dev/null +++ b/lib/rotjs-library/doc/files.html @@ -0,0 +1,286 @@ + + + + + + JsDoc Reference - File Index + + + + + + + + +
    + +
    +

    File Index

    + + +
    +

    <rot.js>

    + +
    + + + + +
    +
    +
    + + +
    +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + \ No newline at end of file diff --git a/lib/rotjs-library/doc/index.html b/lib/rotjs-library/doc/index.html new file mode 100644 index 0000000000000000000000000000000000000000..c301d60c4ef408f5f8f2d7f88b0c05e0d1755412 --- /dev/null +++ b/lib/rotjs-library/doc/index.html @@ -0,0 +1,492 @@ + + + + + + JsDoc Reference - Index + + + + + + + + + + +
    +

    Class Index

    + + +
    +

    _global_

    + +
    +
    + +
    +

    Array

    + +
    +
    + +
    +

    Date

    + +
    +
    + +
    +

    Function

    + +
    +
    + +
    +

    Number

    + +
    +
    + +
    +

    Object

    + +
    +
    + +
    +

    ROT

    + Top-level ROT namespace +
    +
    + +
    +

    ROT.Color

    + Color operations +
    +
    + +
    +

    ROT.Display

    + Visual map display +
    +
    + +
    +

    ROT.Engine

    + Asynchronous main loop +
    +
    + +
    +

    ROT.FOV

    + Abstract FOV algorithm +
    +
    + +
    +

    ROT.FOV.DiscreteShadowcasting

    + Discrete shadowcasting algorithm +
    +
    + +
    +

    ROT.FOV.PreciseShadowcasting

    + Precise shadowcasting algorithm +
    +
    + +
    +

    ROT.Lighting

    + Lighting computation, based on a traditional FOV for multiple light sources and multiple passes. +
    +
    + +
    +

    ROT.Map

    + Base map generator +
    +
    + +
    +

    ROT.Map.Arena

    + Simple empty rectangular room +
    +
    + +
    +

    ROT.Map.Cellular

    + Cellular automaton map generator +
    +
    + +
    +

    ROT.Map.Digger

    + Random dungeon generator using human-like digging patterns. +
    +
    + +
    +

    ROT.Map.DividedMaze

    + Recursively divided maze, http://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_division_method +
    +
    + +
    +

    ROT.Map.Dungeon

    + Dungeon map: has rooms and corridors +
    +
    + +
    +

    ROT.Map.EllerMaze

    + Maze generator - Eller's algorithm +See http://homepages.cwi.nl/~tromp/maze.html for explanation +
    +
    + +
    +

    ROT.Map.Feature

    + Dungeon feature; has own .create() method +
    +
    + +
    +

    ROT.Map.Feature.Corridor

    + Corridor +
    +
    + + +
    + +
    +

    ROT.Map.IceyMaze

    + Icey's Maze generator +See http://www.roguebasin.roguelikedevelopment.org/index.php?title=Simple_maze for explanation +
    +
    + +
    +

    ROT.Map.Uniform

    + Dungeon generator which tries to fill the space evenly. +
    +
    + +
    +

    ROT.Noise

    + Base noise generator +
    +
    + +
    +

    ROT.Noise.Simplex

    + 2D simplex noise generator +
    +
    + +
    +

    ROT.Path

    + Abstract pathfinder +
    +
    + +
    +

    ROT.Path.AStar

    + Simplified A* algorithm: all edges have a value of 1 +
    +
    + +
    +

    ROT.Path.Dijkstra

    + Simplified Dijkstra's algorithm: all edges have a value of 1 +
    +
    + +
    +

    ROT.RNG

    + This code is an implementation of Alea algorithm; (C) 2010 Johannes Baagøe. +
    +
    + +
    +

    ROT.Scheduler

    + Speed-based scheduler +
    +
    + +
    +

    ROT.StringGenerator

    + (Markov process)-based string generator. +
    +
    + +
    +

    ROT.Text

    + Contains text tokenization and breaking routines +
    +
    + +
    +

    String

    + +
    +
    + + +
    +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + \ No newline at end of file diff --git a/lib/rotjs-library/doc/symbols/Array.html b/lib/rotjs-library/doc/symbols/Array.html new file mode 100644 index 0000000000000000000000000000000000000000..c8e81eeffbb5d17fe7f8144f3600eabdacded510 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/Array.html @@ -0,0 +1,431 @@ + + + + + + + JsDoc Reference - Array + + + + + + + + + + + + + +
    + +

    + + Built-In Namespace Array +

    + + +

    + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    random() +
    +
    +
      + +
    +
    + + + + + + + + + + + + + + + +
    + Method Detail +
    + + +
    + + {any} + random() + +
    +
    + + +
    + Defined in: <rot.js>. + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {any} Randomly picked item, null when length=0
    + +
    + + + + +
    + + +
    + + {array} + randomize() + +
    +
    + + +
    + Defined in: <rot.js>. + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {array} New array with randomized items +FIXME destroys this!
    + +
    + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:29 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/Date.html b/lib/rotjs-library/doc/symbols/Date.html new file mode 100644 index 0000000000000000000000000000000000000000..572093aff647690899623944ab5eaa558406cfea --- /dev/null +++ b/lib/rotjs-library/doc/symbols/Date.html @@ -0,0 +1,386 @@ + + + + + + + JsDoc Reference - Date + + + + + + + + + + + + + +
    + +

    + + Built-In Namespace Date +

    + + +

    + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
    <static>   +
    Date.now() +
    +
    +
    + + + + + + + + + + + + + + + +
    + Method Detail +
    + + +
    <static> + + {int} + Date.now() + +
    +
    + + +
    + Defined in: <rot.js>. + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {int} Current timestamp (msec)
    + +
    + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:29 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/Function.html b/lib/rotjs-library/doc/symbols/Function.html new file mode 100644 index 0000000000000000000000000000000000000000..3c2d74ab92142ac57fe7ab4a0c4fb47043ba4ab9 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/Function.html @@ -0,0 +1,390 @@ + + + + + + + JsDoc Reference - Function + + + + + + + + + + + + + +
    + +

    + + Built-In Namespace Function +

    + + +

    + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    extend(parent) +
    +
    Sets prototype of this function to an instance of parent function
    +
    + + + + + + + + + + + + + + + +
    + Method Detail +
    + + +
    + + + extend(parent) + +
    +
    + Sets prototype of this function to an instance of parent function + +
    + Defined in: <rot.js>. + + +
    + + + + +
    +
    Parameters:
    + +
    + {function} parent + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:29 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/Number.html b/lib/rotjs-library/doc/symbols/Number.html new file mode 100644 index 0000000000000000000000000000000000000000..44bd718cf4b053012b2c9b481789b01750d68777 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/Number.html @@ -0,0 +1,397 @@ + + + + + + + JsDoc Reference - Number + + + + + + + + + + + + + +
    + +

    + + Built-In Namespace Number +

    + + +

    + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    mod(n) +
    +
    Always positive modulus
    +
    + + + + + + + + + + + + + + + +
    + Method Detail +
    + + +
    + + {int} + mod(n) + +
    +
    + Always positive modulus + +
    + Defined in: <rot.js>. + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} n + +
    +
    Modulus
    + +
    + + + + + +
    +
    Returns:
    + +
    {int} this modulo n
    + +
    + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:29 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/Object.html b/lib/rotjs-library/doc/symbols/Object.html new file mode 100644 index 0000000000000000000000000000000000000000..eee74b0eae71f7d46bbf9a1e3cc4f8fc5dee9983 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/Object.html @@ -0,0 +1,390 @@ + + + + + + + JsDoc Reference - Object + + + + + + + + + + + + + +
    + +

    + + Built-In Namespace Object +

    + + +

    + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
    <static>   +
    Object.create(o) +
    +
    ES5 Object.create
    +
    + + + + + + + + + + + + + + + +
    + Method Detail +
    + + +
    <static> + + + Object.create(o) + +
    +
    + ES5 Object.create + +
    + Defined in: <rot.js>. + + +
    + + + + +
    +
    Parameters:
    + +
    + o + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:29 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Color.html b/lib/rotjs-library/doc/symbols/ROT.Color.html new file mode 100644 index 0000000000000000000000000000000000000000..ef4b6f13bf2a15fa4bcca4c75686d86bba4504f8 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Color.html @@ -0,0 +1,1049 @@ + + + + + + + JsDoc Reference - ROT.Color + + + + + + + + + + + + + +
    + +

    + + Namespace ROT.Color +

    + + +

    + + + + Color operations + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Namespace Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Color +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
    <static>   +
    ROT.Color.add(color1, color2) +
    +
    Add two or more colors
    +
    <static>   +
    ROT.Color.add_(color1, color2) +
    +
    Add two or more colors, MODIFIES FIRST ARGUMENT
    +
    <static>   +
    ROT.Color.fromString(str) +
    +
    +
    <static>   +
    ROT.Color.hsl2rgb(color) +
    +
    Converts an HSL color value to RGB.
    +
    <static>   +
    ROT.Color.interpolate(color1, color2, factor) +
    +
    Interpolate (blend) two colors with a given factor
    +
    <static>   +
    ROT.Color.interpolateHSL(color1, color2, factor) +
    +
    Interpolate (blend) two colors with a given factor in HSL mode
    +
    <static>   +
    ROT.Color.multiply(color1, color2) +
    +
    Multiply (mix) two or more colors
    +
    <static>   +
    ROT.Color.multiply_(color1, color2) +
    +
    Multiply (mix) two or more colors, MODIFIES FIRST ARGUMENT
    +
    <static>   +
    ROT.Color.randomize(color, diff) +
    +
    Create a new random color based on this one
    +
    <static>   +
    ROT.Color.rgb2hsl(color) +
    +
    Converts an RGB color value to HSL.
    +
    <static>   +
    ROT.Color.toHex(color) +
    +
    +
    <static>   +
    ROT.Color.toRGB(color) +
    +
    +
    + + + + + + + + + +
    +
    + Namespace Detail +
    + +
    + ROT.Color +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    <static> + + {number[]} + ROT.Color.add(color1, color2) + +
    +
    + Add two or more colors + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color1 + +
    +
    + +
    + {number[]} color2 + +
    +
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.add_(color1, color2) + +
    +
    + Add two or more colors, MODIFIES FIRST ARGUMENT + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color1 + +
    +
    + +
    + {number[]} color2 + +
    +
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + + ROT.Color.fromString(str) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + str + +
    +
    + +
    + + + + + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.hsl2rgb(color) + +
    +
    + Converts an HSL color value to RGB. Expects 0..1 inputs, produces 0..255 outputs. + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color + +
    +
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.interpolate(color1, color2, factor) + +
    +
    + Interpolate (blend) two colors with a given factor + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color1 + +
    +
    + +
    + {number[]} color2 + +
    +
    + +
    + {float} factor + Optional, Default: 0.5 +
    +
    0..1
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.interpolateHSL(color1, color2, factor) + +
    +
    + Interpolate (blend) two colors with a given factor in HSL mode + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color1 + +
    +
    + +
    + {number[]} color2 + +
    +
    + +
    + {float} factor + Optional, Default: 0.5 +
    +
    0..1
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.multiply(color1, color2) + +
    +
    + Multiply (mix) two or more colors + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color1 + +
    +
    + +
    + {number[]} color2 + +
    +
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.multiply_(color1, color2) + +
    +
    + Multiply (mix) two or more colors, MODIFIES FIRST ARGUMENT + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color1 + +
    +
    + +
    + {number[]} color2 + +
    +
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.randomize(color, diff) + +
    +
    + Create a new random color based on this one + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color + +
    +
    + +
    + {number[]} diff + +
    +
    Set of standard deviations
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + {number[]} + ROT.Color.rgb2hsl(color) + +
    +
    + Converts an RGB color value to HSL. Expects 0..255 inputs, produces 0..1 outputs. + + +
    + + + + +
    +
    Parameters:
    + +
    + {number[]} color + +
    +
    + +
    + + + + + +
    +
    Returns:
    + +
    {number[]}
    + +
    + + + + +
    + + +
    <static> + + + ROT.Color.toHex(color) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + color + +
    +
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.Color.toRGB(color) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + color + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Display.html b/lib/rotjs-library/doc/symbols/ROT.Display.html new file mode 100644 index 0000000000000000000000000000000000000000..ab0685d89af5624d066e20439a97f1a8235ee78f --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Display.html @@ -0,0 +1,949 @@ + + + + + + + JsDoc Reference - ROT.Display + + + + + + + + + + + + + +
    + +

    + + Class ROT.Display +

    + + +

    + + + + Visual map display + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Display(options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    clear() +
    +
    Clear the whole display (cover it with background color)
    +
      +
    computeFontSize(availWidth, availHeight) +
    +
    Compute the maximum font size to fit into a set of given constraints
    +
      +
    computeSize(availWidth, availHeight) +
    +
    Compute the maximum width/height to fit into a set of given constraints
    +
      +
    DEBUG(x, y, what) +
    +
    Debug helper, ideal as a map generator callback.
    +
      +
    draw(x, y, ch, fg, bg) +
    +
    +
      +
    drawText(x, y, text, maxWidth) +
    +
    Draws a text at given position.
    +
      + +
    Returns the DOM node of this display
    +
      + +
    Returns currently set options
    +
      +
    setOptions(options) +
    +
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Display(options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {object} options + Optional +
    +
    + +
    + {int} options.width + Optional, Default: ROT.DEFAULT_WIDTH +
    +
    + +
    + {int} options.height + Optional, Default: ROT.DEFAULT_HEIGHT +
    +
    + +
    + {int} options.fontSize + Optional, Default: 15 +
    +
    + +
    + {string} options.fontFamily + Optional, Default: "monospace" +
    +
    + +
    + {string} options.fontStyle + Optional, Default: "" +
    +
    bold/italic/none/both
    + +
    + {string} options.fg + Optional, Default: "#ccc" +
    +
    + +
    + {string} options.bg + Optional, Default: "#000" +
    +
    + +
    + {int} options.fps + Optional, Default: 25 +
    +
    + +
    + {float} options.spacing + Optional, Default: 1 +
    +
    + +
    + {float} options.border + Optional, Default: 0 +
    +
    + +
    + {string} options.layout + Optional, Default: "rect" +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + clear() + +
    +
    + Clear the whole display (cover it with background color) + + +
    + + + + + + + + + + + +
    + + +
    + + {int} + computeFontSize(availWidth, availHeight) + +
    +
    + Compute the maximum font size to fit into a set of given constraints + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} availWidth + +
    +
    Maximum allowed pixel width
    + +
    + {int} availHeight + +
    +
    Maximum allowed pixel height
    + +
    + + + + + +
    +
    Returns:
    + +
    {int} fontSize
    + +
    + + + + +
    + + +
    + + {int[2]} + computeSize(availWidth, availHeight) + +
    +
    + Compute the maximum width/height to fit into a set of given constraints + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} availWidth + +
    +
    Maximum allowed pixel width
    + +
    + {int} availHeight + +
    +
    Maximum allowed pixel height
    + +
    + + + + + +
    +
    Returns:
    + +
    {int[2]} cellWidth,cellHeight
    + +
    + + + + +
    + + +
    + + + DEBUG(x, y, what) + +
    +
    + Debug helper, ideal as a map generator callback. Always bound to this. + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} x + +
    +
    + +
    + {int} y + +
    +
    + +
    + {int} what + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + draw(x, y, ch, fg, bg) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} x + +
    +
    + +
    + {int} y + +
    +
    + +
    + {string} ch + +
    +
    + +
    + {string} fg + Optional +
    +
    foreground color
    + +
    + {string} bg + Optional +
    +
    background color
    + +
    + + + + + + + + +
    + + +
    + + {int} + drawText(x, y, text, maxWidth) + +
    +
    + Draws a text at given position. Optionally wraps at a maximum length. Currently does not work with hex layout. + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} x + +
    +
    + +
    + {int} y + +
    +
    + +
    + {string} text + +
    +
    May contain color/background format specifiers, %c{name}/%b{name}, both optional. %c{}/%b{} resets to default.
    + +
    + {int} maxWidth + Optional +
    +
    wrap at what width?
    + +
    + + + + + +
    +
    Returns:
    + +
    {int} lines drawn
    + +
    + + + + +
    + + +
    + + {node} + getContainer() + +
    +
    + Returns the DOM node of this display + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {node} DOM node
    + +
    + + + + +
    + + +
    + + {object} + getOptions() + +
    +
    + Returns currently set options + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {object} Current options object
    + +
    + + + + +
    + + +
    + + + setOptions(options) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + options + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Display
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Engine.html b/lib/rotjs-library/doc/symbols/ROT.Engine.html new file mode 100644 index 0000000000000000000000000000000000000000..03cd4a8931856e87ae012fd31ca6d0700b2ae595 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Engine.html @@ -0,0 +1,618 @@ + + + + + + + JsDoc Reference - ROT.Engine + + + + + + + + + + + + + +
    + +

    + + Class ROT.Engine +

    + + +

    + + + + Asynchronous main loop + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Engine() +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    addActor(actor) +
    +
    +
      +
    clear() +
    +
    Remove all actors
    +
      +
    lock() +
    +
    Interrupt the engine by an asynchronous action
    +
      +
    removeActor(actor) +
    +
    Remove a previously added actor
    +
      +
    start() +
    +
    Start the main loop.
    +
      +
    unlock() +
    +
    Resume execution (paused by a previous lock)
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Engine() +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + addActor(actor) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {object} actor + +
    +
    Anything with "getSpeed" and "act" methods
    + +
    + + + + + + + + +
    + + +
    + + + clear() + +
    +
    + Remove all actors + + +
    + + + + + + + + + + + +
    + + +
    + + + lock() + +
    +
    + Interrupt the engine by an asynchronous action + + +
    + + + + + + + + + + + +
    + + +
    + + + removeActor(actor) + +
    +
    + Remove a previously added actor + + +
    + + + + +
    +
    Parameters:
    + +
    + {object} actor + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + start() + +
    +
    + Start the main loop. When this call returns, the loop is locked. + + +
    + + + + + + + + + + + +
    + + +
    + + + unlock() + +
    +
    + Resume execution (paused by a previous lock) + + +
    + + + + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.FOV.DiscreteShadowcasting.html b/lib/rotjs-library/doc/symbols/ROT.FOV.DiscreteShadowcasting.html new file mode 100644 index 0000000000000000000000000000000000000000..06534ac9fe9f62158af7a6ef4adc66ab4e6d6bec --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.FOV.DiscreteShadowcasting.html @@ -0,0 +1,485 @@ + + + + + + + JsDoc Reference - ROT.FOV.DiscreteShadowcasting + + + + + + + + + + + + + +
    + +

    + + Class ROT.FOV.DiscreteShadowcasting +

    + + +

    + +
    Extends + ROT.FOV.
    + + + Discrete shadowcasting algorithm + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.FOV.DiscreteShadowcasting(lightPassesCallback, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    compute(x, y, R, callback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.FOV.DiscreteShadowcasting(lightPassesCallback, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + lightPassesCallback + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + compute(x, y, R, callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + R + +
    +
    + +
    + callback + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.FOV#compute
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.FOV.PreciseShadowcasting.html b/lib/rotjs-library/doc/symbols/ROT.FOV.PreciseShadowcasting.html new file mode 100644 index 0000000000000000000000000000000000000000..be04f7cac44cecfaf08588e7ee5eeae9b6d76a91 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.FOV.PreciseShadowcasting.html @@ -0,0 +1,485 @@ + + + + + + + JsDoc Reference - ROT.FOV.PreciseShadowcasting + + + + + + + + + + + + + +
    + +

    + + Class ROT.FOV.PreciseShadowcasting +

    + + +

    + +
    Extends + ROT.FOV.
    + + + Precise shadowcasting algorithm + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.FOV.PreciseShadowcasting(lightPassesCallback, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    compute(x, y, R, callback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.FOV.PreciseShadowcasting(lightPassesCallback, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + lightPassesCallback + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + compute(x, y, R, callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + R + +
    +
    + +
    + callback + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.FOV#compute
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.FOV.html b/lib/rotjs-library/doc/symbols/ROT.FOV.html new file mode 100644 index 0000000000000000000000000000000000000000..f98bd2102253619aa7b37f47e8d073d991baa2c3 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.FOV.html @@ -0,0 +1,478 @@ + + + + + + + JsDoc Reference - ROT.FOV + + + + + + + + + + + + + +
    + +

    + + Class ROT.FOV +

    + + +

    + + + + Abstract FOV algorithm + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.FOV(lightPassesCallback, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    compute(x, y, R, callback) +
    +
    Compute visibility
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.FOV(lightPassesCallback, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {function} lightPassesCallback + +
    +
    Does the light pass through x,y?
    + +
    + {object} options + Optional +
    +
    + +
    + {int} options.topology + Optional, Default: 8 +
    +
    4/6/8
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + compute(x, y, R, callback) + +
    +
    + Compute visibility + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} x + +
    +
    + +
    + {int} y + +
    +
    + +
    + {int} R + +
    +
    Maximum visibility radius
    + +
    + {function} callback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Lighting.html b/lib/rotjs-library/doc/symbols/ROT.Lighting.html new file mode 100644 index 0000000000000000000000000000000000000000..e01da62c2834eb28c82b92c40501503dc4cc8ee3 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Lighting.html @@ -0,0 +1,660 @@ + + + + + + + JsDoc Reference - ROT.Lighting + + + + + + + + + + + + + +
    + +

    + + Class ROT.Lighting +

    + + +

    + + + + Lighting computation, based on a traditional FOV for multiple light sources and multiple passes. + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Lighting(reflectivityCallback, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    compute(lightingCallback) +
    +
    Compute the lighting
    +
      +
    reset() +
    +
    Reset the pre-computed topology values.
    +
      +
    setFOV(fov) +
    +
    Set the used Field-Of-View algo
    +
      +
    setLight(x, y, color) +
    +
    Set (or remove) a light source
    +
      +
    setOptions(options) +
    +
    Adjust options at runtime
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Lighting(reflectivityCallback, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {function} reflectivityCallback + +
    +
    Callback to retrieve cell reflectivity (0..1)
    + +
    + {object} options + Optional +
    +
    + +
    + {int} options.passes + Optional, Default: 1 +
    +
    Number of passes. 1 equals to simple FOV of all light sources, >1 means a *highly simplified* radiosity-like algorithm.
    + +
    + {int} options.emissionThreshold + Optional, Default: 100 +
    +
    Cells with emissivity > threshold will be treated as light source in the next pass.
    + +
    + {int} options.range + Optional, Default: 10 +
    +
    Max light range
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + compute(lightingCallback) + +
    +
    + Compute the lighting + + +
    + + + + +
    +
    Parameters:
    + +
    + {function} lightingCallback + +
    +
    Will be called with (x, y, color) for every lit cell
    + +
    + + + + + + + + +
    + + +
    + + + reset() + +
    +
    + Reset the pre-computed topology values. Call whenever the underlying map changes its light-passability. + + +
    + + + + + + + + + + + +
    + + +
    + + + setFOV(fov) + +
    +
    + Set the used Field-Of-View algo + + +
    + + + + +
    +
    Parameters:
    + +
    + {ROT.FOV} fov + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + setLight(x, y, color) + +
    +
    + Set (or remove) a light source + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} x + +
    +
    + +
    + {int} y + +
    +
    + +
    + {null || string || number[3]} color + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + setOptions(options) + +
    +
    + Adjust options at runtime + + +
    + + + + +
    +
    Parameters:
    + +
    + {object} options + Optional +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Lighting
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Arena.html b/lib/rotjs-library/doc/symbols/ROT.Map.Arena.html new file mode 100644 index 0000000000000000000000000000000000000000..bc052c20d0d79a3932bcf559a0d406c3ce2b28c6 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Arena.html @@ -0,0 +1,460 @@ + + + + + + + JsDoc Reference - ROT.Map.Arena + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Arena +

    + + +

    + +
    Extends + ROT.Map.
    + + + Simple empty rectangular room + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.Arena(width, height) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Arena(width, height) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + width + +
    +
    + +
    + height + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Cellular.html b/lib/rotjs-library/doc/symbols/ROT.Map.Cellular.html new file mode 100644 index 0000000000000000000000000000000000000000..6481a3fd81aa0e6cf4d044ef6d97a84649400d8a --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Cellular.html @@ -0,0 +1,586 @@ + + + + + + + JsDoc Reference - ROT.Map.Cellular + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Cellular +

    + + +

    + +
    Extends + ROT.Map.
    + + + Cellular automaton map generator + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.Cellular(width, height, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    +
      +
    randomize(probability) +
    +
    Fill the map with random values
    +
      +
    set(x, y, value) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Cellular(width, height, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {int} width + Optional, Default: ROT.DEFAULT_WIDTH +
    +
    + +
    + {int} height + Optional, Default: ROT.DEFAULT_HEIGHT +
    +
    + +
    + {object} options + Optional +
    +
    Options
    + +
    + {int[]} options.born + Optional +
    +
    List of neighbor counts for a new cell to be born in empty space
    + +
    + {int[]} options.survive + Optional +
    +
    List of neighbor counts for an existing cell to survive
    + +
    + {int} options.topology + Optional +
    +
    Topology 4 or 6 or 8
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + randomize(probability) + +
    +
    + Fill the map with random values + + +
    + + + + +
    +
    Parameters:
    + +
    + {float} probability + +
    +
    Probability for a cell to become alive; 0 = all empty, 1 = all full
    + +
    + + + + + + + + +
    + + +
    + + + set(x, y, value) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + value + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Digger.html b/lib/rotjs-library/doc/symbols/ROT.Map.Digger.html new file mode 100644 index 0000000000000000000000000000000000000000..2a85580058fcb2bb80ff23a15ae70503d793fe7b --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Digger.html @@ -0,0 +1,475 @@ + + + + + + + JsDoc Reference - ROT.Map.Digger + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Digger +

    + + +

    + +
    Extends + ROT.Map.Dungeon.
    + + + Random dungeon generator using human-like digging patterns. +Heavily based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at +http://www.roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm. + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.Digger(width, height, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    Create a map
    +
    + + + +
    +
    Methods borrowed from class ROT.Map.Dungeon:
    getCorridors, getRooms
    +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Digger(width, height, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + width + +
    +
    + +
    + height + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + Create a map + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Map#create
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.DividedMaze.html b/lib/rotjs-library/doc/symbols/ROT.Map.DividedMaze.html new file mode 100644 index 0000000000000000000000000000000000000000..46db205da1ccd286b9b217a1e8f91aba0618bf2e --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.DividedMaze.html @@ -0,0 +1,460 @@ + + + + + + + JsDoc Reference - ROT.Map.DividedMaze + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.DividedMaze +

    + + +

    + +
    Extends + ROT.Map.
    + + + Recursively divided maze, http://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_division_method + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.DividedMaze(width, height) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.DividedMaze(width, height) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + width + +
    +
    + +
    + height + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Dungeon.html b/lib/rotjs-library/doc/symbols/ROT.Map.Dungeon.html new file mode 100644 index 0000000000000000000000000000000000000000..9016c45dadf2d7f10ec118dd48ae956767f13401 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Dungeon.html @@ -0,0 +1,497 @@ + + + + + + + JsDoc Reference - ROT.Map.Dungeon + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Dungeon +

    + + +

    + +
    Extends + ROT.Map.
    + + + Dungeon map: has rooms and corridors + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.Dungeon(width, height) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      + +
    Get all generated corridors
    +
      + +
    Get all generated rooms
    +
    + + + +
    +
    Methods borrowed from class ROT.Map:
    create
    +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Dungeon(width, height) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + width + +
    +
    + +
    + height + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + {ROT.Map.Feature.Corridor[]} + getCorridors() + +
    +
    + Get all generated corridors + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {ROT.Map.Feature.Corridor[]}
    + +
    + + + + +
    + + +
    + + {ROT.Map.Feature.Room[]} + getRooms() + +
    +
    + Get all generated rooms + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {ROT.Map.Feature.Room[]}
    + +
    + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.EllerMaze.html b/lib/rotjs-library/doc/symbols/ROT.Map.EllerMaze.html new file mode 100644 index 0000000000000000000000000000000000000000..2b08401737076773f7821cce4dba049fb88d4a8c --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.EllerMaze.html @@ -0,0 +1,461 @@ + + + + + + + JsDoc Reference - ROT.Map.EllerMaze + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.EllerMaze +

    + + +

    + +
    Extends + ROT.Map.
    + + + Maze generator - Eller's algorithm +See http://homepages.cwi.nl/~tromp/maze.html for explanation + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.EllerMaze(width, height) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.EllerMaze(width, height) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + width + +
    +
    + +
    + height + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Feature.Corridor.html b/lib/rotjs-library/doc/symbols/ROT.Map.Feature.Corridor.html new file mode 100644 index 0000000000000000000000000000000000000000..d263e2b080574122b26503851923963971208a94 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Feature.Corridor.html @@ -0,0 +1,671 @@ + + + + + + + JsDoc Reference - ROT.Map.Feature.Corridor + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Feature.Corridor +

    + + +

    + +
    Extends + ROT.Map.Feature.
    + + + Corridor + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.Feature.Corridor(startX, startY, endX, endY) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(digCallback) +
    +
    +
      +
    createPriorityWalls(priorityWallCallback) +
    +
    +
    <static>   +
    ROT.Map.Feature.Corridor.createRandomAt(x, y, dx, dy, options) +
    +
    +
      +
    debug() +
    +
    +
      +
    isValid(isWallCallback, canBeDugCallback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Feature.Corridor(startX, startY, endX, endY) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {int} startX + +
    +
    + +
    + {int} startY + +
    +
    + +
    + {int} endX + +
    +
    + +
    + {int} endY + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(digCallback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {function} digCallback + +
    +
    Dig callback with a signature (x, y, value). Values: 0 = empty.
    + +
    + + + + + + + + +
    + + +
    + + + createPriorityWalls(priorityWallCallback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + priorityWallCallback + +
    +
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.Map.Feature.Corridor.createRandomAt(x, y, dx, dy, options) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + dx + +
    +
    + +
    + dy + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + debug() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + isValid(isWallCallback, canBeDugCallback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + isWallCallback + +
    +
    + +
    + canBeDugCallback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Feature.Room.html b/lib/rotjs-library/doc/symbols/ROT.Map.Feature.Room.html new file mode 100644 index 0000000000000000000000000000000000000000..4d449b6ef5f35488884a4768ec2b633a409188cb --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Feature.Room.html @@ -0,0 +1,1052 @@ + + + + + + + JsDoc Reference - ROT.Map.Feature.Room + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Feature.Room +

    + + +

    + +
    Extends + ROT.Map.Feature.
    + + + Room + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.Feature.Room(x1, y1, x2, y2, doorX, doorY) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    addDoor(x, y) +
    +
    +
      + +
    +
      +
    create(digCallback) +
    +
    +
    <static>   +
    ROT.Map.Feature.Room.createRandom(availWidth, availHeight, options) +
    +
    Room of random size within a given dimensions
    +
    <static>   +
    ROT.Map.Feature.Room.createRandomAt(x, y, dx, dy, options) +
    +
    Room of random size, with a given doors and direction
    +
    <static>   +
    ROT.Map.Feature.Room.createRandomCenter(cx, cy, options) +
    +
    Room of random size, positioned around center coords
    +
      +
    debug() +
    +
    +
      + +
    +
      + +
    +
      + +
    +
      +
    getLeft() +
    +
    +
      + +
    +
      +
    getTop() +
    +
    +
      +
    isValid(isWallCallback, canBeDugCallback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Feature.Room(x1, y1, x2, y2, doorX, doorY) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {int} x1 + +
    +
    + +
    + {int} y1 + +
    +
    + +
    + {int} x2 + +
    +
    + +
    + {int} y2 + +
    +
    + +
    + {int} doorX + Optional +
    +
    + +
    + {int} doorY + Optional +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + addDoor(x, y) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + clearDoors() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + create(digCallback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {function} digCallback + +
    +
    Dig callback with a signature (x, y, value). Values: 0 = empty, 1 = wall, 2 = door. Multiple doors are allowed.
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.Map.Feature.Room.createRandom(availWidth, availHeight, options) + +
    +
    + Room of random size within a given dimensions + + +
    + + + + +
    +
    Parameters:
    + +
    + availWidth + +
    +
    + +
    + availHeight + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.Map.Feature.Room.createRandomAt(x, y, dx, dy, options) + +
    +
    + Room of random size, with a given doors and direction + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + dx + +
    +
    + +
    + dy + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.Map.Feature.Room.createRandomCenter(cx, cy, options) + +
    +
    + Room of random size, positioned around center coords + + +
    + + + + +
    +
    Parameters:
    + +
    + cx + +
    +
    + +
    + cy + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + debug() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + getBottom() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + getCenter() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + getDoors() + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {function} + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + getLeft() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + getRight() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + getTop() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + isValid(isWallCallback, canBeDugCallback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + isWallCallback + +
    +
    + +
    + canBeDugCallback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Feature.html b/lib/rotjs-library/doc/symbols/ROT.Map.Feature.html new file mode 100644 index 0000000000000000000000000000000000000000..022bcb01211688587c73f78bda210ad043120ccb --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Feature.html @@ -0,0 +1,585 @@ + + + + + + + JsDoc Reference - ROT.Map.Feature + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Feature +

    + + +

    + + + + Dungeon feature; has own .create() method + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(digCallback) +
    +
    +
    <static>   +
    ROT.Map.Feature.createRandomAt(x, y, dx, dy, options) +
    +
    +
      +
    debug() +
    +
    +
      +
    isValid(canBeDugCallback) +
    +
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Feature() +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(digCallback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + digCallback + +
    +
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.Map.Feature.createRandomAt(x, y, dx, dy, options) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + dx + +
    +
    + +
    + dy + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + +
    + + + debug() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + isValid(canBeDugCallback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + canBeDugCallback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.IceyMaze.html b/lib/rotjs-library/doc/symbols/ROT.Map.IceyMaze.html new file mode 100644 index 0000000000000000000000000000000000000000..ea149f88221139be7256988501b3f0c84499a74a --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.IceyMaze.html @@ -0,0 +1,467 @@ + + + + + + + JsDoc Reference - ROT.Map.IceyMaze + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.IceyMaze +

    + + +

    + +
    Extends + ROT.Map.
    + + + Icey's Maze generator +See http://www.roguebasin.roguelikedevelopment.org/index.php?title=Simple_maze for explanation + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.IceyMaze(width, height, regularity) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.IceyMaze(width, height, regularity) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + width + +
    +
    + +
    + height + +
    +
    + +
    + regularity + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.Uniform.html b/lib/rotjs-library/doc/symbols/ROT.Map.Uniform.html new file mode 100644 index 0000000000000000000000000000000000000000..d6b17416fa3c7f072d8a42973ea10746c524ea43 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.Uniform.html @@ -0,0 +1,473 @@ + + + + + + + JsDoc Reference - ROT.Map.Uniform + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map.Uniform +

    + + +

    + +
    Extends + ROT.Map.Dungeon.
    + + + Dungeon generator which tries to fill the space evenly. Generates independent rooms and tries to connect them. + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map.Uniform(width, height, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    Create a map.
    +
    + + + +
    +
    Methods borrowed from class ROT.Map.Dungeon:
    getCorridors, getRooms
    +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map.Uniform(width, height, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + width + +
    +
    + +
    + height + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + Create a map. If the time limit has been hit, returns null. + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Map#create
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Map.html b/lib/rotjs-library/doc/symbols/ROT.Map.html new file mode 100644 index 0000000000000000000000000000000000000000..d652acb1e46f947b944a78ed35ca3f8c662645f7 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Map.html @@ -0,0 +1,454 @@ + + + + + + + JsDoc Reference - ROT.Map + + + + + + + + + + + + + +
    + +

    + + Class ROT.Map +

    + + +

    + + + + Base map generator + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Map(width, height) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    create(callback) +
    +
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Map(width, height) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {int} width + Optional, Default: ROT.DEFAULT_WIDTH +
    +
    + +
    + {int} height + Optional, Default: ROT.DEFAULT_HEIGHT +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + create(callback) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + callback + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Noise.Simplex.html b/lib/rotjs-library/doc/symbols/ROT.Noise.Simplex.html new file mode 100644 index 0000000000000000000000000000000000000000..7a1c32383b2f7c382769c4f1737480dc4b5f805e --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Noise.Simplex.html @@ -0,0 +1,454 @@ + + + + + + + JsDoc Reference - ROT.Noise.Simplex + + + + + + + + + + + + + +
    + +

    + + Class ROT.Noise.Simplex +

    + + +

    + + + + 2D simplex noise generator + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Noise.Simplex(gradients) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    get(xin, yin) +
    +
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Noise.Simplex(gradients) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {int} gradients + Optional, Default: 256 +
    +
    Random gradients
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + get(xin, yin) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + xin + +
    +
    + +
    + yin + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Noise.html b/lib/rotjs-library/doc/symbols/ROT.Noise.html new file mode 100644 index 0000000000000000000000000000000000000000..9397eacbe198df2d2f57945fb2619644e90fe2e9 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Noise.html @@ -0,0 +1,443 @@ + + + + + + + JsDoc Reference - ROT.Noise + + + + + + + + + + + + + +
    + +

    + + Class ROT.Noise +

    + + +

    + + + + Base noise generator + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Noise() +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    get(x, y) +
    +
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Noise() +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + get(x, y) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + x + +
    +
    + +
    + y + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Path.AStar.html b/lib/rotjs-library/doc/symbols/ROT.Path.AStar.html new file mode 100644 index 0000000000000000000000000000000000000000..8e54de91c51e3b9adc8673ef37ccc94ebe16baba --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Path.AStar.html @@ -0,0 +1,498 @@ + + + + + + + JsDoc Reference - ROT.Path.AStar + + + + + + + + + + + + + +
    + +

    + + Class ROT.Path.AStar +

    + + +

    + +
    Extends + ROT.Path.
    + + + Simplified A* algorithm: all edges have a value of 1 + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Path.AStar(toX, toY, passableCallback, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    compute(fromX, fromY, callback) +
    +
    Compute a path from a given point
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Path.AStar(toX, toY, passableCallback, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + toX + +
    +
    + +
    + toY + +
    +
    + +
    + passableCallback + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Path
    + +
    + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + compute(fromX, fromY, callback) + +
    +
    + Compute a path from a given point + + +
    + + + + +
    +
    Parameters:
    + +
    + fromX + +
    +
    + +
    + fromY + +
    +
    + +
    + callback + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Path#compute
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Path.Dijkstra.html b/lib/rotjs-library/doc/symbols/ROT.Path.Dijkstra.html new file mode 100644 index 0000000000000000000000000000000000000000..419daf9442c50cf43f7a7331555ad60634cc20ff --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Path.Dijkstra.html @@ -0,0 +1,498 @@ + + + + + + + JsDoc Reference - ROT.Path.Dijkstra + + + + + + + + + + + + + +
    + +

    + + Class ROT.Path.Dijkstra +

    + + +

    + +
    Extends + ROT.Path.
    + + + Simplified Dijkstra's algorithm: all edges have a value of 1 + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Path.Dijkstra(toX, toY, passableCallback, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    compute(fromX, fromY, callback) +
    +
    Compute a path from a given point
    +
    + + + +
    + +
    + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Path.Dijkstra(toX, toY, passableCallback, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + toX + +
    +
    + +
    + toY + +
    +
    + +
    + passableCallback + +
    +
    + +
    + options + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Path
    + +
    + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + compute(fromX, fromY, callback) + +
    +
    + Compute a path from a given point + + +
    + + + + +
    +
    Parameters:
    + +
    + fromX + +
    +
    + +
    + fromY + +
    +
    + +
    + callback + +
    +
    + +
    + + + + + + + +
    +
    See:
    + +
    ROT.Path#compute
    + +
    + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Path.html b/lib/rotjs-library/doc/symbols/ROT.Path.html new file mode 100644 index 0000000000000000000000000000000000000000..845bc7fb1b9385eca2960e5947957751d9051a2d --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Path.html @@ -0,0 +1,484 @@ + + + + + + + JsDoc Reference - ROT.Path + + + + + + + + + + + + + +
    + +

    + + Class ROT.Path +

    + + +

    + + + + Abstract pathfinder + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Path(toX, toY, passableCallback, options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    compute(fromX, fromY, callback) +
    +
    Compute a path from a given point
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Path(toX, toY, passableCallback, options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {int} toX + +
    +
    Target X coord
    + +
    + {int} toY + +
    +
    Target Y coord
    + +
    + {function} passableCallback + +
    +
    Callback to determine map passability
    + +
    + {object} options + Optional +
    +
    + +
    + {int} options.topology + Optional, Default: 8 +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + compute(fromX, fromY, callback) + +
    +
    + Compute a path from a given point + + +
    + + + + +
    +
    Parameters:
    + +
    + {int} fromX + +
    +
    + +
    + {int} fromY + +
    +
    + +
    + {function} callback + +
    +
    Will be called for every path item with arguments "x" and "y"
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.RNG.html b/lib/rotjs-library/doc/symbols/ROT.RNG.html new file mode 100644 index 0000000000000000000000000000000000000000..495ca965ee1a94f671c07d48cea4ea7d5e398911 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.RNG.html @@ -0,0 +1,757 @@ + + + + + + + JsDoc Reference - ROT.RNG + + + + + + + + + + + + + +
    + +

    + + Namespace ROT.RNG +

    + + +

    + + + + This code is an implementation of Alea algorithm; (C) 2010 Johannes Baagøe. +Alea is licensed according to the http://en.wikipedia.org/wiki/MIT_License. + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Namespace Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.RNG +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
    <static>   +
    ROT.RNG.getNormal(mean, stddev) +
    +
    +
    <static>   +
    ROT.RNG.getPercentage() +
    +
    +
    <static>   +
    ROT.RNG.getSeed() +
    +
    +
    <static>   +
    ROT.RNG.getState() +
    +
    Get RNG state.
    +
    <static>   +
    ROT.RNG.getUniform() +
    +
    +
    <static>   +
    ROT.RNG.getWeightedValue(data) +
    +
    +
    <static>   +
    ROT.RNG.setSeed(seed) +
    +
    +
    <static>   +
    ROT.RNG.setState(state) +
    +
    Set a previously retrieved state.
    +
    + + + + + + + + + +
    +
    + Namespace Detail +
    + +
    + ROT.RNG +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    <static> + + {float} + ROT.RNG.getNormal(mean, stddev) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {float} mean + Optional, Default: 0 +
    +
    Mean value
    + +
    + {float} stddev + Optional, Default: 1 +
    +
    Standard deviation. ~95% of the absolute values will be lower than 2*stddev.
    + +
    + + + + + +
    +
    Returns:
    + +
    {float} A normally distributed pseudorandom value
    + +
    + + + + +
    + + +
    <static> + + {int} + ROT.RNG.getPercentage() + +
    +
    + + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {int} Pseudorandom value [1,100] inclusive, uniformly distributed
    + +
    + + + + +
    + + +
    <static> + + {number} + ROT.RNG.getSeed() + +
    +
    + + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {number}
    + +
    + + + + +
    + + +
    <static> + + {?} + ROT.RNG.getState() + +
    +
    + Get RNG state. Useful for storing the state and re-setting it via setState. + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {?} Internal state
    + +
    + + + + +
    + + +
    <static> + + {float} + ROT.RNG.getUniform() + +
    +
    + + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {float} Pseudorandom value [0,1), uniformly distributed
    + +
    + + + + +
    + + +
    <static> + + {string} + ROT.RNG.getWeightedValue(data) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {object} data + +
    +
    key=whatever, value=weight (relative probability)
    + +
    + + + + + +
    +
    Returns:
    + +
    {string} whatever
    + +
    + + + + +
    + + +
    <static> + + + ROT.RNG.setSeed(seed) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {number} seed + +
    +
    Seed the number generator
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.RNG.setState(state) + +
    +
    + Set a previously retrieved state. + + +
    + + + + +
    +
    Parameters:
    + +
    + {?} state + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Scheduler.html b/lib/rotjs-library/doc/symbols/ROT.Scheduler.html new file mode 100644 index 0000000000000000000000000000000000000000..c0fd1b97039100c33c01942d80d3e1fd8d0db992 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Scheduler.html @@ -0,0 +1,557 @@ + + + + + + + JsDoc Reference - ROT.Scheduler + + + + + + + + + + + + + +
    + +

    + + Class ROT.Scheduler +

    + + +

    + + + + Speed-based scheduler + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    add(item) +
    +
    +
      +
    clear() +
    +
    Clear all actors
    +
      +
    next() +
    +
    Schedule next actor
    +
      +
    remove(item) +
    +
    Remove a previously added item
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.Scheduler() +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + add(item) + +
    +
    + + + +
    + + + + +
    +
    Parameters:
    + +
    + {object} item + +
    +
    anything with "getSpeed" method
    + +
    + + + + + + + + +
    + + +
    + + + clear() + +
    +
    + Clear all actors + + +
    + + + + + + + + + + + +
    + + +
    + + {object} + next() + +
    +
    + Schedule next actor + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {object}
    + +
    + + + + +
    + + +
    + + + remove(item) + +
    +
    + Remove a previously added item + + +
    + + + + +
    +
    Parameters:
    + +
    + {object} item + +
    +
    anything with "getSpeed" method
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.StringGenerator.html b/lib/rotjs-library/doc/symbols/ROT.StringGenerator.html new file mode 100644 index 0000000000000000000000000000000000000000..2f146f5f2270a0b3ab2ea48ddbeb17fc2a448a9f --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.StringGenerator.html @@ -0,0 +1,577 @@ + + + + + + + JsDoc Reference - ROT.StringGenerator + + + + + + + + + + + + + +
    + +

    + + Class ROT.StringGenerator +

    + + +

    + + + + (Markov process)-based string generator. +Copied from a RogueBasin article. +Offers configurable order and prior. + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Class Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.StringGenerator(options) +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      +
    clear() +
    +
    Remove all learning data
    +
      + +
    +
      + +
    +
      +
    observe(string) +
    +
    Observe (learn) a string from a training set
    +
    + + + + + + + + + +
    +
    + Class Detail +
    + +
    + ROT.StringGenerator(options) +
    + +
    + + +
    + + + + + +
    +
    Parameters:
    + +
    + {object} options + Optional +
    +
    + +
    + {bool} options.words + Optional, Default: false +
    +
    Use word mode?
    + +
    + {int} options.order + Optional, Default: 3 +
    +
    + +
    + {float} options.prior + Optional, Default: 0.001 +
    +
    + +
    + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    + + + clear() + +
    +
    + Remove all learning data + + +
    + + + + + + + + + + + +
    + + +
    + + {string} + generate() + +
    +
    + + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {string} Generated string
    + +
    + + + + +
    + + +
    + + + getStats() + +
    +
    + + + +
    + + + + + + + + + + + +
    + + +
    + + + observe(string) + +
    +
    + Observe (learn) a string from a training set + + +
    + + + + +
    +
    Parameters:
    + +
    + string + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.Text.html b/lib/rotjs-library/doc/symbols/ROT.Text.html new file mode 100644 index 0000000000000000000000000000000000000000..7534cc6cb7c71c737a2f2a64e258efd0f9ac9162 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.Text.html @@ -0,0 +1,494 @@ + + + + + + + JsDoc Reference - ROT.Text + + + + + + + + + + + + + +
    + +

    + + Namespace ROT.Text +

    + + +

    + + + + Contains text tokenization and breaking routines + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Namespace Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT.Text +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
    <static>   +
    ROT.Text.measure(str, maxWidth) +
    +
    Measure size of a resulting text block
    +
    <static>   +
    ROT.Text.tokenize(str, maxWidth) +
    +
    Convert string to a series of a formatting commands
    +
    + + + + + + + + + +
    +
    + Namespace Detail +
    + +
    + ROT.Text +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + + + + +
    + Method Detail +
    + + +
    <static> + + + ROT.Text.measure(str, maxWidth) + +
    +
    + Measure size of a resulting text block + + +
    + + + + +
    +
    Parameters:
    + +
    + str + +
    +
    + +
    + maxWidth + +
    +
    + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.Text.tokenize(str, maxWidth) + +
    +
    + Convert string to a series of a formatting commands + + +
    + + + + +
    +
    Parameters:
    + +
    + str + +
    +
    + +
    + maxWidth + +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/ROT.html b/lib/rotjs-library/doc/symbols/ROT.html new file mode 100644 index 0000000000000000000000000000000000000000..f5f6d6006da802221c31b6a2676f1ab68f4d2484 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/ROT.html @@ -0,0 +1,5448 @@ + + + + + + + JsDoc Reference - ROT + + + + + + + + + + + + + +
    + +

    + + Namespace ROT +

    + + +

    + + + + Top-level ROT namespace + + +
    Defined in: <rot.js>. + +

    + + + + + + + + + + + + + + + + + +
    Namespace Summary
    Constructor AttributesConstructor Name and Description
      +
    + ROT +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Field Summary
    Field AttributesField Name and Description
    <static>   +
    + ROT.DEFAULT_HEIGHT +
    +
    Default height for display and map generators
    +
    <static>   +
    + ROT.DEFAULT_WIDTH +
    +
    Default with for display and map generators
    +
    <static>   +
    + ROT.DIRS +
    +
    Directional constants.
    +
    <static>   +
    + ROT.VK_0 +
    +
    +
    <static>   +
    + ROT.VK_1 +
    +
    +
    <static>   +
    + ROT.VK_2 +
    +
    +
    <static>   +
    + ROT.VK_3 +
    +
    +
    <static>   +
    + ROT.VK_4 +
    +
    +
    <static>   +
    + ROT.VK_5 +
    +
    +
    <static>   +
    + ROT.VK_6 +
    +
    +
    <static>   +
    + ROT.VK_7 +
    +
    +
    <static>   +
    + ROT.VK_8 +
    +
    +
    <static>   +
    + ROT.VK_9 +
    +
    +
    <static>   +
    + ROT.VK_A +
    +
    +
    <static>   +
    + ROT.VK_ACCEPT +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_ADD +
    +
    + on the numeric keypad.
    +
    <static>   +
    + ROT.VK_ALT +
    +
    Alt (Option on Mac) key.
    +
    <static>   +
    + ROT.VK_ALTGR +
    +
    AltGr key on Linux.
    +
    <static>   +
    + ROT.VK_AMPERSAND +
    +
    Ampersand (&) key.
    +
    <static>   +
    + ROT.VK_AT +
    +
    Atmark (@) key.
    +
    <static>   +
    + ROT.VK_B +
    +
    +
    <static>   +
    + ROT.VK_BACK_QUOTE +
    +
    Back tick (`) key.
    +
    <static>   +
    + ROT.VK_BACK_SLASH +
    +
    Back slash (\) key.
    +
    <static>   +
    + ROT.VK_BACK_SPACE +
    +
    Backspace key.
    +
    <static>   +
    + ROT.VK_C +
    +
    +
    <static>   +
    + ROT.VK_CANCEL +
    +
    Cancel key.
    +
    <static>   +
    + ROT.VK_CAPS_LOCK +
    +
    Caps lock.
    +
    <static>   +
    + ROT.VK_CIRCUMFLEX +
    +
    Circumflex (^) key.
    +
    <static>   +
    + ROT.VK_CLEAR +
    +
    5 key on Numpad when NumLock is unlocked.
    +
    <static>   + +
    Close square bracket (]) key.
    +
    <static>   + +
    Close curly bracket (}) key.
    +
    <static>   +
    + ROT.VK_CLOSE_PAREN +
    +
    Close parenthesis ()) key.
    +
    <static>   +
    + ROT.VK_COLON +
    +
    Colon (:) key.
    +
    <static>   +
    + ROT.VK_COMMA +
    +
    Comma (,) key.
    +
    <static>   +
    + ROT.VK_CONTEXT_MENU +
    +
    +
    <static>   +
    + ROT.VK_CONTROL +
    +
    Control key.
    +
    <static>   +
    + ROT.VK_CONVERT +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_D +
    +
    +
    <static>   +
    + ROT.VK_DECIMAL +
    +
    Decimal point on the numeric keypad.
    +
    <static>   +
    + ROT.VK_DELETE +
    +
    Del(ete) key.
    +
    <static>   +
    + ROT.VK_DIVIDE +
    +
    / on the numeric keypad.
    +
    <static>   +
    + ROT.VK_DOLLAR +
    +
    Dollar sign ($) key.
    +
    <static>   +
    + ROT.VK_DOUBLE_QUOTE +
    +
    Double quote () key.
    +
    <static>   +
    + ROT.VK_DOWN +
    +
    Down arrow.
    +
    <static>   +
    + ROT.VK_E +
    +
    +
    <static>   +
    + ROT.VK_EISU +
    +
    英数 key on Japanese Mac keyboard.
    +
    <static>   +
    + ROT.VK_END +
    +
    End key.
    +
    <static>   +
    + ROT.VK_ENTER +
    +
    Reserved, but not used.
    +
    <static>   +
    + ROT.VK_EQUALS +
    +
    Equals (=) key.
    +
    <static>   +
    + ROT.VK_ESCAPE +
    +
    Escape key.
    +
    <static>   +
    + ROT.VK_EXCLAMATION +
    +
    Exclamation (!) key.
    +
    <static>   +
    + ROT.VK_EXECUTE +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_F +
    +
    +
    <static>   +
    + ROT.VK_F1 +
    +
    F1 key.
    +
    <static>   +
    + ROT.VK_F10 +
    +
    F10 key.
    +
    <static>   +
    + ROT.VK_F11 +
    +
    F11 key.
    +
    <static>   +
    + ROT.VK_F12 +
    +
    F12 key.
    +
    <static>   +
    + ROT.VK_F13 +
    +
    F13 key.
    +
    <static>   +
    + ROT.VK_F14 +
    +
    F14 key.
    +
    <static>   +
    + ROT.VK_F15 +
    +
    F15 key.
    +
    <static>   +
    + ROT.VK_F16 +
    +
    F16 key.
    +
    <static>   +
    + ROT.VK_F17 +
    +
    F17 key.
    +
    <static>   +
    + ROT.VK_F18 +
    +
    F18 key.
    +
    <static>   +
    + ROT.VK_F19 +
    +
    F19 key.
    +
    <static>   +
    + ROT.VK_F2 +
    +
    F2 key.
    +
    <static>   +
    + ROT.VK_F20 +
    +
    F20 key.
    +
    <static>   +
    + ROT.VK_F21 +
    +
    F21 key.
    +
    <static>   +
    + ROT.VK_F22 +
    +
    F22 key.
    +
    <static>   +
    + ROT.VK_F23 +
    +
    F23 key.
    +
    <static>   +
    + ROT.VK_F24 +
    +
    F24 key.
    +
    <static>   +
    + ROT.VK_F3 +
    +
    F3 key.
    +
    <static>   +
    + ROT.VK_F4 +
    +
    F4 key.
    +
    <static>   +
    + ROT.VK_F5 +
    +
    F5 key.
    +
    <static>   +
    + ROT.VK_F6 +
    +
    F6 key.
    +
    <static>   +
    + ROT.VK_F7 +
    +
    F7 key.
    +
    <static>   +
    + ROT.VK_F8 +
    +
    F8 key.
    +
    <static>   +
    + ROT.VK_F9 +
    +
    F9 key.
    +
    <static>   +
    + ROT.VK_FINAL +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_G +
    +
    +
    <static>   +
    + ROT.VK_GREATER_THAN +
    +
    Greater-than (>) key.
    +
    <static>   +
    + ROT.VK_H +
    +
    +
    <static>   +
    + ROT.VK_HANGUL +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_HANJA +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_HASH +
    +
    Hash (#) key.
    +
    <static>   +
    + ROT.VK_HELP +
    +
    Help key.
    +
    <static>   +
    + ROT.VK_HOME +
    +
    Home key.
    +
    <static>   +
    + ROT.VK_HYPHEN_MINUS +
    +
    Hyphen-US/docs/Minus (-) key.
    +
    <static>   +
    + ROT.VK_I +
    +
    +
    <static>   +
    + ROT.VK_INSERT +
    +
    Ins(ert) key.
    +
    <static>   +
    + ROT.VK_J +
    +
    +
    <static>   +
    + ROT.VK_JUNJA +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_K +
    +
    +
    <static>   +
    + ROT.VK_KANA +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_KANJI +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_L +
    +
    +
    <static>   +
    + ROT.VK_LEFT +
    +
    Left arrow.
    +
    <static>   +
    + ROT.VK_LESS_THAN +
    +
    Less-than (<) key.
    +
    <static>   +
    + ROT.VK_M +
    +
    +
    <static>   +
    + ROT.VK_META +
    +
    Meta key on Linux, Command key on Mac.
    +
    <static>   +
    + ROT.VK_MODECHANGE +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_MULTIPLY +
    +
    on the numeric keypad.
    +
    <static>   +
    + ROT.VK_N +
    +
    +
    <static>   +
    + ROT.VK_NONCONVERT +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_NUM_LOCK +
    +
    Num Lock key.
    +
    <static>   +
    + ROT.VK_NUMPAD0 +
    +
    0 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD1 +
    +
    1 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD2 +
    +
    2 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD3 +
    +
    3 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD4 +
    +
    4 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD5 +
    +
    5 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD6 +
    +
    6 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD7 +
    +
    7 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD8 +
    +
    8 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_NUMPAD9 +
    +
    9 on the numeric keypad.
    +
    <static>   +
    + ROT.VK_O +
    +
    +
    <static>   +
    + ROT.VK_OPEN_BRACKET +
    +
    Open square bracket ([) key.
    +
    <static>   + +
    Open curly bracket ({) key.
    +
    <static>   +
    + ROT.VK_OPEN_PAREN +
    +
    Open parenthesis (() key.
    +
    <static>   +
    + ROT.VK_P +
    +
    +
    <static>   +
    + ROT.VK_PAGE_DOWN +
    +
    Page Down key.
    +
    <static>   +
    + ROT.VK_PAGE_UP +
    +
    Page Up key.
    +
    <static>   +
    + ROT.VK_PAUSE +
    +
    Pause key.
    +
    <static>   +
    + ROT.VK_PERCENT +
    +
    Percent (%) key.
    +
    <static>   +
    + ROT.VK_PERIOD +
    +
    Period (.
    +
    <static>   +
    + ROT.VK_PIPE +
    +
    Pipe (|) key.
    +
    <static>   +
    + ROT.VK_PLUS +
    +
    Plus (+) key.
    +
    <static>   +
    + ROT.VK_PRINT +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_PRINTSCREEN +
    +
    Print Screen key.
    +
    <static>   +
    + ROT.VK_Q +
    +
    +
    <static>   + +
    Question mark (?) key.
    +
    <static>   +
    + ROT.VK_QUOTE +
    +
    Quote (''') key.
    +
    <static>   +
    + ROT.VK_R +
    +
    +
    <static>   +
    + ROT.VK_RETURN +
    +
    Return/enter key on the main keyboard.
    +
    <static>   +
    + ROT.VK_RIGHT +
    +
    Right arrow.
    +
    <static>   +
    + ROT.VK_S +
    +
    +
    <static>   +
    + ROT.VK_SCROLL_LOCK +
    +
    Scroll Lock key.
    +
    <static>   +
    + ROT.VK_SELECT +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_SEMICOLON +
    +
    Semicolon (;) key.
    +
    <static>   +
    + ROT.VK_SEPARATOR +
    +
    +
    <static>   +
    + ROT.VK_SHIFT +
    +
    Shift key.
    +
    <static>   +
    + ROT.VK_SLASH +
    +
    Slash (/) key.
    +
    <static>   +
    + ROT.VK_SLEEP +
    +
    Linux support for this keycode was added in Gecko 4.0.
    +
    <static>   +
    + ROT.VK_SPACE +
    +
    Space bar.
    +
    <static>   +
    + ROT.VK_SUBTRACT +
    +
    - on the numeric keypad.
    +
    <static>   +
    + ROT.VK_T +
    +
    +
    <static>   +
    + ROT.VK_TAB +
    +
    Tab key.
    +
    <static>   +
    + ROT.VK_TILDE +
    +
    Tilde (~) key.
    +
    <static>   +
    + ROT.VK_U +
    +
    +
    <static>   +
    + ROT.VK_UNDERSCORE +
    +
    Underscore (_) key.
    +
    <static>   +
    + ROT.VK_UP +
    +
    Up arrow.
    +
    <static>   +
    + ROT.VK_V +
    +
    +
    <static>   +
    + ROT.VK_W +
    +
    +
    <static>   +
    + ROT.VK_WIN +
    +
    Windows logo key on Windows.
    +
    <static>   +
    + ROT.VK_X +
    +
    +
    <static>   +
    + ROT.VK_Y +
    +
    +
    <static>   +
    + ROT.VK_Z +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
    <static>   +
    ROT.isSupported() +
    +
    +
    + + + + + + + + + +
    +
    + Namespace Detail +
    + +
    + ROT +
    + +
    + + +
    + + + + + + + + + + + + +
    + + + + +
    + Field Detail +
    + + +
    <static> + + + ROT.DEFAULT_HEIGHT + +
    +
    + Default height for display and map generators + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.DEFAULT_WIDTH + +
    +
    + Default with for display and map generators + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.DIRS + +
    +
    + Directional constants. Ordering is important! + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_0 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_1 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_2 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_3 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_4 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_5 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_6 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_7 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_8 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_9 + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_A + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_ACCEPT + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_ADD + +
    +
    + + on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_ALT + +
    +
    + Alt (Option on Mac) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_ALTGR + +
    +
    + AltGr key on Linux. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_AMPERSAND + +
    +
    + Ampersand (&) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_AT + +
    +
    + Atmark (@) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_B + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_BACK_QUOTE + +
    +
    + Back tick (`) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_BACK_SLASH + +
    +
    + Back slash (\) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_BACK_SPACE + +
    +
    + Backspace key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_C + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CANCEL + +
    +
    + Cancel key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CAPS_LOCK + +
    +
    + Caps lock. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CIRCUMFLEX + +
    +
    + Circumflex (^) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CLEAR + +
    +
    + 5 key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CLOSE_BRACKET + +
    +
    + Close square bracket (]) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CLOSE_CURLY_BRACKET + +
    +
    + Close curly bracket (}) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CLOSE_PAREN + +
    +
    + Close parenthesis ()) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_COLON + +
    +
    + Colon (:) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_COMMA + +
    +
    + Comma (,) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CONTEXT_MENU + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CONTROL + +
    +
    + Control key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_CONVERT + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_D + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_DECIMAL + +
    +
    + Decimal point on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_DELETE + +
    +
    + Del(ete) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_DIVIDE + +
    +
    + / on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_DOLLAR + +
    +
    + Dollar sign ($) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_DOUBLE_QUOTE + +
    +
    + Double quote () key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_DOWN + +
    +
    + Down arrow. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_E + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_EISU + +
    +
    + 英数 key on Japanese Mac keyboard. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_END + +
    +
    + End key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_ENTER + +
    +
    + Reserved, but not used. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_EQUALS + +
    +
    + Equals (=) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_ESCAPE + +
    +
    + Escape key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_EXCLAMATION + +
    +
    + Exclamation (!) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_EXECUTE + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F1 + +
    +
    + F1 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F10 + +
    +
    + F10 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F11 + +
    +
    + F11 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F12 + +
    +
    + F12 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F13 + +
    +
    + F13 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F14 + +
    +
    + F14 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F15 + +
    +
    + F15 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F16 + +
    +
    + F16 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F17 + +
    +
    + F17 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F18 + +
    +
    + F18 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F19 + +
    +
    + F19 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F2 + +
    +
    + F2 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F20 + +
    +
    + F20 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F21 + +
    +
    + F21 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F22 + +
    +
    + F22 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F23 + +
    +
    + F23 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F24 + +
    +
    + F24 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F3 + +
    +
    + F3 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F4 + +
    +
    + F4 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F5 + +
    +
    + F5 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F6 + +
    +
    + F6 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F7 + +
    +
    + F7 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F8 + +
    +
    + F8 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_F9 + +
    +
    + F9 key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_FINAL + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_G + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_GREATER_THAN + +
    +
    + Greater-than (>) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_H + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_HANGUL + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_HANJA + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_HASH + +
    +
    + Hash (#) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_HELP + +
    +
    + Help key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_HOME + +
    +
    + Home key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_HYPHEN_MINUS + +
    +
    + Hyphen-US/docs/Minus (-) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_I + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_INSERT + +
    +
    + Ins(ert) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_J + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_JUNJA + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_K + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_KANA + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_KANJI + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_L + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_LEFT + +
    +
    + Left arrow. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_LESS_THAN + +
    +
    + Less-than (<) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_M + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_META + +
    +
    + Meta key on Linux, Command key on Mac. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_MODECHANGE + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_MULTIPLY + +
    +
    + on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_N + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NONCONVERT + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUM_LOCK + +
    +
    + Num Lock key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD0 + +
    +
    + 0 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD1 + +
    +
    + 1 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD2 + +
    +
    + 2 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD3 + +
    +
    + 3 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD4 + +
    +
    + 4 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD5 + +
    +
    + 5 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD6 + +
    +
    + 6 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD7 + +
    +
    + 7 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD8 + +
    +
    + 8 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_NUMPAD9 + +
    +
    + 9 on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_O + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_OPEN_BRACKET + +
    +
    + Open square bracket ([) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_OPEN_CURLY_BRACKET + +
    +
    + Open curly bracket ({) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_OPEN_PAREN + +
    +
    + Open parenthesis (() key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_P + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PAGE_DOWN + +
    +
    + Page Down key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PAGE_UP + +
    +
    + Page Up key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PAUSE + +
    +
    + Pause key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PERCENT + +
    +
    + Percent (%) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PERIOD + +
    +
    + Period (.) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PIPE + +
    +
    + Pipe (|) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PLUS + +
    +
    + Plus (+) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PRINT + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_PRINTSCREEN + +
    +
    + Print Screen key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_Q + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_QUESTION_MARK + +
    +
    + Question mark (?) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_QUOTE + +
    +
    + Quote (''') key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_R + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_RETURN + +
    +
    + Return/enter key on the main keyboard. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_RIGHT + +
    +
    + Right arrow. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_S + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SCROLL_LOCK + +
    +
    + Scroll Lock key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SELECT + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SEMICOLON + +
    +
    + Semicolon (;) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SEPARATOR + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SHIFT + +
    +
    + Shift key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SLASH + +
    +
    + Slash (/) key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SLEEP + +
    +
    + Linux support for this keycode was added in Gecko 4.0. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SPACE + +
    +
    + Space bar. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_SUBTRACT + +
    +
    + - on the numeric keypad. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_T + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_TAB + +
    +
    + Tab key. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_TILDE + +
    +
    + Tilde (~) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_U + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_UNDERSCORE + +
    +
    + Underscore (_) key. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_UP + +
    +
    + Up arrow. + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_V + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_W + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_WIN + +
    +
    + Windows logo key on Windows. Or Super or Hyper key on Linux. Requires Gecko 15.0 + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_X + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_Y + +
    +
    + + + +
    + + + + + + + + +
    + + +
    <static> + + + ROT.VK_Z + +
    +
    + + + +
    + + + + + + + + + + + + + + +
    + Method Detail +
    + + +
    <static> + + {bool} + ROT.isSupported() + +
    +
    + + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {bool} Is rot.js supported by this browser?
    + +
    + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/String.html b/lib/rotjs-library/doc/symbols/String.html new file mode 100644 index 0000000000000000000000000000000000000000..0a541af01baebc89dc37f50624fdf0e23c08739e --- /dev/null +++ b/lib/rotjs-library/doc/symbols/String.html @@ -0,0 +1,585 @@ + + + + + + + JsDoc Reference - String + + + + + + + + + + + + + +
    + +

    + + Built-In Namespace String +

    + + +

    + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    Method Summary
    Method AttributesMethod Name and Description
      + +
    +
    <static>   +
    String.format(template, argv) +
    +
    Format a string in a flexible way.
    +
      +
    format() +
    +
    Convenience shortcut to String.format(this)
    +
      +
    lpad(character, count) +
    +
    Left pad
    +
      +
    rpad(character, count) +
    +
    Right pad
    +
    + + + + + + + + + + + + + + + +
    + Method Detail +
    + + +
    + + {string} + capitalize() + +
    +
    + + +
    + Defined in: <rot.js>. + + +
    + + + + + + + + +
    +
    Returns:
    + +
    {string} First letter capitalized
    + +
    + + + + +
    + + +
    <static> + + + String.format(template, argv) + +
    +
    + Format a string in a flexible way. Scans for %s strings and replaces them with arguments. List of patterns is modifiable via String.format.map. + +
    + Defined in: <rot.js>. + + +
    + + + + +
    +
    Parameters:
    + +
    + {string} template + +
    +
    + +
    + {any} argv + Optional +
    +
    + +
    + + + + + + + + +
    + + +
    + + + format() + +
    +
    + Convenience shortcut to String.format(this) + +
    + Defined in: <rot.js>. + + +
    + + + + + + + + + + + +
    + + +
    + + + lpad(character, count) + +
    +
    + Left pad + +
    + Defined in: <rot.js>. + + +
    + + + + +
    +
    Parameters:
    + +
    + {string} character + Optional, Default: "0" +
    +
    + +
    + {int} count + Optional, Default: 2 +
    +
    + +
    + + + + + + + + +
    + + +
    + + + rpad(character, count) + +
    +
    + Right pad + +
    + Defined in: <rot.js>. + + +
    + + + + +
    +
    Parameters:
    + +
    + {string} character + Optional, Default: "0" +
    +
    + +
    + {int} count + Optional, Default: 2 +
    +
    + +
    + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:30 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/doc/symbols/_global_.html b/lib/rotjs-library/doc/symbols/_global_.html new file mode 100644 index 0000000000000000000000000000000000000000..1aa499f2c2e26abac89df8335b866ec4093f7140 --- /dev/null +++ b/lib/rotjs-library/doc/symbols/_global_.html @@ -0,0 +1,319 @@ + + + + + + + JsDoc Reference - _global_ + + + + + + + + + + + + + +
    + +

    + + Built-In Namespace _global_ +

    + + +

    + + + + + + +

    + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + +
    + + Documentation generated by JsDoc Toolkit 2.4.0 on Fri Mar 08 2013 11:07:29 GMT+0100 (CET) +
    + + diff --git a/lib/rotjs-library/hp/hp.css b/lib/rotjs-library/hp/hp.css new file mode 100644 index 0000000000000000000000000000000000000000..2bba15d3fb127503f947b78ec0aa99ca0df4a45e --- /dev/null +++ b/lib/rotjs-library/hp/hp.css @@ -0,0 +1,91 @@ +@import url(http://fonts.googleapis.com/css?family=Inconsolata); + +body { + background-color: #000; + text-align: center; +} + +pre { + display: inline-block; + text-align: left; + font-family: inconsolata, monospace; + margin: 0; + line-height: 100%; +} + +pre { + font-size: 16px; +} + +@media all and (min-height: 610px) { + pre { font-size: 17px; } +} + +@media all and (min-height: 650px) { + pre { font-size: 18px; } +} + +@media all and (min-height: 700px) { + pre { font-size: 19px; } +} + +@media all and (min-height: 750px) { + pre { font-size: 20px; } +} + +@media all and (min-height: 800px) { + pre { font-size: 21px; } +} + +@media all and (min-height: 850px) { + pre { font-size: 22px; } +} + +@media all and (min-height: 900px) { + pre { font-size: 23px; } +} + +pre span { + opacity: 0.5; +} + +a { + color: #fff; + text-decoration: none; + opacity: 1; +} + +a:hover { + background-color: #333; +} + +.text { + color: #bbb; + opacity: 1; +} + +.text:first-child { + color: #fff; + text-decoration: underline; +} + +.wall { color: #666; } +.corridor { color: #ccc; } +.staircase { color: #aaa; } +.door { color: #a60; } +.trap { color: #f0f; } +.scroll { color: #fff; } +.water { color: #33f; } +.potion { color: #3ff; } + +.money, .money a { + color: #fe0; + opacity: 1; +} + +.player { color:#f00; } +.kobold { color:#3f3; } +.orc { color:#3f3; } +.goblin { color:#00f; } +.ogre { color:#3a3; } +.dragon { color:#f33; } diff --git a/lib/rotjs-library/hp/hp.js b/lib/rotjs-library/hp/hp.js new file mode 100644 index 0000000000000000000000000000000000000000..71714ef44ded620b8ff69f1437a79a75c4898ef4 --- /dev/null +++ b/lib/rotjs-library/hp/hp.js @@ -0,0 +1,97 @@ +var pre = document.querySelector("pre"); +var re = /(>)|([a-z-][a-z0-9 \.,:\(\)-]*[a-z0-9\.:])|(#+)|(\.+)|([+/])|(\$+)|(\^)|(\?)|(=+)|(!)/ig; + +var str = pre.innerHTML; +str = str.replace(re, function(match) { + var types = ["", "staircase", "text", "wall", "corridor", "door", "money", "trap", "scroll", "water", "potion"]; + for (var i=1; i"; + return str; + } + } + return match; +}); +str = str.replace("YYYY", new Date().getFullYear()); +pre.innerHTML = str; + +var links = { + "download": "https://github.com/ondras/rot.js/zipball/master", + "github": "https://github.com/ondras/rot.js", + "interactive manual": "../manual/", + "autogenerated documentation": "../doc/", + "ondrej zara": "http://ondras.zarovi.cz/", + "libtcod": "http://doryen.eptalys.net/libtcod/", + "tests": "../tests/", + "tutorial": "http://www.roguebasin.roguelikedevelopment.org/index.php?title=Rot.js_tutorial", + "$$$": "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=7WXVKF3ZJ9FZE" +}; +var spans = document.querySelectorAll("span"); +for (var i=0;i= random) { + sum2 -= random; /* sum2 = index of dot in corridors[i] */ + var span = corridors[i]; + if (sum2) { + var tmp = document.createElement("span"); + tmp.className = span.className; + tmp.innerHTML = span.innerHTML.substring(0, sum2); + span.parentNode.insertBefore(tmp, span); + } + + var node = document.createElement("span"); + node.className = monster; + node.title = monster; + node.innerHTML = p; + span.parentNode.insertBefore(node, span); + + if (sum2 < span.innerHTML.length-1) { + var tmp = document.createElement("span"); + tmp.className = span.className; + tmp.innerHTML = span.innerHTML.substring(sum2+1, span.innerHTML.length); + span.parentNode.insertBefore(tmp, span); + } + + span.parentNode.removeChild(span); + break; + } + } +} diff --git a/lib/rotjs-library/hp/index.html b/lib/rotjs-library/hp/index.html new file mode 100644 index 0000000000000000000000000000000000000000..3d2c5bec1d1aa32f11c15af166014b815a7af596 --- /dev/null +++ b/lib/rotjs-library/hp/index.html @@ -0,0 +1,47 @@ + + + + + + + +
    +                       rot.js: ROguelike Toolkit in JavaScript          ###############
    +#####                                                                   #.............#
    +#...#                                                                   #.............#
    +#...#  - Github                                                         #.............#
    +#.?.#  - Download                            ############################.............#
    +#...#  - Interactive manual                  #======.....+............../.............#
    +#+###  - Autogenerated documentation         #====.......##########.#####.............#
    +#.#    - Tests                               #===........#        #.#   ####/##########
    +#.#    - Tutorial                            #############        #.#      #.#         
    +#.#                                                               #.#      #.#         
    +#.#                                                               #.#      #.#         
    +#.#        ########################################################.#      #.#######   
    +#.#        #$$$.........+...........................................#      #......^#   
    +#.#        #............#############################################      #########   
    +#.##########............#                                                              
    +#........../............#     rot.js is a set of JavaScript libraries, designed to help
    +#.#######################     with a roguelike development in browser environment.     
    +#.#                                                                                    
    +#.#                                                                                    
    +#.#  rot.js is modelled after libtcod and offers the following features and concepts:  
    +#.#                                                                                    
    +#.##   - JS prototype enhancements                          #########         #########
    +#..##  - RNG, Map generation, FOV, Lighting                 #.......###########.......#
    +##..#  - Pathfinding, turn scheduling                       #......./........./.......#
    + ##.#  - Canvas-based ASCII display                 #########.......###########.......#
    +##..#                                               #.......+.......#         #.......#
    +#..##  - Does not depend on any JS library          #.###############         #.......#
    +#.##   - Open-source software, BSD License          #.#              ##########.......#
    +#.#                                                 #.#              #......../.......#
    +#.#            ######################################.################.########.......#
    +#.#            #.......................................................#      #.......#
    +#.#            #.#######################################################      #.......#
    +#.##############.#                                                            #...>...#
    +#!...............#                                                            #.......#
    +##################         rot.js is (C) 2012-YYYY Ondrej Zara                #########
    +
    + + + diff --git a/lib/rotjs-library/index.html b/lib/rotjs-library/index.html new file mode 100644 index 0000000000000000000000000000000000000000..cd98297120fae2dfdff9e5917424efee5419d616 --- /dev/null +++ b/lib/rotjs-library/index.html @@ -0,0 +1,7 @@ + + + + + + + diff --git a/lib/rotjs-library/license.txt b/lib/rotjs-library/license.txt new file mode 100644 index 0000000000000000000000000000000000000000..035c4f402a2693f505b9f5fbe8917eb275edc037 --- /dev/null +++ b/lib/rotjs-library/license.txt @@ -0,0 +1,25 @@ +Copyright (c) 2012-now(), Ondrej Zara +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of Ondrej Zara nor the names of its contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/lib/rotjs-library/manual/index.html b/lib/rotjs-library/manual/index.html new file mode 100644 index 0000000000000000000000000000000000000000..48ce0a1d0ee5f72b346bbbcc7e041e1375aadb7e --- /dev/null +++ b/lib/rotjs-library/manual/index.html @@ -0,0 +1,58 @@ + + + + + + + rot.js interactive manual + + +

    rot.js interactive manual

    + + + +
    + + + + + + + + + diff --git a/lib/rotjs-library/manual/java.txt b/lib/rotjs-library/manual/java.txt new file mode 100644 index 0000000000000000000000000000000000000000..82ac00b18f00259d345bded4c56980d91d68e4e6 --- /dev/null +++ b/lib/rotjs-library/manual/java.txt @@ -0,0 +1,4024 @@ +AbstractAction +AbstractAnnotationValueVisitor6 +AbstractAnnotationValueVisitor7 +AbstractBorder +AbstractButton +AbstractCellEditor +AbstractCollection +AbstractColorChooserPanel +AbstractDocument +AbstractDocument.AttributeContext +AbstractDocument.Content +AbstractDocument.ElementEdit +AbstractElementVisitor6 +AbstractElementVisitor7 +AbstractExecutorService +AbstractInterruptibleChannel +AbstractLayoutCache +AbstractLayoutCache.NodeDimensions +AbstractList +AbstractListModel +AbstractMap +AbstractMap.SimpleEntry +AbstractMap.SimpleImmutableEntry +AbstractMarshallerImpl +AbstractMethodError +AbstractOwnableSynchronizer +AbstractPreferences +AbstractProcessor +AbstractQueue +AbstractQueuedLongSynchronizer +AbstractQueuedSynchronizer +AbstractRegionPainter +AbstractRegionPainter.PaintContext +AbstractRegionPainter.PaintContext.CacheMode +AbstractScriptEngine +AbstractSelectableChannel +AbstractSelectionKey +AbstractSelector +AbstractSequentialList +AbstractSet +AbstractSpinnerModel +AbstractTableModel +AbstractTypeVisitor6 +AbstractTypeVisitor7 +AbstractUndoableEdit +AbstractUnmarshallerImpl +AbstractWriter +AcceptPendingException +AccessControlContext +AccessControlException +AccessController +AccessDeniedException +AccessException +Accessible +AccessibleAction +AccessibleAttributeSequence +AccessibleBundle +AccessibleComponent +AccessibleContext +AccessibleEditableText +AccessibleExtendedComponent +AccessibleExtendedTable +AccessibleExtendedText +AccessibleHyperlink +AccessibleHypertext +AccessibleIcon +AccessibleKeyBinding +AccessibleObject +AccessibleRelation +AccessibleRelationSet +AccessibleResourceBundle +AccessibleRole +AccessibleSelection +AccessibleState +AccessibleStateSet +AccessibleStreamable +AccessibleTable +AccessibleTableModelChange +AccessibleText +AccessibleTextSequence +AccessibleValue +AccessMode +AccountException +AccountExpiredException +AccountLockedException +AccountNotFoundException +Acl +AclEntry +AclEntry +AclEntry.Builder +AclEntryFlag +AclEntryPermission +AclEntryType +AclFileAttributeView +AclNotFoundException +Action +Action +ActionEvent +ActionListener +ActionMap +ActionMapUIResource +Activatable +ActivateFailedException +ActivationDataFlavor +ActivationDesc +ActivationException +ActivationGroup +ActivationGroup_Stub +ActivationGroupDesc +ActivationGroupDesc.CommandEnvironment +ActivationGroupID +ActivationID +ActivationInstantiator +ActivationMonitor +ActivationSystem +Activator +ACTIVE +ActiveEvent +ACTIVITY_COMPLETED +ACTIVITY_REQUIRED +ActivityCompletedException +ActivityRequiredException +AdapterActivator +AdapterActivatorOperations +AdapterAlreadyExists +AdapterAlreadyExistsHelper +AdapterInactive +AdapterInactiveHelper +AdapterManagerIdHelper +AdapterNameHelper +AdapterNonExistent +AdapterNonExistentHelper +AdapterStateHelper +AddressHelper +Addressing +AddressingFeature +AddressingFeature.Responses +Adjustable +AdjustmentEvent +AdjustmentListener +Adler32 +AEADBadTagException +AffineTransform +AffineTransformOp +AlgorithmConstraints +AlgorithmMethod +AlgorithmParameterGenerator +AlgorithmParameterGeneratorSpi +AlgorithmParameters +AlgorithmParameterSpec +AlgorithmParametersSpi +AllPermission +AlphaComposite +AlreadyBound +AlreadyBoundException +AlreadyBoundException +AlreadyBoundHelper +AlreadyBoundHolder +AlreadyConnectedException +AncestorEvent +AncestorListener +AnnotatedElement +Annotation +Annotation +AnnotationFormatError +AnnotationMirror +AnnotationTypeMismatchException +AnnotationValue +AnnotationValueVisitor +Any +AnyHolder +AnySeqHelper +AnySeqHelper +AnySeqHolder +AppConfigurationEntry +AppConfigurationEntry.LoginModuleControlFlag +Appendable +Applet +AppletContext +AppletInitializer +AppletStub +ApplicationException +Arc2D +Arc2D.Double +Arc2D.Float +Area +AreaAveragingScaleFilter +ARG_IN +ARG_INOUT +ARG_OUT +ArithmeticException +Array +Array +ArrayBlockingQueue +ArrayDeque +ArrayIndexOutOfBoundsException +ArrayList +Arrays +ArrayStoreException +ArrayType +ArrayType +AssertionError +AsyncBoxView +AsyncHandler +AsynchronousByteChannel +AsynchronousChannel +AsynchronousChannelGroup +AsynchronousChannelProvider +AsynchronousCloseException +AsynchronousFileChannel +AsynchronousServerSocketChannel +AsynchronousSocketChannel +AtomicBoolean +AtomicInteger +AtomicIntegerArray +AtomicIntegerFieldUpdater +AtomicLong +AtomicLongArray +AtomicLongFieldUpdater +AtomicMarkableReference +AtomicMoveNotSupportedException +AtomicReference +AtomicReferenceArray +AtomicReferenceFieldUpdater +AtomicStampedReference +AttachmentMarshaller +AttachmentPart +AttachmentUnmarshaller +Attr +Attribute +Attribute +Attribute +Attribute +AttributeChangeNotification +AttributeChangeNotificationFilter +AttributedCharacterIterator +AttributedCharacterIterator.Attribute +AttributedString +AttributeException +AttributeInUseException +AttributeList +AttributeList +AttributeList +AttributeListImpl +AttributeModificationException +AttributeNotFoundException +Attributes +Attributes +Attributes +Attributes.Name +Attributes2 +Attributes2Impl +AttributeSet +AttributeSet +AttributeSet.CharacterAttribute +AttributeSet.ColorAttribute +AttributeSet.FontAttribute +AttributeSet.ParagraphAttribute +AttributeSetUtilities +AttributesImpl +AttributeValueExp +AttributeView +AudioClip +AudioFileFormat +AudioFileFormat.Type +AudioFileReader +AudioFileWriter +AudioFormat +AudioFormat.Encoding +AudioInputStream +AudioPermission +AudioSystem +AuthenticationException +AuthenticationException +AuthenticationNotSupportedException +Authenticator +Authenticator.RequestorType +AuthorizeCallback +AuthPermission +AuthProvider +AutoCloseable +Autoscroll +AWTError +AWTEvent +AWTEventListener +AWTEventListenerProxy +AWTEventMulticaster +AWTException +AWTKeyStroke +AWTPermission +BackingStoreException +BAD_CONTEXT +BAD_INV_ORDER +BAD_OPERATION +BAD_PARAM +BAD_POLICY +BAD_POLICY_TYPE +BAD_POLICY_VALUE +BAD_QOS +BAD_TYPECODE +BadAttributeValueExpException +BadBinaryOpValueExpException +BadKind +BadLocationException +BadPaddingException +BadStringOperationException +BandCombineOp +BandedSampleModel +BaseRowSet +BasicArrowButton +BasicAttribute +BasicAttributes +BasicBorders +BasicBorders.ButtonBorder +BasicBorders.FieldBorder +BasicBorders.MarginBorder +BasicBorders.MenuBarBorder +BasicBorders.RadioButtonBorder +BasicBorders.RolloverButtonBorder +BasicBorders.SplitPaneBorder +BasicBorders.ToggleButtonBorder +BasicButtonListener +BasicButtonUI +BasicCheckBoxMenuItemUI +BasicCheckBoxUI +BasicColorChooserUI +BasicComboBoxEditor +BasicComboBoxEditor.UIResource +BasicComboBoxRenderer +BasicComboBoxRenderer.UIResource +BasicComboBoxUI +BasicComboPopup +BasicControl +BasicDesktopIconUI +BasicDesktopPaneUI +BasicDirectoryModel +BasicEditorPaneUI +BasicFileAttributes +BasicFileAttributeView +BasicFileChooserUI +BasicFormattedTextFieldUI +BasicGraphicsUtils +BasicHTML +BasicIconFactory +BasicInternalFrameTitlePane +BasicInternalFrameUI +BasicLabelUI +BasicListUI +BasicLookAndFeel +BasicMenuBarUI +BasicMenuItemUI +BasicMenuUI +BasicOptionPaneUI +BasicOptionPaneUI.ButtonAreaLayout +BasicPanelUI +BasicPasswordFieldUI +BasicPermission +BasicPopupMenuSeparatorUI +BasicPopupMenuUI +BasicProgressBarUI +BasicRadioButtonMenuItemUI +BasicRadioButtonUI +BasicRootPaneUI +BasicScrollBarUI +BasicScrollPaneUI +BasicSeparatorUI +BasicSliderUI +BasicSpinnerUI +BasicSplitPaneDivider +BasicSplitPaneUI +BasicStroke +BasicTabbedPaneUI +BasicTableHeaderUI +BasicTableUI +BasicTextAreaUI +BasicTextFieldUI +BasicTextPaneUI +BasicTextUI +BasicTextUI.BasicCaret +BasicTextUI.BasicHighlighter +BasicToggleButtonUI +BasicToolBarSeparatorUI +BasicToolBarUI +BasicToolTipUI +BasicTreeUI +BasicViewportUI +BatchUpdateException +BeanContext +BeanContextChild +BeanContextChildComponentProxy +BeanContextChildSupport +BeanContextContainerProxy +BeanContextEvent +BeanContextMembershipEvent +BeanContextMembershipListener +BeanContextProxy +BeanContextServiceAvailableEvent +BeanContextServiceProvider +BeanContextServiceProviderBeanInfo +BeanContextServiceRevokedEvent +BeanContextServiceRevokedListener +BeanContextServices +BeanContextServicesListener +BeanContextServicesSupport +BeanContextServicesSupport.BCSSServiceProvider +BeanContextSupport +BeanContextSupport.BCSIterator +BeanDescriptor +BeanInfo +Beans +BevelBorder +Bidi +BigDecimal +BigInteger +BinaryRefAddr +Binder +BindException +Binding +Binding +Binding +BindingHelper +BindingHolder +BindingIterator +BindingIteratorHelper +BindingIteratorHolder +BindingIteratorOperations +BindingIteratorPOA +BindingListHelper +BindingListHolder +BindingProvider +Bindings +BindingType +BindingType +BindingTypeHelper +BindingTypeHolder +BitSet +Blob +BlockingDeque +BlockingQueue +BlockView +BMPImageWriteParam +Book +Boolean +BooleanControl +BooleanControl.Type +BooleanHolder +BooleanSeqHelper +BooleanSeqHolder +BootstrapMethodError +Border +BorderFactory +BorderLayout +BorderUIResource +BorderUIResource.BevelBorderUIResource +BorderUIResource.CompoundBorderUIResource +BorderUIResource.EmptyBorderUIResource +BorderUIResource.EtchedBorderUIResource +BorderUIResource.LineBorderUIResource +BorderUIResource.MatteBorderUIResource +BorderUIResource.TitledBorderUIResource +BoundedRangeModel +Bounds +Bounds +Box +Box.Filler +BoxedValueHelper +BoxLayout +BoxView +BreakIterator +BreakIteratorProvider +BrokenBarrierException +Buffer +BufferCapabilities +BufferCapabilities.FlipContents +BufferedImage +BufferedImageFilter +BufferedImageOp +BufferedInputStream +BufferedOutputStream +BufferedReader +BufferedWriter +BufferOverflowException +BufferPoolMXBean +BufferStrategy +BufferUnderflowException +Button +ButtonGroup +ButtonModel +ButtonUI +Byte +ByteArrayInputStream +ByteArrayOutputStream +ByteBuffer +ByteChannel +ByteHolder +ByteLookupTable +ByteOrder +C14NMethodParameterSpec +CachedRowSet +CacheRequest +CacheResponse +Calendar +Callable +CallableStatement +Callback +CallbackHandler +CallSite +CancelablePrintJob +CancellationException +CancelledKeyException +CannotProceed +CannotProceedException +CannotProceedHelper +CannotProceedHolder +CannotRedoException +CannotUndoException +CanonicalizationMethod +Canvas +CardLayout +Caret +CaretEvent +CaretListener +CDATASection +CellEditor +CellEditorListener +CellRendererPane +Certificate +Certificate +Certificate +Certificate.CertificateRep +CertificateEncodingException +CertificateEncodingException +CertificateException +CertificateException +CertificateExpiredException +CertificateExpiredException +CertificateFactory +CertificateFactorySpi +CertificateNotYetValidException +CertificateNotYetValidException +CertificateParsingException +CertificateParsingException +CertificateRevokedException +CertPath +CertPath.CertPathRep +CertPathBuilder +CertPathBuilderException +CertPathBuilderResult +CertPathBuilderSpi +CertPathParameters +CertPathTrustManagerParameters +CertPathValidator +CertPathValidatorException +CertPathValidatorException.BasicReason +CertPathValidatorException.Reason +CertPathValidatorResult +CertPathValidatorSpi +CertSelector +CertStore +CertStoreException +CertStoreParameters +CertStoreSpi +ChangedCharSetException +ChangeEvent +ChangeListener +Channel +ChannelBinding +Channels +Character +Character.Subset +Character.UnicodeBlock +Character.UnicodeScript +CharacterCodingException +CharacterData +CharacterIterator +Characters +CharArrayReader +CharArrayWriter +CharBuffer +CharConversionException +CharHolder +CharSeqHelper +CharSeqHolder +CharSequence +Charset +CharsetDecoder +CharsetEncoder +CharsetProvider +Checkbox +CheckboxGroup +CheckboxMenuItem +CheckedInputStream +CheckedOutputStream +Checksum +Choice +ChoiceCallback +ChoiceFormat +Chromaticity +Cipher +CipherInputStream +CipherOutputStream +CipherSpi +Class +ClassCastException +ClassCircularityError +ClassDefinition +ClassDesc +ClassFileTransformer +ClassFormatError +ClassLoader +ClassLoaderRepository +ClassLoadingMXBean +ClassNotFoundException +ClassValue +ClientInfoStatus +ClientRequestInfo +ClientRequestInfoOperations +ClientRequestInterceptor +ClientRequestInterceptorOperations +Clip +Clipboard +ClipboardOwner +Clob +Cloneable +CloneNotSupportedException +Closeable +ClosedByInterruptException +ClosedChannelException +ClosedDirectoryStreamException +ClosedFileSystemException +ClosedSelectorException +ClosedWatchServiceException +CMMException +Codec +CodecFactory +CodecFactoryHelper +CodecFactoryOperations +CodecOperations +CoderMalfunctionError +CoderResult +CODESET_INCOMPATIBLE +CodeSets +CodeSigner +CodeSource +CodingErrorAction +CollapsedStringAdapter +CollationElementIterator +CollationKey +Collator +CollatorProvider +Collection +CollectionCertStoreParameters +Collections +Color +ColorChooserComponentFactory +ColorChooserUI +ColorConvertOp +ColorModel +ColorSelectionModel +ColorSpace +ColorSupported +ColorType +ColorUIResource +ComboBoxEditor +ComboBoxModel +ComboBoxUI +ComboPopup +COMM_FAILURE +CommandInfo +CommandMap +CommandObject +Comment +Comment +CommonDataSource +CommunicationException +Comparable +Comparator +Compilable +CompilationMXBean +CompiledScript +Compiler +Completion +CompletionHandler +Completions +CompletionService +CompletionStatus +CompletionStatusHelper +Component +Component.BaselineResizeBehavior +ComponentAdapter +ComponentColorModel +ComponentEvent +ComponentIdHelper +ComponentInputMap +ComponentInputMapUIResource +ComponentListener +ComponentOrientation +ComponentSampleModel +ComponentUI +ComponentView +Composite +CompositeContext +CompositeData +CompositeDataInvocationHandler +CompositeDataSupport +CompositeDataView +CompositeName +CompositeType +CompositeView +CompoundBorder +CompoundControl +CompoundControl.Type +CompoundEdit +CompoundName +Compression +ConcurrentHashMap +ConcurrentLinkedDeque +ConcurrentLinkedQueue +ConcurrentMap +ConcurrentModificationException +ConcurrentNavigableMap +ConcurrentSkipListMap +ConcurrentSkipListSet +Condition +Configuration +Configuration.Parameters +ConfigurationException +ConfigurationSpi +ConfirmationCallback +ConnectException +ConnectException +ConnectIOException +Connection +ConnectionEvent +ConnectionEventListener +ConnectionPendingException +ConnectionPoolDataSource +Console +ConsoleHandler +ConstantCallSite +Constructor +ConstructorProperties +Container +ContainerAdapter +ContainerEvent +ContainerListener +ContainerOrderFocusTraversalPolicy +ContentHandler +ContentHandler +ContentHandlerFactory +ContentModel +Context +Context +ContextList +ContextNotEmptyException +ContextualRenderedImageFactory +Control +Control +Control.Type +ControlFactory +ControllerEventListener +ConvolveOp +CookieHandler +CookieHolder +CookieManager +CookiePolicy +CookieStore +Copies +CopiesSupported +CopyOnWriteArrayList +CopyOnWriteArraySet +CopyOption +CountDownLatch +CounterMonitor +CounterMonitorMBean +CRC32 +CredentialException +CredentialExpiredException +CredentialNotFoundException +CRL +CRLException +CRLReason +CRLSelector +CropImageFilter +CryptoPrimitive +CSS +CSS.Attribute +CTX_RESTRICT_SCOPE +CubicCurve2D +CubicCurve2D.Double +CubicCurve2D.Float +Currency +CurrencyNameProvider +Current +Current +Current +CurrentHelper +CurrentHelper +CurrentHelper +CurrentHolder +CurrentOperations +CurrentOperations +CurrentOperations +Cursor +Customizer +CustomMarshal +CustomValue +CyclicBarrier +Data +DATA_CONVERSION +DatabaseMetaData +DataBindingException +DataBuffer +DataBufferByte +DataBufferDouble +DataBufferFloat +DataBufferInt +DataBufferShort +DataBufferUShort +DataContentHandler +DataContentHandlerFactory +DataFlavor +DataFormatException +DatagramChannel +DatagramPacket +DatagramSocket +DatagramSocketImpl +DatagramSocketImplFactory +DataHandler +DataInput +DataInputStream +DataInputStream +DataLine +DataLine.Info +DataOutput +DataOutputStream +DataOutputStream +DataSource +DataSource +DataTruncation +DatatypeConfigurationException +DatatypeConstants +DatatypeConstants.Field +DatatypeConverter +DatatypeConverterInterface +DatatypeFactory +Date +Date +DateFormat +DateFormat.Field +DateFormatProvider +DateFormatSymbols +DateFormatSymbolsProvider +DateFormatter +DateTimeAtCompleted +DateTimeAtCreation +DateTimeAtProcessing +DateTimeSyntax +DebugGraphics +DecimalFormat +DecimalFormatSymbols +DecimalFormatSymbolsProvider +DeclaredType +DeclHandler +DefaultBoundedRangeModel +DefaultButtonModel +DefaultCaret +DefaultCellEditor +DefaultColorSelectionModel +DefaultComboBoxModel +DefaultDesktopManager +DefaultEditorKit +DefaultEditorKit.BeepAction +DefaultEditorKit.CopyAction +DefaultEditorKit.CutAction +DefaultEditorKit.DefaultKeyTypedAction +DefaultEditorKit.InsertBreakAction +DefaultEditorKit.InsertContentAction +DefaultEditorKit.InsertTabAction +DefaultEditorKit.PasteAction +DefaultFocusManager +DefaultFocusTraversalPolicy +DefaultFormatter +DefaultFormatterFactory +DefaultHandler +DefaultHandler2 +DefaultHighlighter +DefaultHighlighter.DefaultHighlightPainter +DefaultKeyboardFocusManager +DefaultListCellRenderer +DefaultListCellRenderer.UIResource +DefaultListModel +DefaultListSelectionModel +DefaultLoaderRepository +DefaultLoaderRepository +DefaultMenuLayout +DefaultMetalTheme +DefaultMutableTreeNode +DefaultPersistenceDelegate +DefaultRowSorter +DefaultRowSorter.ModelWrapper +DefaultSingleSelectionModel +DefaultStyledDocument +DefaultStyledDocument.AttributeUndoableEdit +DefaultStyledDocument.ElementSpec +DefaultTableCellRenderer +DefaultTableCellRenderer.UIResource +DefaultTableColumnModel +DefaultTableModel +DefaultTextUI +DefaultTreeCellEditor +DefaultTreeCellRenderer +DefaultTreeModel +DefaultTreeSelectionModel +DefaultValidationEventHandler +DefinitionKind +DefinitionKindHelper +Deflater +DeflaterInputStream +DeflaterOutputStream +Delayed +DelayQueue +Delegate +Delegate +Delegate +DelegationPermission +Deprecated +Deque +Descriptor +DescriptorAccess +DescriptorKey +DescriptorRead +DescriptorSupport +DESedeKeySpec +DesignMode +DESKeySpec +Desktop +Desktop.Action +DesktopIconUI +DesktopManager +DesktopPaneUI +Destination +Destroyable +DestroyFailedException +Detail +DetailEntry +DGC +DHGenParameterSpec +DHKey +DHParameterSpec +DHPrivateKey +DHPrivateKeySpec +DHPublicKey +DHPublicKeySpec +Diagnostic +Diagnostic.Kind +DiagnosticCollector +DiagnosticListener +Dialog +Dialog.ModalExclusionType +Dialog.ModalityType +DialogTypeSelection +Dictionary +DigestException +DigestInputStream +DigestMethod +DigestMethodParameterSpec +DigestOutputStream +Dimension +Dimension2D +DimensionUIResource +DirContext +DirectColorModel +DirectoryIteratorException +DirectoryManager +DirectoryNotEmptyException +DirectoryStream +DirectoryStream.Filter +DirObjectFactory +DirStateFactory +DirStateFactory.Result +DISCARDING +Dispatch +DisplayMode +DnDConstants +Doc +DocAttribute +DocAttributeSet +DocFlavor +DocFlavor.BYTE_ARRAY +DocFlavor.CHAR_ARRAY +DocFlavor.INPUT_STREAM +DocFlavor.READER +DocFlavor.SERVICE_FORMATTED +DocFlavor.STRING +DocFlavor.URL +DocPrintJob +Document +Document +DocumentBuilder +DocumentBuilderFactory +Documented +DocumentEvent +DocumentEvent +DocumentEvent.ElementChange +DocumentEvent.EventType +DocumentFilter +DocumentFilter.FilterBypass +DocumentFragment +DocumentHandler +DocumentListener +DocumentName +DocumentParser +DocumentType +DomainCombiner +DomainManager +DomainManagerOperations +DOMConfiguration +DOMCryptoContext +DOMError +DOMErrorHandler +DOMException +DomHandler +DOMImplementation +DOMImplementationList +DOMImplementationLS +DOMImplementationRegistry +DOMImplementationSource +DOMLocator +DOMLocator +DOMResult +DOMSignContext +DOMSource +DOMStringList +DOMStructure +DOMURIReference +DOMValidateContext +DosFileAttributes +DosFileAttributeView +Double +DoubleBuffer +DoubleHolder +DoubleSeqHelper +DoubleSeqHolder +DragGestureEvent +DragGestureListener +DragGestureRecognizer +DragSource +DragSourceAdapter +DragSourceContext +DragSourceDragEvent +DragSourceDropEvent +DragSourceEvent +DragSourceListener +DragSourceMotionListener +Driver +DriverManager +DriverPropertyInfo +DropMode +DropTarget +DropTarget.DropTargetAutoScroller +DropTargetAdapter +DropTargetContext +DropTargetDragEvent +DropTargetDropEvent +DropTargetEvent +DropTargetListener +DSAKey +DSAKeyPairGenerator +DSAParameterSpec +DSAParams +DSAPrivateKey +DSAPrivateKeySpec +DSAPublicKey +DSAPublicKeySpec +DTD +DTD +DTDConstants +DTDHandler +DuplicateFormatFlagsException +DuplicateName +DuplicateNameHelper +Duration +DynamicImplementation +DynamicImplementation +DynamicMBean +DynAny +DynAny +DynAnyFactory +DynAnyFactoryHelper +DynAnyFactoryOperations +DynAnyHelper +DynAnyOperations +DynAnySeqHelper +DynArray +DynArray +DynArrayHelper +DynArrayOperations +DynEnum +DynEnum +DynEnumHelper +DynEnumOperations +DynFixed +DynFixed +DynFixedHelper +DynFixedOperations +DynSequence +DynSequence +DynSequenceHelper +DynSequenceOperations +DynStruct +DynStruct +DynStructHelper +DynStructOperations +DynUnion +DynUnion +DynUnionHelper +DynUnionOperations +DynValue +DynValue +DynValueBox +DynValueBoxOperations +DynValueCommon +DynValueCommonOperations +DynValueHelper +DynValueOperations +ECField +ECFieldF2m +ECFieldFp +ECGenParameterSpec +ECKey +ECParameterSpec +ECPoint +ECPrivateKey +ECPrivateKeySpec +ECPublicKey +ECPublicKeySpec +EditorKit +Element +Element +Element +Element +Element +ElementFilter +ElementIterator +ElementKind +ElementKindVisitor6 +ElementKindVisitor7 +Elements +ElementScanner6 +ElementScanner7 +ElementType +ElementVisitor +Ellipse2D +Ellipse2D.Double +Ellipse2D.Float +EllipticCurve +EmptyBorder +EmptyStackException +EncodedKeySpec +Encoder +Encoding +ENCODING_CDR_ENCAPS +EncryptedPrivateKeyInfo +EndDocument +EndElement +Endpoint +EndpointContext +EndpointReference +Entity +Entity +EntityDeclaration +EntityReference +EntityReference +EntityResolver +EntityResolver2 +Enum +EnumConstantNotPresentException +EnumControl +EnumControl.Type +Enumeration +EnumMap +EnumSet +EnumSyntax +Environment +EOFException +Error +ErrorHandler +ErrorListener +ErrorManager +ErrorType +EtchedBorder +Event +Event +EventContext +EventDirContext +EventException +EventFilter +EventHandler +EventListener +EventListener +EventListenerList +EventListenerProxy +EventObject +EventQueue +EventReaderDelegate +EventSetDescriptor +EventTarget +ExcC14NParameterSpec +Exception +ExceptionDetailMessage +ExceptionInInitializerError +ExceptionList +ExceptionListener +Exchanger +ExecutableElement +ExecutableType +ExecutionException +Executor +ExecutorCompletionService +Executors +ExecutorService +ExemptionMechanism +ExemptionMechanismException +ExemptionMechanismSpi +ExpandVetoException +ExportException +Expression +ExtendedRequest +ExtendedResponse +ExtendedSSLSession +Extension +Externalizable +FactoryConfigurationError +FactoryConfigurationError +FailedLoginException +FaultAction +FeatureDescriptor +Fidelity +Field +FieldNameHelper +FieldNameHelper +FieldPosition +FieldView +File +FileAlreadyExistsException +FileAttribute +FileAttributeView +FileCacheImageInputStream +FileCacheImageOutputStream +FileChannel +FileChannel.MapMode +FileChooserUI +FileDataSource +FileDescriptor +FileDialog +FileFilter +FileFilter +FileHandler +FileImageInputStream +FileImageOutputStream +FileInputStream +FileLock +FileLockInterruptionException +FileNameExtensionFilter +FilenameFilter +FileNameMap +FileNotFoundException +FileObject +FileOutputStream +FileOwnerAttributeView +FilePermission +Filer +FileReader +FilerException +Files +FileStore +FileStoreAttributeView +FileSystem +FileSystemAlreadyExistsException +FileSystemException +FileSystemLoopException +FileSystemNotFoundException +FileSystemProvider +FileSystems +FileSystemView +FileTime +FileTypeDetector +FileTypeMap +FileView +FileVisitOption +FileVisitor +FileVisitResult +FileWriter +Filter +FilteredImageSource +FilteredRowSet +FilterInputStream +FilterOutputStream +FilterReader +FilterWriter +Finishings +FixedHeightLayoutCache +FixedHolder +FlatteningPathIterator +FlavorEvent +FlavorException +FlavorListener +FlavorMap +FlavorTable +Float +FloatBuffer +FloatControl +FloatControl.Type +FloatHolder +FloatSeqHelper +FloatSeqHolder +FlowLayout +FlowView +FlowView.FlowStrategy +Flushable +FocusAdapter +FocusEvent +FocusListener +FocusManager +FocusTraversalPolicy +Font +FontFormatException +FontMetrics +FontRenderContext +FontUIResource +ForkJoinPool +ForkJoinPool.ForkJoinWorkerThreadFactory +ForkJoinPool.ManagedBlocker +ForkJoinTask +ForkJoinWorkerThread +Format +Format.Field +FormatConversionProvider +FormatFlagsConversionMismatchException +FormatMismatch +FormatMismatchHelper +Formattable +FormattableFlags +Formatter +Formatter +Formatter.BigDecimalLayoutForm +FormatterClosedException +FormSubmitEvent +FormSubmitEvent.MethodType +FormView +ForwardingFileObject +ForwardingJavaFileManager +ForwardingJavaFileObject +ForwardRequest +ForwardRequest +ForwardRequestHelper +ForwardRequestHelper +Frame +FREE_MEM +Future +FutureTask +GapContent +GarbageCollectorMXBean +GatheringByteChannel +GaugeMonitor +GaugeMonitorMBean +GCMParameterSpec +GeneralPath +GeneralSecurityException +Generated +GenericArrayType +GenericDeclaration +GenericSignatureFormatError +GlyphJustificationInfo +GlyphMetrics +GlyphVector +GlyphView +GlyphView.GlyphPainter +GradientPaint +GraphicAttribute +Graphics +Graphics2D +GraphicsConfigTemplate +GraphicsConfiguration +GraphicsDevice +GraphicsDevice.WindowTranslucency +GraphicsEnvironment +GrayFilter +GregorianCalendar +GridBagConstraints +GridBagLayout +GridBagLayoutInfo +GridLayout +Group +GroupLayout +GroupLayout.Alignment +GroupPrincipal +GSSContext +GSSCredential +GSSException +GSSManager +GSSName +Guard +GuardedObject +GZIPInputStream +GZIPOutputStream +Handler +Handler +HandlerBase +HandlerChain +HandlerResolver +HandshakeCompletedEvent +HandshakeCompletedListener +HasControls +HashAttributeSet +HashDocAttributeSet +HashMap +HashPrintJobAttributeSet +HashPrintRequestAttributeSet +HashPrintServiceAttributeSet +HashSet +Hashtable +HeadlessException +HexBinaryAdapter +HierarchyBoundsAdapter +HierarchyBoundsListener +HierarchyEvent +HierarchyListener +Highlighter +Highlighter.Highlight +Highlighter.HighlightPainter +HMACParameterSpec +Holder +HOLDING +HostnameVerifier +HTML +HTML.Attribute +HTML.Tag +HTML.UnknownTag +HTMLDocument +HTMLDocument.Iterator +HTMLEditorKit +HTMLEditorKit.HTMLFactory +HTMLEditorKit.HTMLTextAction +HTMLEditorKit.InsertHTMLTextAction +HTMLEditorKit.LinkController +HTMLEditorKit.Parser +HTMLEditorKit.ParserCallback +HTMLFrameHyperlinkEvent +HTMLWriter +HTTPBinding +HttpContext +HttpCookie +HTTPException +HttpExchange +HttpHandler +HttpRetryException +HttpsURLConnection +HttpURLConnection +HyperlinkEvent +HyperlinkEvent.EventType +HyperlinkListener +ICC_ColorSpace +ICC_Profile +ICC_ProfileGray +ICC_ProfileRGB +Icon +IconUIResource +IconView +ID_ASSIGNMENT_POLICY_ID +ID_UNIQUENESS_POLICY_ID +IdAssignmentPolicy +IdAssignmentPolicyOperations +IdAssignmentPolicyValue +IdentifierHelper +Identity +IdentityHashMap +IdentityScope +IDLEntity +IDLType +IDLTypeHelper +IDLTypeOperations +IDN +IdUniquenessPolicy +IdUniquenessPolicyOperations +IdUniquenessPolicyValue +IIOByteBuffer +IIOException +IIOImage +IIOInvalidTreeException +IIOMetadata +IIOMetadataController +IIOMetadataFormat +IIOMetadataFormatImpl +IIOMetadataNode +IIOParam +IIOParamController +IIOReadProgressListener +IIOReadUpdateListener +IIOReadWarningListener +IIORegistry +IIOServiceProvider +IIOWriteProgressListener +IIOWriteWarningListener +IllegalAccessError +IllegalAccessException +IllegalArgumentException +IllegalBlockingModeException +IllegalBlockSizeException +IllegalChannelGroupException +IllegalCharsetNameException +IllegalClassFormatException +IllegalComponentStateException +IllegalFormatCodePointException +IllegalFormatConversionException +IllegalFormatException +IllegalFormatFlagsException +IllegalFormatPrecisionException +IllegalFormatWidthException +IllegalMonitorStateException +IllegalPathStateException +IllegalSelectorException +IllegalStateException +IllegalThreadStateException +IllformedLocaleException +Image +ImageCapabilities +ImageConsumer +ImageFilter +ImageGraphicAttribute +ImageIcon +ImageInputStream +ImageInputStreamImpl +ImageInputStreamSpi +ImageIO +ImageObserver +ImageOutputStream +ImageOutputStreamImpl +ImageOutputStreamSpi +ImageProducer +ImageReader +ImageReaderSpi +ImageReaderWriterSpi +ImageReadParam +ImageTranscoder +ImageTranscoderSpi +ImageTypeSpecifier +ImageView +ImageWriteParam +ImageWriter +ImageWriterSpi +ImagingOpException +ImmutableDescriptor +IMP_LIMIT +IMPLICIT_ACTIVATION_POLICY_ID +ImplicitActivationPolicy +ImplicitActivationPolicyOperations +ImplicitActivationPolicyValue +INACTIVE +IncompatibleClassChangeError +IncompleteAnnotationException +InconsistentTypeCode +InconsistentTypeCode +InconsistentTypeCodeHelper +IndexColorModel +IndexedPropertyChangeEvent +IndexedPropertyDescriptor +IndexOutOfBoundsException +IndirectionException +Inet4Address +Inet6Address +InetAddress +InetSocketAddress +Inflater +InflaterInputStream +InflaterOutputStream +InheritableThreadLocal +Inherited +InitialContext +InitialContextFactory +InitialContextFactoryBuilder +InitialDirContext +INITIALIZE +InitialLdapContext +InitParam +InlineView +InputContext +InputEvent +InputMap +InputMapUIResource +InputMethod +InputMethodContext +InputMethodDescriptor +InputMethodEvent +InputMethodHighlight +InputMethodListener +InputMethodRequests +InputMismatchException +InputSource +InputStream +InputStream +InputStream +InputStreamReader +InputSubset +InputVerifier +Insets +InsetsUIResource +InstanceAlreadyExistsException +InstanceNotFoundException +InstantiationError +InstantiationException +Instrument +Instrumentation +InsufficientResourcesException +IntBuffer +Integer +IntegerSyntax +Interceptor +InterceptorOperations +InterfaceAddress +INTERNAL +InternalError +InternalFrameAdapter +InternalFrameEvent +InternalFrameFocusTraversalPolicy +InternalFrameListener +InternalFrameUI +InternationalFormatter +InterruptedByTimeoutException +InterruptedException +InterruptedIOException +InterruptedNamingException +InterruptibleChannel +INTF_REPOS +IntHolder +IntrospectionException +IntrospectionException +Introspector +INV_FLAG +INV_IDENT +INV_OBJREF +INV_POLICY +Invalid +INVALID_ACTIVITY +INVALID_TRANSACTION +InvalidActivityException +InvalidAddress +InvalidAddressHelper +InvalidAddressHolder +InvalidAlgorithmParameterException +InvalidApplicationException +InvalidAttributeIdentifierException +InvalidAttributesException +InvalidAttributeValueException +InvalidAttributeValueException +InvalidClassException +InvalidDnDOperationException +InvalidKeyException +InvalidKeyException +InvalidKeySpecException +InvalidMarkException +InvalidMidiDataException +InvalidName +InvalidName +InvalidName +InvalidNameException +InvalidNameHelper +InvalidNameHelper +InvalidNameHolder +InvalidObjectException +InvalidOpenTypeException +InvalidParameterException +InvalidParameterSpecException +InvalidPathException +InvalidPolicy +InvalidPolicyHelper +InvalidPreferencesFormatException +InvalidPropertiesFormatException +InvalidRelationIdException +InvalidRelationServiceException +InvalidRelationTypeException +InvalidRoleInfoException +InvalidRoleValueException +InvalidSearchControlsException +InvalidSearchFilterException +InvalidSeq +InvalidSlot +InvalidSlotHelper +InvalidTargetObjectTypeException +InvalidTransactionException +InvalidTypeForEncoding +InvalidTypeForEncodingHelper +InvalidValue +InvalidValue +InvalidValueHelper +Invocable +InvocationEvent +InvocationHandler +InvocationTargetException +InvokeHandler +Invoker +IOError +IOException +IOR +IORHelper +IORHolder +IORInfo +IORInfoOperations +IORInterceptor +IORInterceptor_3_0 +IORInterceptor_3_0Helper +IORInterceptor_3_0Holder +IORInterceptor_3_0Operations +IORInterceptorOperations +IRObject +IRObjectOperations +IstringHelper +ItemEvent +ItemListener +ItemSelectable +Iterable +Iterator +IvParameterSpec +JApplet +JarEntry +JarException +JarFile +JarInputStream +JarOutputStream +JarURLConnection +JavaCompiler +JavaCompiler.CompilationTask +JavaFileManager +JavaFileManager.Location +JavaFileObject +JavaFileObject.Kind +JAXB +JAXBContext +JAXBElement +JAXBElement.GlobalScope +JAXBException +JAXBIntrospector +JAXBPermission +JAXBResult +JAXBSource +JButton +JCheckBox +JCheckBoxMenuItem +JColorChooser +JComboBox +JComboBox.KeySelectionManager +JComponent +JdbcRowSet +JDesktopPane +JDialog +JEditorPane +JFileChooser +JFormattedTextField +JFormattedTextField.AbstractFormatter +JFormattedTextField.AbstractFormatterFactory +JFrame +JInternalFrame +JInternalFrame.JDesktopIcon +JLabel +JLayer +JLayeredPane +JList +JList.DropLocation +JMenu +JMenuBar +JMenuItem +JMException +JMRuntimeException +JMX +JMXAddressable +JMXAuthenticator +JMXConnectionNotification +JMXConnector +JMXConnectorFactory +JMXConnectorProvider +JMXConnectorServer +JMXConnectorServerFactory +JMXConnectorServerMBean +JMXConnectorServerProvider +JMXPrincipal +JMXProviderException +JMXServerErrorException +JMXServiceURL +JobAttributes +JobAttributes.DefaultSelectionType +JobAttributes.DestinationType +JobAttributes.DialogType +JobAttributes.MultipleDocumentHandlingType +JobAttributes.SidesType +JobHoldUntil +JobImpressions +JobImpressionsCompleted +JobImpressionsSupported +JobKOctets +JobKOctetsProcessed +JobKOctetsSupported +JobMediaSheets +JobMediaSheetsCompleted +JobMediaSheetsSupported +JobMessageFromOperator +JobName +JobOriginatingUserName +JobPriority +JobPrioritySupported +JobSheets +JobState +JobStateReason +JobStateReasons +Joinable +JoinRowSet +JOptionPane +JPanel +JPasswordField +JPEGHuffmanTable +JPEGImageReadParam +JPEGImageWriteParam +JPEGQTable +JPopupMenu +JPopupMenu.Separator +JProgressBar +JRadioButton +JRadioButtonMenuItem +JRootPane +JScrollBar +JScrollPane +JSeparator +JSlider +JSpinner +JSpinner.DateEditor +JSpinner.DefaultEditor +JSpinner.ListEditor +JSpinner.NumberEditor +JSplitPane +JTabbedPane +JTable +JTable.DropLocation +JTable.PrintMode +JTableHeader +JTextArea +JTextComponent +JTextComponent.DropLocation +JTextComponent.KeyBinding +JTextField +JTextPane +JToggleButton +JToggleButton.ToggleButtonModel +JToolBar +JToolBar.Separator +JToolTip +JTree +JTree.DropLocation +JTree.DynamicUtilTreeNode +JTree.EmptySelectionModel +JViewport +JWindow +KerberosKey +KerberosPrincipal +KerberosTicket +Kernel +Key +KeyAdapter +KeyAgreement +KeyAgreementSpi +KeyAlreadyExistsException +KeyboardFocusManager +KeyEvent +KeyEventDispatcher +KeyEventPostProcessor +KeyException +KeyFactory +KeyFactorySpi +KeyGenerator +KeyGeneratorSpi +KeyInfo +KeyInfoFactory +KeyListener +KeyManagementException +KeyManager +KeyManagerFactory +KeyManagerFactorySpi +Keymap +KeyName +KeyPair +KeyPairGenerator +KeyPairGeneratorSpi +KeyRep +KeyRep.Type +KeySelector +KeySelector.Purpose +KeySelectorException +KeySelectorResult +KeySpec +KeyStore +KeyStore.Builder +KeyStore.CallbackHandlerProtection +KeyStore.Entry +KeyStore.LoadStoreParameter +KeyStore.PasswordProtection +KeyStore.PrivateKeyEntry +KeyStore.ProtectionParameter +KeyStore.SecretKeyEntry +KeyStore.TrustedCertificateEntry +KeyStoreBuilderParameters +KeyStoreException +KeyStoreSpi +KeyStroke +KeyTab +KeyValue +Label +LabelUI +LabelView +LanguageCallback +LastOwnerException +LayeredHighlighter +LayeredHighlighter.LayerPainter +LayerUI +LayoutFocusTraversalPolicy +LayoutManager +LayoutManager2 +LayoutPath +LayoutQueue +LayoutStyle +LayoutStyle.ComponentPlacement +LDAPCertStoreParameters +LdapContext +LdapName +LdapReferralException +Lease +Level +LexicalHandler +LIFESPAN_POLICY_ID +LifespanPolicy +LifespanPolicyOperations +LifespanPolicyValue +LimitExceededException +Line +Line.Info +Line2D +Line2D.Double +Line2D.Float +LinearGradientPaint +LineBorder +LineBreakMeasurer +LineEvent +LineEvent.Type +LineListener +LineMetrics +LineNumberInputStream +LineNumberReader +LineUnavailableException +LinkageError +LinkedBlockingDeque +LinkedBlockingQueue +LinkedHashMap +LinkedHashSet +LinkedList +LinkedTransferQueue +LinkException +LinkLoopException +LinkOption +LinkPermission +LinkRef +List +List +ListCellRenderer +ListDataEvent +ListDataListener +ListenerNotFoundException +ListIterator +ListModel +ListResourceBundle +ListSelectionEvent +ListSelectionListener +ListSelectionModel +ListUI +ListView +LoaderHandler +Locale +Locale.Builder +Locale.Category +LocaleNameProvider +LocaleServiceProvider +LocalObject +LocateRegistry +Location +LOCATION_FORWARD +Locator +Locator2 +Locator2Impl +LocatorImpl +Lock +LockInfo +LockSupport +Logger +LoggingMXBean +LoggingPermission +LogicalHandler +LogicalMessage +LogicalMessageContext +LoginContext +LoginException +LoginModule +LogManager +LogRecord +LogStream +Long +LongBuffer +LongHolder +LongLongSeqHelper +LongLongSeqHolder +LongSeqHelper +LongSeqHolder +LookAndFeel +LookupOp +LookupTable +LSException +LSInput +LSLoadEvent +LSOutput +LSParser +LSParserFilter +LSProgressEvent +LSResourceResolver +LSSerializer +LSSerializerFilter +Mac +MacSpi +MailcapCommandMap +MalformedInputException +MalformedLinkException +MalformedObjectNameException +MalformedParameterizedTypeException +MalformedURLException +ManagementFactory +ManagementPermission +ManageReferralControl +ManagerFactoryParameters +Manifest +Manifest +Map +Map.Entry +MappedByteBuffer +MARSHAL +MarshalException +MarshalException +MarshalException +MarshalledObject +Marshaller +Marshaller.Listener +MaskFormatter +Matcher +MatchResult +Math +MathContext +MatteBorder +MBeanAttributeInfo +MBeanConstructorInfo +MBeanException +MBeanFeatureInfo +MBeanInfo +MBeanNotificationInfo +MBeanOperationInfo +MBeanParameterInfo +MBeanPermission +MBeanRegistration +MBeanRegistrationException +MBeanServer +MBeanServerBuilder +MBeanServerConnection +MBeanServerDelegate +MBeanServerDelegateMBean +MBeanServerFactory +MBeanServerForwarder +MBeanServerInvocationHandler +MBeanServerNotification +MBeanServerNotificationFilter +MBeanServerPermission +MBeanTrustPermission +Media +MediaName +MediaPrintableArea +MediaSize +MediaSize.Engineering +MediaSize.ISO +MediaSize.JIS +MediaSize.NA +MediaSize.Other +MediaSizeName +MediaTracker +MediaTray +Member +MembershipKey +MemoryCacheImageInputStream +MemoryCacheImageOutputStream +MemoryHandler +MemoryImageSource +MemoryManagerMXBean +MemoryMXBean +MemoryNotificationInfo +MemoryPoolMXBean +MemoryType +MemoryUsage +Menu +MenuBar +MenuBarUI +MenuComponent +MenuContainer +MenuDragMouseEvent +MenuDragMouseListener +MenuElement +MenuEvent +MenuItem +MenuItemUI +MenuKeyEvent +MenuKeyListener +MenuListener +MenuSelectionManager +MenuShortcut +MessageContext +MessageContext.Scope +MessageDigest +MessageDigestSpi +MessageFactory +MessageFormat +MessageFormat.Field +MessageProp +Messager +MetaEventListener +MetalBorders +MetalBorders.ButtonBorder +MetalBorders.Flush3DBorder +MetalBorders.InternalFrameBorder +MetalBorders.MenuBarBorder +MetalBorders.MenuItemBorder +MetalBorders.OptionDialogBorder +MetalBorders.PaletteBorder +MetalBorders.PopupMenuBorder +MetalBorders.RolloverButtonBorder +MetalBorders.ScrollPaneBorder +MetalBorders.TableHeaderBorder +MetalBorders.TextFieldBorder +MetalBorders.ToggleButtonBorder +MetalBorders.ToolBarBorder +MetalButtonUI +MetalCheckBoxIcon +MetalCheckBoxUI +MetalComboBoxButton +MetalComboBoxEditor +MetalComboBoxEditor.UIResource +MetalComboBoxIcon +MetalComboBoxUI +MetalDesktopIconUI +MetalFileChooserUI +MetalIconFactory +MetalIconFactory.FileIcon16 +MetalIconFactory.FolderIcon16 +MetalIconFactory.PaletteCloseIcon +MetalIconFactory.TreeControlIcon +MetalIconFactory.TreeFolderIcon +MetalIconFactory.TreeLeafIcon +MetalInternalFrameTitlePane +MetalInternalFrameUI +MetalLabelUI +MetalLookAndFeel +MetalMenuBarUI +MetalPopupMenuSeparatorUI +MetalProgressBarUI +MetalRadioButtonUI +MetalRootPaneUI +MetalScrollBarUI +MetalScrollButton +MetalScrollPaneUI +MetalSeparatorUI +MetalSliderUI +MetalSplitPaneUI +MetalTabbedPaneUI +MetalTextFieldUI +MetalTheme +MetalToggleButtonUI +MetalToolBarUI +MetalToolTipUI +MetalTreeUI +MetaMessage +Method +MethodDescriptor +MethodHandle +MethodHandleProxies +MethodHandles +MethodHandles.Lookup +MethodType +MGF1ParameterSpec +MidiChannel +MidiDevice +MidiDevice.Info +MidiDeviceProvider +MidiDeviceReceiver +MidiDeviceTransmitter +MidiEvent +MidiFileFormat +MidiFileReader +MidiFileWriter +MidiMessage +MidiSystem +MidiUnavailableException +MimeHeader +MimeHeaders +MimeType +MimeTypeParameterList +MimeTypeParseException +MimeTypeParseException +MimetypesFileTypeMap +MinimalHTMLWriter +MirroredTypeException +MirroredTypesException +MissingFormatArgumentException +MissingFormatWidthException +MissingResourceException +Mixer +Mixer.Info +MixerProvider +MLet +MLetContent +MLetMBean +ModelMBean +ModelMBeanAttributeInfo +ModelMBeanConstructorInfo +ModelMBeanInfo +ModelMBeanInfoSupport +ModelMBeanNotificationBroadcaster +ModelMBeanNotificationInfo +ModelMBeanOperationInfo +ModificationItem +Modifier +Modifier +Monitor +MonitorInfo +MonitorMBean +MonitorNotification +MonitorSettingException +MouseAdapter +MouseDragGestureRecognizer +MouseEvent +MouseEvent +MouseInfo +MouseInputAdapter +MouseInputListener +MouseListener +MouseMotionAdapter +MouseMotionListener +MouseWheelEvent +MouseWheelListener +MTOM +MTOMFeature +MultiButtonUI +MulticastChannel +MulticastSocket +MultiColorChooserUI +MultiComboBoxUI +MultiDesktopIconUI +MultiDesktopPaneUI +MultiDoc +MultiDocPrintJob +MultiDocPrintService +MultiFileChooserUI +MultiInternalFrameUI +MultiLabelUI +MultiListUI +MultiLookAndFeel +MultiMenuBarUI +MultiMenuItemUI +MultiOptionPaneUI +MultiPanelUI +MultiPixelPackedSampleModel +MultipleComponentProfileHelper +MultipleComponentProfileHolder +MultipleDocumentHandling +MultipleGradientPaint +MultipleGradientPaint.ColorSpaceType +MultipleGradientPaint.CycleMethod +MultipleMaster +MultiPopupMenuUI +MultiProgressBarUI +MultiRootPaneUI +MultiScrollBarUI +MultiScrollPaneUI +MultiSeparatorUI +MultiSliderUI +MultiSpinnerUI +MultiSplitPaneUI +MultiTabbedPaneUI +MultiTableHeaderUI +MultiTableUI +MultiTextUI +MultiToolBarUI +MultiToolTipUI +MultiTreeUI +MultiViewportUI +MutableAttributeSet +MutableCallSite +MutableComboBoxModel +MutableTreeNode +MutationEvent +MXBean +Name +Name +Name +NameAlreadyBoundException +NameCallback +NameClassPair +NameComponent +NameComponentHelper +NameComponentHolder +NamedNodeMap +NamedValue +NameDynAnyPair +NameDynAnyPairHelper +NameDynAnyPairSeqHelper +NameHelper +NameHolder +NameList +NameNotFoundException +NameParser +Namespace +NamespaceChangeListener +NamespaceContext +NamespaceSupport +NameValuePair +NameValuePair +NameValuePairHelper +NameValuePairHelper +NameValuePairSeqHelper +Naming +NamingContext +NamingContextExt +NamingContextExtHelper +NamingContextExtHolder +NamingContextExtOperations +NamingContextExtPOA +NamingContextHelper +NamingContextHolder +NamingContextOperations +NamingContextPOA +NamingEnumeration +NamingEvent +NamingException +NamingExceptionEvent +NamingListener +NamingManager +NamingSecurityException +NavigableMap +NavigableSet +NavigationFilter +NavigationFilter.FilterBypass +NClob +NegativeArraySizeException +NestingKind +NetPermission +NetworkChannel +NetworkInterface +NimbusLookAndFeel +NimbusStyle +NO_IMPLEMENT +NO_MEMORY +NO_PERMISSION +NO_RESOURCES +NO_RESPONSE +NoClassDefFoundError +NoConnectionPendingException +NoContext +NoContextHelper +Node +Node +NodeChangeEvent +NodeChangeListener +NodeList +NodeSetData +NoInitialContextException +NON_EXISTENT +NoninvertibleTransformException +NonReadableChannelException +NonWritableChannelException +NoPermissionException +NormalizedStringAdapter +Normalizer +Normalizer.Form +NoRouteToHostException +NoServant +NoServantHelper +NoSuchAlgorithmException +NoSuchAttributeException +NoSuchElementException +NoSuchFieldError +NoSuchFieldException +NoSuchFileException +NoSuchMechanismException +NoSuchMethodError +NoSuchMethodException +NoSuchObjectException +NoSuchPaddingException +NoSuchProviderException +NotActiveException +Notation +NotationDeclaration +NotBoundException +NotCompliantMBeanException +NotContextException +NotDirectoryException +NotEmpty +NotEmptyHelper +NotEmptyHolder +NotFound +NotFoundHelper +NotFoundHolder +NotFoundReason +NotFoundReasonHelper +NotFoundReasonHolder +NotIdentifiableEvent +NotIdentifiableEventImpl +Notification +NotificationBroadcaster +NotificationBroadcasterSupport +NotificationEmitter +NotificationFilter +NotificationFilterSupport +NotificationListener +NotificationResult +NotLinkException +NotOwnerException +NotSerializableException +NotYetBoundException +NotYetConnectedException +NoType +NullCipher +NullPointerException +NullType +Number +NumberFormat +NumberFormat.Field +NumberFormatException +NumberFormatProvider +NumberFormatter +NumberOfDocuments +NumberOfInterveningJobs +NumberUp +NumberUpSupported +NumericShaper +NumericShaper.Range +NVList +OAEPParameterSpec +OBJ_ADAPTER +Object +Object +OBJECT_NOT_EXIST +ObjectAlreadyActive +ObjectAlreadyActiveHelper +ObjectChangeListener +ObjectFactory +ObjectFactoryBuilder +ObjectHelper +ObjectHolder +ObjectIdHelper +ObjectIdHelper +ObjectImpl +ObjectImpl +ObjectInput +ObjectInputStream +ObjectInputStream.GetField +ObjectInputValidation +ObjectInstance +ObjectName +ObjectNotActive +ObjectNotActiveHelper +ObjectOutput +ObjectOutputStream +ObjectOutputStream.PutField +ObjectReferenceFactory +ObjectReferenceFactoryHelper +ObjectReferenceFactoryHolder +ObjectReferenceTemplate +ObjectReferenceTemplateHelper +ObjectReferenceTemplateHolder +ObjectReferenceTemplateSeqHelper +ObjectReferenceTemplateSeqHolder +Objects +ObjectStreamClass +ObjectStreamConstants +ObjectStreamException +ObjectStreamField +ObjectView +ObjID +Observable +Observer +OceanTheme +OctetSeqHelper +OctetSeqHolder +OctetStreamData +Oid +OMGVMCID +Oneway +OpenDataException +OpenMBeanAttributeInfo +OpenMBeanAttributeInfoSupport +OpenMBeanConstructorInfo +OpenMBeanConstructorInfoSupport +OpenMBeanInfo +OpenMBeanInfoSupport +OpenMBeanOperationInfo +OpenMBeanOperationInfoSupport +OpenMBeanParameterInfo +OpenMBeanParameterInfoSupport +OpenOption +OpenType +OpenType +OperatingSystemMXBean +Operation +OperationNotSupportedException +OperationsException +Option +OptionalDataException +OptionChecker +OptionPaneUI +ORB +ORB +ORBIdHelper +ORBInitializer +ORBInitializerOperations +ORBInitInfo +ORBInitInfoOperations +OrientationRequested +OutOfMemoryError +OutputDeviceAssigned +OutputKeys +OutputStream +OutputStream +OutputStream +OutputStreamWriter +OverlappingFileLockException +OverlayLayout +Override +Owner +Pack200 +Pack200.Packer +Pack200.Unpacker +Package +PackageElement +PackedColorModel +Pageable +PageAttributes +PageAttributes.ColorType +PageAttributes.MediaType +PageAttributes.OrientationRequestedType +PageAttributes.OriginType +PageAttributes.PrintQualityType +PagedResultsControl +PagedResultsResponseControl +PageFormat +PageRanges +PagesPerMinute +PagesPerMinuteColor +Paint +PaintContext +Painter +PaintEvent +Panel +PanelUI +Paper +ParagraphView +ParagraphView +Parameter +ParameterBlock +ParameterDescriptor +Parameterizable +ParameterizedType +ParameterMetaData +ParameterMode +ParameterModeHelper +ParameterModeHolder +ParseConversionEvent +ParseConversionEventImpl +ParseException +ParsePosition +Parser +Parser +ParserAdapter +ParserConfigurationException +ParserDelegator +ParserFactory +PartialResultException +PasswordAuthentication +PasswordCallback +PasswordView +Patch +Path +Path2D +Path2D.Double +Path2D.Float +PathIterator +PathMatcher +Paths +Pattern +PatternSyntaxException +PBEKey +PBEKeySpec +PBEParameterSpec +PDLOverrideSupported +Permission +Permission +PermissionCollection +Permissions +PERSIST_STORE +PersistenceDelegate +PersistentMBean +PGPData +PhantomReference +Phaser +Pipe +Pipe.SinkChannel +Pipe.SourceChannel +PipedInputStream +PipedOutputStream +PipedReader +PipedWriter +PixelGrabber +PixelInterleavedSampleModel +PKCS8EncodedKeySpec +PKIXBuilderParameters +PKIXCertPathBuilderResult +PKIXCertPathChecker +PKIXCertPathValidatorResult +PKIXParameters +PKIXReason +PlainDocument +PlainView +PlatformLoggingMXBean +PlatformManagedObject +POA +POAHelper +POAManager +POAManagerOperations +POAOperations +Point +Point2D +Point2D.Double +Point2D.Float +PointerInfo +Policy +Policy +Policy +Policy.Parameters +PolicyError +PolicyErrorCodeHelper +PolicyErrorHelper +PolicyErrorHolder +PolicyFactory +PolicyFactoryOperations +PolicyHelper +PolicyHolder +PolicyListHelper +PolicyListHolder +PolicyNode +PolicyOperations +PolicyQualifierInfo +PolicySpi +PolicyTypeHelper +Polygon +PooledConnection +Popup +PopupFactory +PopupMenu +PopupMenuEvent +PopupMenuListener +PopupMenuUI +Port +Port.Info +PortableRemoteObject +PortableRemoteObjectDelegate +PortInfo +PortUnreachableException +Position +Position.Bias +PosixFileAttributes +PosixFileAttributeView +PosixFilePermission +PosixFilePermissions +PostConstruct +PreDestroy +Predicate +PreferenceChangeEvent +PreferenceChangeListener +Preferences +PreferencesFactory +PreparedStatement +PresentationDirection +PrimitiveType +Principal +Principal +PrincipalHolder +Printable +PrintConversionEvent +PrintConversionEventImpl +PrinterAbortException +PrinterException +PrinterGraphics +PrinterInfo +PrinterIOException +PrinterIsAcceptingJobs +PrinterJob +PrinterLocation +PrinterMakeAndModel +PrinterMessageFromOperator +PrinterMoreInfo +PrinterMoreInfoManufacturer +PrinterName +PrinterResolution +PrinterState +PrinterStateReason +PrinterStateReasons +PrinterURI +PrintEvent +PrintException +PrintGraphics +PrintJob +PrintJobAdapter +PrintJobAttribute +PrintJobAttributeEvent +PrintJobAttributeListener +PrintJobAttributeSet +PrintJobEvent +PrintJobListener +PrintQuality +PrintRequestAttribute +PrintRequestAttributeSet +PrintService +PrintServiceAttribute +PrintServiceAttributeEvent +PrintServiceAttributeListener +PrintServiceAttributeSet +PrintServiceLookup +PrintStream +PrintWriter +PriorityBlockingQueue +PriorityQueue +PRIVATE_MEMBER +PrivateClassLoader +PrivateCredentialPermission +PrivateKey +PrivateMLet +PrivilegedAction +PrivilegedActionException +PrivilegedExceptionAction +Process +ProcessBuilder +ProcessBuilder.Redirect +ProcessBuilder.Redirect.Type +ProcessingEnvironment +ProcessingInstruction +ProcessingInstruction +Processor +ProfileDataException +ProfileIdHelper +ProgressBarUI +ProgressMonitor +ProgressMonitorInputStream +Properties +PropertyChangeEvent +PropertyChangeListener +PropertyChangeListenerProxy +PropertyChangeSupport +PropertyDescriptor +PropertyEditor +PropertyEditorManager +PropertyEditorSupport +PropertyException +PropertyPermission +PropertyResourceBundle +PropertyVetoException +ProtectionDomain +ProtocolException +ProtocolException +ProtocolFamily +Provider +Provider +Provider +Provider.Service +ProviderException +ProviderMismatchException +ProviderNotFoundException +Proxy +Proxy +Proxy.Type +ProxySelector +PseudoColumnUsage +PSource +PSource.PSpecified +PSSParameterSpec +PUBLIC_MEMBER +PublicKey +PushbackInputStream +PushbackReader +QName +QuadCurve2D +QuadCurve2D.Double +QuadCurve2D.Float +QualifiedNameable +Query +QueryEval +QueryExp +Queue +QueuedJobCount +RadialGradientPaint +Random +RandomAccess +RandomAccessFile +Raster +RasterFormatException +RasterOp +RC2ParameterSpec +RC5ParameterSpec +Rdn +Readable +ReadableByteChannel +Reader +ReadOnlyBufferException +ReadOnlyFileSystemException +ReadPendingException +ReadWriteLock +RealmCallback +RealmChoiceCallback +REBIND +Receiver +Rectangle +Rectangle2D +Rectangle2D.Double +Rectangle2D.Float +RectangularShape +RecursiveAction +RecursiveTask +ReentrantLock +ReentrantReadWriteLock +ReentrantReadWriteLock.ReadLock +ReentrantReadWriteLock.WriteLock +Ref +RefAddr +Reference +Reference +Reference +Referenceable +ReferenceQueue +ReferenceType +ReferenceUriSchemesSupported +ReferralException +ReflectionException +ReflectiveOperationException +ReflectPermission +Refreshable +RefreshFailedException +Region +RegisterableService +Registry +RegistryHandler +RejectedExecutionException +RejectedExecutionHandler +Relation +RelationException +RelationNotFoundException +RelationNotification +RelationService +RelationServiceMBean +RelationServiceNotRegisteredException +RelationSupport +RelationSupportMBean +RelationType +RelationTypeNotFoundException +RelationTypeSupport +RemarshalException +Remote +RemoteCall +RemoteException +RemoteObject +RemoteObjectInvocationHandler +RemoteRef +RemoteServer +RemoteStub +RenderableImage +RenderableImageOp +RenderableImageProducer +RenderContext +RenderedImage +RenderedImageFactory +Renderer +RenderingHints +RenderingHints.Key +RepaintManager +ReplicateScaleFilter +RepositoryIdHelper +Request +REQUEST_PROCESSING_POLICY_ID +RequestInfo +RequestInfoOperations +RequestingUserName +RequestProcessingPolicy +RequestProcessingPolicyOperations +RequestProcessingPolicyValue +RequestWrapper +RequiredModelMBean +RescaleOp +ResolutionSyntax +Resolver +ResolveResult +Resource +Resource.AuthenticationType +ResourceBundle +ResourceBundle.Control +Resources +RespectBinding +RespectBindingFeature +Response +ResponseCache +ResponseHandler +ResponseWrapper +Result +ResultSet +ResultSetMetaData +Retention +RetentionPolicy +RetrievalMethod +ReverbType +RGBImageFilter +RMIClassLoader +RMIClassLoaderSpi +RMIClientSocketFactory +RMIConnection +RMIConnectionImpl +RMIConnectionImpl_Stub +RMIConnector +RMIConnectorServer +RMICustomMaxStreamFormat +RMIFailureHandler +RMIIIOPServerImpl +RMIJRMPServerImpl +RMISecurityException +RMISecurityManager +RMIServer +RMIServerImpl +RMIServerImpl_Stub +RMIServerSocketFactory +RMISocketFactory +Robot +Role +RoleInfo +RoleInfoNotFoundException +RoleList +RoleNotFoundException +RoleResult +RoleStatus +RoleUnresolved +RoleUnresolvedList +RootPaneContainer +RootPaneUI +RoundEnvironment +RoundingMode +RoundRectangle2D +RoundRectangle2D.Double +RoundRectangle2D.Float +RowFilter +RowFilter.ComparisonType +RowFilter.Entry +RowId +RowIdLifetime +RowMapper +RowSet +RowSetEvent +RowSetFactory +RowSetInternal +RowSetListener +RowSetMetaData +RowSetMetaDataImpl +RowSetProvider +RowSetReader +RowSetWarning +RowSetWriter +RowSorter +RowSorter.SortKey +RowSorterEvent +RowSorterEvent.Type +RowSorterListener +RSAKey +RSAKeyGenParameterSpec +RSAMultiPrimePrivateCrtKey +RSAMultiPrimePrivateCrtKeySpec +RSAOtherPrimeInfo +RSAPrivateCrtKey +RSAPrivateCrtKeySpec +RSAPrivateKey +RSAPrivateKeySpec +RSAPublicKey +RSAPublicKeySpec +RTFEditorKit +RuleBasedCollator +Runnable +RunnableFuture +RunnableScheduledFuture +Runtime +RunTime +RuntimeErrorException +RuntimeException +RuntimeMBeanException +RuntimeMXBean +RunTimeOperations +RuntimeOperationsException +RuntimePermission +SAAJMetaFactory +SAAJResult +SafeVarargs +SampleModel +Sasl +SaslClient +SaslClientFactory +SaslException +SaslServer +SaslServerFactory +Savepoint +SAXException +SAXNotRecognizedException +SAXNotSupportedException +SAXParseException +SAXParser +SAXParserFactory +SAXResult +SAXSource +SAXTransformerFactory +Scanner +ScatteringByteChannel +ScheduledExecutorService +ScheduledFuture +ScheduledThreadPoolExecutor +Schema +SchemaFactory +SchemaFactoryLoader +SchemaOutputResolver +SchemaViolationException +ScriptContext +ScriptEngine +ScriptEngineFactory +ScriptEngineManager +ScriptException +Scrollable +Scrollbar +ScrollBarUI +ScrollPane +ScrollPaneAdjustable +ScrollPaneConstants +ScrollPaneLayout +ScrollPaneLayout.UIResource +ScrollPaneUI +SealedObject +SearchControls +SearchResult +SecondaryLoop +SecretKey +SecretKeyFactory +SecretKeyFactorySpi +SecretKeySpec +SecureCacheResponse +SecureClassLoader +SecureDirectoryStream +SecureRandom +SecureRandomSpi +Security +SecurityException +SecurityManager +SecurityPermission +SeekableByteChannel +Segment +SelectableChannel +SelectionKey +Selector +SelectorProvider +Semaphore +SeparatorUI +Sequence +SequenceInputStream +Sequencer +Sequencer.SyncMode +SerialArray +SerialBlob +SerialClob +SerialDatalink +SerialException +Serializable +SerializablePermission +SerialJavaObject +SerialRef +SerialStruct +Servant +SERVANT_RETENTION_POLICY_ID +ServantActivator +ServantActivatorHelper +ServantActivatorOperations +ServantActivatorPOA +ServantAlreadyActive +ServantAlreadyActiveHelper +ServantLocator +ServantLocatorHelper +ServantLocatorOperations +ServantLocatorPOA +ServantManager +ServantManagerOperations +ServantNotActive +ServantNotActiveHelper +ServantObject +ServantRetentionPolicy +ServantRetentionPolicyOperations +ServantRetentionPolicyValue +ServerCloneException +ServerError +ServerException +ServerIdHelper +ServerNotActiveException +ServerRef +ServerRequest +ServerRequestInfo +ServerRequestInfoOperations +ServerRequestInterceptor +ServerRequestInterceptorOperations +ServerRuntimeException +ServerSocket +ServerSocketChannel +ServerSocketFactory +Service +Service.Mode +ServiceConfigurationError +ServiceContext +ServiceContextHelper +ServiceContextHolder +ServiceContextListHelper +ServiceContextListHolder +ServiceDelegate +ServiceDetail +ServiceDetailHelper +ServiceIdHelper +ServiceInformation +ServiceInformationHelper +ServiceInformationHolder +ServiceLoader +ServiceMode +ServiceNotFoundException +ServicePermission +ServiceRegistry +ServiceRegistry.Filter +ServiceUI +ServiceUIFactory +ServiceUnavailableException +Set +SetOfIntegerSyntax +SetOverrideType +SetOverrideTypeHelper +Severity +Shape +ShapeGraphicAttribute +SheetCollate +Short +ShortBuffer +ShortBufferException +ShortHolder +ShortLookupTable +ShortMessage +ShortSeqHelper +ShortSeqHolder +ShutdownChannelGroupException +Sides +Signature +SignatureException +SignatureMethod +SignatureMethodParameterSpec +SignatureProperties +SignatureProperty +SignatureSpi +SignedInfo +SignedObject +Signer +SimpleAnnotationValueVisitor6 +SimpleAnnotationValueVisitor7 +SimpleAttributeSet +SimpleBeanInfo +SimpleBindings +SimpleDateFormat +SimpleDoc +SimpleElementVisitor6 +SimpleElementVisitor7 +SimpleFileVisitor +SimpleFormatter +SimpleJavaFileObject +SimpleScriptContext +SimpleTimeZone +SimpleType +SimpleTypeVisitor6 +SimpleTypeVisitor7 +SinglePixelPackedSampleModel +SingleSelectionModel +Size2DSyntax +SizeLimitExceededException +SizeRequirements +SizeSequence +Skeleton +SkeletonMismatchException +SkeletonNotFoundException +SliderUI +SOAPBinding +SOAPBinding +SOAPBinding.ParameterStyle +SOAPBinding.Style +SOAPBinding.Use +SOAPBody +SOAPBodyElement +SOAPConnection +SOAPConnectionFactory +SOAPConstants +SOAPElement +SOAPElementFactory +SOAPEnvelope +SOAPException +SOAPFactory +SOAPFault +SOAPFaultElement +SOAPFaultException +SOAPHandler +SOAPHeader +SOAPHeaderElement +SOAPMessage +SOAPMessageContext +SOAPMessageHandler +SOAPMessageHandlers +SOAPPart +Socket +SocketAddress +SocketChannel +SocketException +SocketFactory +SocketHandler +SocketImpl +SocketImplFactory +SocketOption +SocketOptions +SocketPermission +SocketSecurityException +SocketTimeoutException +SoftBevelBorder +SoftReference +SortControl +SortedMap +SortedSet +SortingFocusTraversalPolicy +SortKey +SortOrder +SortResponseControl +Soundbank +SoundbankReader +SoundbankResource +Source +SourceDataLine +SourceLocator +SourceVersion +SpinnerDateModel +SpinnerListModel +SpinnerModel +SpinnerNumberModel +SpinnerUI +SplashScreen +SplitPaneUI +Spring +SpringLayout +SpringLayout.Constraints +SQLClientInfoException +SQLData +SQLDataException +SQLException +SQLFeatureNotSupportedException +SQLInput +SQLInputImpl +SQLIntegrityConstraintViolationException +SQLInvalidAuthorizationSpecException +SQLNonTransientConnectionException +SQLNonTransientException +SQLOutput +SQLOutputImpl +SQLPermission +SQLRecoverableException +SQLSyntaxErrorException +SQLTimeoutException +SQLTransactionRollbackException +SQLTransientConnectionException +SQLTransientException +SQLWarning +SQLXML +SSLContext +SSLContextSpi +SSLEngine +SSLEngineResult +SSLEngineResult.HandshakeStatus +SSLEngineResult.Status +SSLException +SSLHandshakeException +SSLKeyException +SSLParameters +SSLPeerUnverifiedException +SSLPermission +SSLProtocolException +SslRMIClientSocketFactory +SslRMIServerSocketFactory +SSLServerSocket +SSLServerSocketFactory +SSLSession +SSLSessionBindingEvent +SSLSessionBindingListener +SSLSessionContext +SSLSocket +SSLSocketFactory +Stack +StackOverflowError +StackTraceElement +StandardCharsets +StandardCopyOption +StandardEmitterMBean +StandardJavaFileManager +StandardLocation +StandardMBean +StandardOpenOption +StandardProtocolFamily +StandardSocketOptions +StandardWatchEventKinds +StartDocument +StartElement +StartTlsRequest +StartTlsResponse +State +State +StateEdit +StateEditable +StateFactory +Statement +Statement +StatementEvent +StatementEventListener +StAXResult +StAXSource +Streamable +StreamableValue +StreamCorruptedException +StreamFilter +StreamHandler +StreamPrintService +StreamPrintServiceFactory +StreamReaderDelegate +StreamResult +StreamSource +StreamTokenizer +StrictMath +String +StringBuffer +StringBufferInputStream +StringBuilder +StringCharacterIterator +StringContent +StringHolder +StringIndexOutOfBoundsException +StringMonitor +StringMonitorMBean +StringNameHelper +StringReader +StringRefAddr +StringSelection +StringSeqHelper +StringSeqHolder +StringTokenizer +StringValueExp +StringValueHelper +StringWriter +Stroke +StrokeBorder +Struct +StructMember +StructMemberHelper +Stub +StubDelegate +StubNotFoundException +Style +StyleConstants +StyleConstants.CharacterConstants +StyleConstants.ColorConstants +StyleConstants.FontConstants +StyleConstants.ParagraphConstants +StyleContext +StyledDocument +StyledEditorKit +StyledEditorKit.AlignmentAction +StyledEditorKit.BoldAction +StyledEditorKit.FontFamilyAction +StyledEditorKit.FontSizeAction +StyledEditorKit.ForegroundAction +StyledEditorKit.ItalicAction +StyledEditorKit.StyledTextAction +StyledEditorKit.UnderlineAction +StyleSheet +StyleSheet.BoxPainter +StyleSheet.ListPainter +Subject +SubjectDelegationPermission +SubjectDomainCombiner +SUCCESSFUL +SupportedAnnotationTypes +SupportedOptions +SupportedSourceVersion +SupportedValuesAttribute +SuppressWarnings +SwingConstants +SwingPropertyChangeSupport +SwingUtilities +SwingWorker +SwingWorker.StateValue +SwitchPoint +SYNC_WITH_TRANSPORT +SyncFactory +SyncFactoryException +SyncFailedException +SynchronousQueue +SyncProvider +SyncProviderException +SyncResolver +SyncScopeHelper +SynthButtonUI +SynthCheckBoxMenuItemUI +SynthCheckBoxUI +SynthColorChooserUI +SynthComboBoxUI +SynthConstants +SynthContext +SynthDesktopIconUI +SynthDesktopPaneUI +SynthEditorPaneUI +Synthesizer +SynthFormattedTextFieldUI +SynthGraphicsUtils +SynthInternalFrameUI +SynthLabelUI +SynthListUI +SynthLookAndFeel +SynthMenuBarUI +SynthMenuItemUI +SynthMenuUI +SynthOptionPaneUI +SynthPainter +SynthPanelUI +SynthPasswordFieldUI +SynthPopupMenuUI +SynthProgressBarUI +SynthRadioButtonMenuItemUI +SynthRadioButtonUI +SynthRootPaneUI +SynthScrollBarUI +SynthScrollPaneUI +SynthSeparatorUI +SynthSliderUI +SynthSpinnerUI +SynthSplitPaneUI +SynthStyle +SynthStyleFactory +SynthTabbedPaneUI +SynthTableHeaderUI +SynthTableUI +SynthTextAreaUI +SynthTextFieldUI +SynthTextPaneUI +SynthToggleButtonUI +SynthToolBarUI +SynthToolTipUI +SynthTreeUI +SynthUI +SynthViewportUI +SysexMessage +System +SYSTEM_EXCEPTION +SystemColor +SystemException +SystemFlavorMap +SystemTray +TabableView +TabbedPaneUI +TabExpander +TableCellEditor +TableCellRenderer +TableColumn +TableColumnModel +TableColumnModelEvent +TableColumnModelListener +TableHeaderUI +TableModel +TableModelEvent +TableModelListener +TableRowSorter +TableStringConverter +TableUI +TableView +TabSet +TabStop +TabularData +TabularDataSupport +TabularType +TAG_ALTERNATE_IIOP_ADDRESS +TAG_CODE_SETS +TAG_INTERNET_IOP +TAG_JAVA_CODEBASE +TAG_MULTIPLE_COMPONENTS +TAG_ORB_TYPE +TAG_POLICIES +TAG_RMI_CUSTOM_MAX_STREAM_FORMAT +TagElement +TaggedComponent +TaggedComponentHelper +TaggedComponentHolder +TaggedProfile +TaggedProfileHelper +TaggedProfileHolder +Target +TargetDataLine +TargetedNotification +TCKind +Templates +TemplatesHandler +Text +Text +TextAction +TextArea +TextAttribute +TextComponent +TextEvent +TextField +TextHitInfo +TextInputCallback +TextLayout +TextLayout.CaretPolicy +TextListener +TextMeasurer +TextOutputCallback +TextSyntax +TextUI +TexturePaint +Thread +Thread.State +Thread.UncaughtExceptionHandler +THREAD_POLICY_ID +ThreadDeath +ThreadFactory +ThreadGroup +ThreadInfo +ThreadLocal +ThreadLocalRandom +ThreadMXBean +ThreadPolicy +ThreadPolicyOperations +ThreadPolicyValue +ThreadPoolExecutor +ThreadPoolExecutor.AbortPolicy +ThreadPoolExecutor.CallerRunsPolicy +ThreadPoolExecutor.DiscardOldestPolicy +ThreadPoolExecutor.DiscardPolicy +Throwable +Tie +TileObserver +Time +TimeLimitExceededException +TIMEOUT +TimeoutException +Timer +Timer +Timer +TimerMBean +TimerNotification +TimerTask +Timestamp +Timestamp +TimeUnit +TimeZone +TimeZoneNameProvider +TitledBorder +Tool +ToolBarUI +Toolkit +ToolProvider +ToolTipManager +ToolTipUI +TooManyListenersException +Track +TRANSACTION_MODE +TRANSACTION_REQUIRED +TRANSACTION_ROLLEDBACK +TRANSACTION_UNAVAILABLE +TransactionalWriter +TransactionRequiredException +TransactionRolledbackException +TransactionService +Transferable +TransferHandler +TransferHandler.DropLocation +TransferHandler.TransferSupport +TransferQueue +Transform +TransformAttribute +Transformer +TransformerConfigurationException +TransformerException +TransformerFactory +TransformerFactoryConfigurationError +TransformerHandler +TransformException +TransformParameterSpec +TransformService +Transient +TRANSIENT +Transmitter +Transparency +TRANSPORT_RETRY +TrayIcon +TrayIcon.MessageType +TreeCellEditor +TreeCellRenderer +TreeExpansionEvent +TreeExpansionListener +TreeMap +TreeModel +TreeModelEvent +TreeModelListener +TreeNode +TreePath +TreeSelectionEvent +TreeSelectionListener +TreeSelectionModel +TreeSet +TreeUI +TreeWillExpandListener +TrustAnchor +TrustManager +TrustManagerFactory +TrustManagerFactorySpi +Type +TypeCode +TypeCodeHolder +TypeConstraintException +TypeElement +TypeInfo +TypeInfoProvider +TypeKind +TypeKindVisitor6 +TypeKindVisitor7 +TypeMirror +TypeMismatch +TypeMismatch +TypeMismatch +TypeMismatchHelper +TypeMismatchHelper +TypeNotPresentException +TypeParameterElement +Types +Types +TypeVariable +TypeVariable +TypeVisitor +UID +UIDefaults +UIDefaults.ActiveValue +UIDefaults.LazyInputMap +UIDefaults.LazyValue +UIDefaults.ProxyLazyValue +UIEvent +UIManager +UIManager.LookAndFeelInfo +UIResource +ULongLongSeqHelper +ULongLongSeqHolder +ULongSeqHelper +ULongSeqHolder +UndeclaredThrowableException +UndoableEdit +UndoableEditEvent +UndoableEditListener +UndoableEditSupport +UndoManager +UnexpectedException +UnicastRemoteObject +UnionMember +UnionMemberHelper +UnionType +UNKNOWN +UNKNOWN +UnknownAnnotationValueException +UnknownElementException +UnknownEncoding +UnknownEncodingHelper +UnknownEntityException +UnknownError +UnknownException +UnknownFormatConversionException +UnknownFormatFlagsException +UnknownGroupException +UnknownHostException +UnknownHostException +UnknownObjectException +UnknownServiceException +UnknownTypeException +UnknownUserException +UnknownUserExceptionHelper +UnknownUserExceptionHolder +UnmappableCharacterException +UnmarshalException +UnmarshalException +Unmarshaller +Unmarshaller.Listener +UnmarshallerHandler +UnmodifiableClassException +UnmodifiableSetException +UnrecoverableEntryException +UnrecoverableKeyException +Unreferenced +UnresolvedAddressException +UnresolvedPermission +UnsatisfiedLinkError +UnsolicitedNotification +UnsolicitedNotificationEvent +UnsolicitedNotificationListener +UNSUPPORTED_POLICY +UNSUPPORTED_POLICY_VALUE +UnsupportedAddressTypeException +UnsupportedAudioFileException +UnsupportedCallbackException +UnsupportedCharsetException +UnsupportedClassVersionError +UnsupportedDataTypeException +UnsupportedEncodingException +UnsupportedFlavorException +UnsupportedLookAndFeelException +UnsupportedOperationException +URI +URIDereferencer +URIException +URIParameter +URIReference +URIReferenceException +URIResolver +URISyntax +URISyntaxException +URL +URLClassLoader +URLConnection +URLDataSource +URLDecoder +URLEncoder +URLStreamHandler +URLStreamHandlerFactory +URLStringHelper +USER_EXCEPTION +UserDataHandler +UserDefinedFileAttributeView +UserException +UserPrincipal +UserPrincipalLookupService +UserPrincipalNotFoundException +UShortSeqHelper +UShortSeqHolder +UTFDataFormatException +Util +UtilDelegate +Utilities +UUID +ValidationEvent +ValidationEventCollector +ValidationEventHandler +ValidationEventImpl +ValidationEventLocator +ValidationEventLocatorImpl +ValidationException +Validator +Validator +ValidatorHandler +ValueBase +ValueBaseHelper +ValueBaseHolder +ValueExp +ValueFactory +ValueHandler +ValueHandlerMultiFormat +ValueInputStream +ValueMember +ValueMemberHelper +ValueOutputStream +VariableElement +VariableHeightLayoutCache +Vector +VerifyError +VersionSpecHelper +VetoableChangeListener +VetoableChangeListenerProxy +VetoableChangeSupport +View +ViewFactory +ViewportLayout +ViewportUI +VirtualMachineError +Visibility +VisibilityHelper +VM_ABSTRACT +VM_CUSTOM +VM_NONE +VM_TRUNCATABLE +VMID +VoiceStatus +Void +VolatileCallSite +VolatileImage +W3CDomHandler +W3CEndpointReference +W3CEndpointReferenceBuilder +Watchable +WatchEvent +WatchEvent.Kind +WatchEvent.Modifier +WatchKey +WatchService +WCharSeqHelper +WCharSeqHolder +WeakHashMap +WeakReference +WebEndpoint +WebFault +WebMethod +WebParam +WebParam.Mode +WebResult +WebRowSet +WebService +WebServiceClient +WebServiceContext +WebServiceException +WebServiceFeature +WebServiceFeatureAnnotation +WebServicePermission +WebServiceProvider +WebServiceRef +WebServiceRefs +WildcardType +WildcardType +Window +Window.Type +WindowAdapter +WindowConstants +WindowEvent +WindowFocusListener +WindowListener +WindowStateListener +WrappedPlainView +Wrapper +WritableByteChannel +WritableRaster +WritableRenderedImage +WriteAbortedException +WritePendingException +Writer +WrongAdapter +WrongAdapterHelper +WrongMethodTypeException +WrongPolicy +WrongPolicyHelper +WrongTransaction +WrongTransactionHelper +WrongTransactionHolder +WStringSeqHelper +WStringSeqHolder +WStringValueHelper +X500Principal +X500PrivateCredential +X509Certificate +X509Certificate +X509CertSelector +X509CRL +X509CRLEntry +X509CRLSelector +X509Data +X509EncodedKeySpec +X509ExtendedKeyManager +X509ExtendedTrustManager +X509Extension +X509IssuerSerial +X509KeyManager +X509TrustManager +XAConnection +XADataSource +XAException +XAResource +Xid +XmlAccessOrder +XmlAccessorOrder +XmlAccessorType +XmlAccessType +XmlAdapter +XmlAnyAttribute +XmlAnyElement +XmlAttachmentRef +XmlAttribute +XMLConstants +XMLCryptoContext +XMLDecoder +XmlElement +XmlElement.DEFAULT +XmlElementDecl +XmlElementDecl.GLOBAL +XmlElementRef +XmlElementRef.DEFAULT +XmlElementRefs +XmlElements +XmlElementWrapper +XMLEncoder +XmlEnum +XmlEnumValue +XMLEvent +XMLEventAllocator +XMLEventConsumer +XMLEventFactory +XMLEventReader +XMLEventWriter +XMLFilter +XMLFilterImpl +XMLFormatter +XMLGregorianCalendar +XmlID +XmlIDREF +XmlInlineBinaryData +XMLInputFactory +XmlJavaTypeAdapter +XmlJavaTypeAdapter.DEFAULT +XmlJavaTypeAdapters +XmlList +XmlMimeType +XmlMixed +XmlNs +XmlNsForm +XMLObject +XMLOutputFactory +XMLParseException +XmlReader +XMLReader +XMLReaderAdapter +XMLReaderFactory +XmlRegistry +XMLReporter +XMLResolver +XmlRootElement +XmlSchema +XmlSchemaType +XmlSchemaType.DEFAULT +XmlSchemaTypes +XmlSeeAlso +XMLSignature +XMLSignature.SignatureValue +XMLSignatureException +XMLSignatureFactory +XMLSignContext +XMLStreamConstants +XMLStreamException +XMLStreamReader +XMLStreamWriter +XMLStructure +XmlTransient +XmlType +XmlType.DEFAULT +XMLValidateContext +XmlValue +XmlWriter +XPath +XPathConstants +XPathException +XPathExpression +XPathExpressionException +XPathFactory +XPathFactoryConfigurationException +XPathFilter2ParameterSpec +XPathFilterParameterSpec +XPathFunction +XPathFunctionException +XPathFunctionResolver +XPathType +XPathType.Filter +XPathVariableResolver +XSLTTransformParameterSpec +ZipEntry +ZipError +ZipException +ZipFile +ZipInputStream +ZipOutputStream +ZoneView +_BindingIteratorImplBase +_BindingIteratorStub +_DynAnyFactoryStub +_DynAnyStub +_DynArrayStub +_DynEnumStub +_DynFixedStub +_DynSequenceStub +_DynStructStub +_DynUnionStub +_DynValueStub +_IDLTypeStub +_NamingContextExtStub +_NamingContextImplBase +_NamingContextStub +_PolicyStub +_Remote_Stub +_ServantActivatorStub +_ServantLocatorStub diff --git a/lib/rotjs-library/manual/js/manual.js b/lib/rotjs-library/manual/js/manual.js new file mode 100644 index 0000000000000000000000000000000000000000..1c612af09c130ff704503b56d90dc096e397055f --- /dev/null +++ b/lib/rotjs-library/manual/js/manual.js @@ -0,0 +1,134 @@ +var Example = function(node) { + this._node = node; + + this._source = OZ.DOM.elm("pre", {className:"code"}); + this._source.setAttribute("data-syntax", "js"); + this._source.addEventListener("click", this); + + this._ta = OZ.DOM.elm("textarea", {className:"code"}); + this._ta.spellcheck = false; + this._ta.addEventListener("click", this); + + this._result = OZ.DOM.elm("pre", {className:"result"}); + + this._time = OZ.DOM.elm("div", {className:"time"}); + + this._useCode(node.textContent); +} + +Example.prototype.handleEvent = function(e) { + e.stopPropagation(); + if (this.constructor.current != this) { this.open(); } +} + +Example.prototype.open = function() { + this.constructor.current = this; + + var height = OZ.Style.get(this._source, "height"); + this._ta.style.height = height; + this._ta.value = this._source.textContent.trim(); + this._source.parentNode.replaceChild(this._ta, this._source); + this._ta.focus(); +} + +Example.prototype.close = function() { + this.constructor.current = null; + var code = this._ta.value; + this._useCode(code); +} + +/** + * @param {string} code no html entities, plain code + */ +Example.prototype._useCode = function(code) { + this._node.innerHTML = ""; + this._result.innerHTML = ""; + this._source.innerHTML = ""; + this._node.appendChild(this._source); + this._node.appendChild(this._result); + this._node.appendChild(this._time); + this._source.appendChild(OZ.DOM.text(code)); + Syntax.apply(this._source); + + var result = this._result; + var show = function() { + for (var i=0;i"; + }); + + OZ.Event.add(window, "hashchange", this._hashChange.bind(this)); + this._hashChange(); + } + +} + +Manual.init(); diff --git a/lib/rotjs-library/manual/js/oz.js b/lib/rotjs-library/manual/js/oz.js new file mode 100644 index 0000000000000000000000000000000000000000..e18a3e18f99ab9086e587f9eadd82cc64df81d1e --- /dev/null +++ b/lib/rotjs-library/manual/js/oz.js @@ -0,0 +1,335 @@ +/* (c) 2007 - now() Ondrej Zara, 1.7 */ +var OZ = { + $:function(x) { return typeof(x) == "string" ? document.getElementById(x) : x; }, + select: function(x) { return document.querySelectorAll(x); }, + opera:!!window.opera, + ie:!!document.attachEvent && !window.opera, + gecko:!!document.getAnonymousElementByAttribute, + webkit:!!navigator.userAgent.match(/webkit/i), + khtml:!!navigator.userAgent.match(/khtml/i) || !!navigator.userAgent.match(/konqueror/i), + Event:{ + _id:0, + _byName:{}, + _byID:{}, + add:function(elm,event,cb) { + var id = OZ.Event._id++; + var element = OZ.$(elm); + var fnc = (element && element.attachEvent ? function() { return cb.apply(element,arguments); } : cb); + var rec = [element,event,fnc]; + var parts = event.split(" "); + while (parts.length) { + var e = parts.pop(); + if (element) { + if (element.addEventListener) { + element.addEventListener(e,fnc,false); + } else if (element.attachEvent) { + element.attachEvent("on"+e,fnc); + } + } + if (!(e in OZ.Event._byName)) { OZ.Event._byName[e] = {}; } + OZ.Event._byName[e][id] = rec; + } + OZ.Event._byID[id] = rec; + return id; + }, + remove:function(id) { + var rec = OZ.Event._byID[id]; + if (!rec) { return; } + var elm = rec[0]; + var parts = rec[1].split(" "); + while (parts.length) { + var e = parts.pop(); + if (elm) { + if (elm.removeEventListener) { + elm.removeEventListener(e,rec[2],false); + } else if (elm.detachEvent) { + elm.detachEvent("on"+e,rec[2]); + } + } + delete OZ.Event._byName[e][id]; + } + delete OZ.Event._byID[id]; + }, + stop:function(e) { e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; }, + prevent:function(e) { e.preventDefault ? e.preventDefault() : e.returnValue = false; }, + target:function(e) { return e.target || e.srcElement; } + }, + Class:function() { + var c = function() { + var init = arguments.callee.prototype.init; + if (init) { init.apply(this,arguments); } + }; + c.implement = function(parent) { + for (var p in parent.prototype) { this.prototype[p] = parent.prototype[p]; } + return this; + }; + c.extend = function(parent) { + var tmp = function(){}; + tmp.prototype = parent.prototype; + this.prototype = new tmp(); + this.prototype.constructor = this; + return this; + }; + c.prototype.bind = function(fnc) { return fnc.bind(this); }; + c.prototype.dispatch = function(type, data) { + var obj = { + type:type, + target:this, + timeStamp:(new Date()).getTime(), + data:data + } + var tocall = []; + var list = OZ.Event._byName[type]; + for (var id in list) { + var item = list[id]; + if (!item[0] || item[0] == this) { tocall.push(item[2]); } + } + var len = tocall.length; + for (var i=0;i-1;i--) { + if (i in this && this[i] === item) { return i; } + } + return -1; + } +} +if (!Array.lastIndexOf) { + Array.lastIndexOf = function(obj, item, from) { return Array.prototype.lastIndexOf.call(obj, item, from); } +} + +if (!Array.prototype.forEach) { + Array.prototype.forEach = function(cb, _this) { + var len = this.length; + for (var i=0;i * { + border-top-right-radius: 10px; +} + +#menu li:last-child > * { + border-bottom-right-radius: 10px; +} + +#menu li ul { + position: absolute; + left: 0px; + top: 0px; + z-index: 0; +} + +/* submenu offset */ + +#menu li li:not(:first-child) a { + margin-left: 3px; +} + +#menu li li:first-child a { + padding-left: 19px; +} + +#menu li li:first-child a.active:before { + left: 5px; +} + +/* item hovers */ + +#menu li:hover > a { + background-color: #333; +} + +/* main menu transitions */ + +#menu li, #menu h2 { + -webkit-transition: all 1s; + -moz-transition: all 1s; + transition: all 1s; +} + +#menu > li:not(:first-child) { + -webkit-transform: translate(-100%, 0); + -moz-transform: translate(-100%, 0); + -ms-transform: translate(-100%, 0); + transform: translate(-100%, 0); +} + +#menu > li:first-child { + -webkit-transform-origin: 0 100%; + -moz-transform-origin: 0 100%; + -ms-transform-origin: 0 100%; + -webkit-transform-origin: 0 100%; + + -webkit-transform: rotate(90deg); + -moz-transform: rotate(90deg); + -ms-transform: rotate(90deg); + transform: rotate(90deg); +} + +#menu:hover > * { + -webkit-transform: none !important; + -moz-transform: none !important; + -ms-transform: none !important; + transform: none !important; +} + +#menu:hover h2 { + border-top-left-radius: 0px; +} + +/* submenu transitions */ + +#menu li ul { + -webkit-transition: all 0.5s; + -moz-transition: all 0.5s; + transition: all 0.5s; +} + +#menu li:hover ul { + display: block; +} + +#menu li:hover ul { + left: 180px; +} diff --git a/lib/rotjs-library/manual/pages/color.html b/lib/rotjs-library/manual/pages/color.html new file mode 100644 index 0000000000000000000000000000000000000000..ba0e3fc767de892c55692e9a4ab7f62b2be9f0c9 --- /dev/null +++ b/lib/rotjs-library/manual/pages/color.html @@ -0,0 +1,68 @@ +

    Color manipulations

    + +

    There is no dedicated Color data type in rot.js; passing strings around is sufficient in most cases (such as ROT.Display::draw). However, if you need to perform color adjustments and computations, it is suitable to represent them as arrays of numbers. For this case, the ROT.Color namespace offers a bunch of useful methods.

    + +

    Converting string → array

    + +
    +SHOW( + ROT.Color.fromString("rgb(10, 128, 230)"), + ROT.Color.fromString("#faa"), + ROT.Color.fromString("#83fcc4"), + ROT.Color.fromString("goldenrod") +);
    + +

    Converting array → string

    + +
    +SHOW( + ROT.Color.toRGB([10, 128, 230]), + ROT.Color.toHex([10, 128, 230]) +);
    + +

    Converting between RGB and HSL

    + +
    +SHOW( + ROT.Color.rgb2hsl([51, 102, 51]), + ROT.Color.hsl2rgb([0.333, 0.333, 0.3]) +);
    + +

    Adding and mixing colors

    + +

    These methods accept a variable number of arguments. Methods whose names end with an underscore modify their first argument instead of returning a new array. Note that color values are not clamped to 0..255; this happens only when serializing to a string.

    + +
    +SHOW( /* addition = lightening */ + ROT.Color.add([10, 128, 230], [200, 10, 15], [30, 30, 100]), + ROT.Color.add_([10, 128, 230], [200, 10, 15]) +); +SHOW( /* multiplication = darkening */ + ROT.Color.multiply([10, 128, 230], [200, 10, 15]), + ROT.Color.multiply_([10, 128, 230], [200, 10, 15]) +); +
    + +

    Interpolating between two colors

    + +

    The third argument specifies the interpolation factor (0 = first color, 1 = last color, 0.5 = default = halfway between them).

    + +
    +SHOW( + /* computed in RGB space */ + ROT.Color.interpolate([10, 128, 230], [30, 255, 255], 0.3), + + /* computed in HSL space */ + ROT.Color.interpolateHSL([10, 128, 230], [30, 255, 255], 0.3) +);
    + +

    Creating random variants

    + +

    You can create new colors by adjusting an exiting color by a (normally distributed) random value. Second argument is a set of standard deviations; note that ~95% of generated colors will fall within 2*stddev.

    + +
    +SHOW( + ROT.Color.randomize([100, 128, 230], [30, 10, 20]), + ROT.Color.randomize([100, 128, 230], [30, 10, 20]), + ROT.Color.randomize([100, 128, 230], [30, 10, 20]) +);
    diff --git a/lib/rotjs-library/manual/pages/display.html b/lib/rotjs-library/manual/pages/display.html new file mode 100644 index 0000000000000000000000000000000000000000..c120f7a5e58b5abc9beb0575aff1e81e28995a89 --- /dev/null +++ b/lib/rotjs-library/manual/pages/display.html @@ -0,0 +1,81 @@ +

    ASCII console display

    + +

    ROT.Display provides a canvas-based output that resembles a traditional TTY console.

    + +

    Creating a display

    + +
    +var display = new ROT.Display({width:20, height:5}); +SHOW(display.getContainer()); /* do not forget to append to page! */ +
    + +

    Configuring the display

    + +

    The display is configured using these values:

    +
      +
    • width – horizontal size, in characters
    • +
    • height – vertical size, in characters
    • +
    • fontSize – in pixels, default 15
    • +
    • fontFamily – string, default "monospace"
    • +
    • fps – int, target frames-per-second rate, default 25
    • +
    • fg – default foreground color; valid CSS color string
    • +
    • bg – default background color; valid CSS color string
    • +
    • spacing – spacing adjustment coefficient; 1 = normal, <1 tighter, >1 looser
    • +
    • layout – what layouting algorithm shall be used; "rect" or "hex"
    • +
    + +

    You can configure the display by passing a configuration object to the constructor; alternatively, all options can be changed at runtime using the setOptions method.

    + +
    +var display = new ROT.Display({width:20, height:5}); +SHOW(display.getContainer()); +display.setOptions({ + width: 30, + fontSize: 8, + fontStyle: "bold", + bg: "#a00" +}); +
    + +

    Drawing individual characters

    + +
    +var display = new ROT.Display({width:40, height:9}); +SHOW(display.getContainer()); + +display.draw(5, 4, "@"); +display.draw(15, 4, "%", "#0f0"); /* foreground color */ +display.draw(25, 4, "#", "#f00", "#009"); /* and background color */ +
    + +

    Drawing strings

    + +
    +var display = new ROT.Display({width:40, height:20}); +SHOW(display.getContainer()); + +display.drawText(5, 2, "Hello world"); + +/* last argument specifies maximum length */ +display.drawText(20, 5, "This line of text is very long.", 16); + +/* lines are broken at word boundaries; lines are trimmed */ +var words = ["lorem", "ipsum", "dolor", "sit", "amet"]; +var long = []; +for (var i=0;i<30;i++) { long.push(words.random()); } +long = long.join(" "); + +display.drawText(1, 10, long, 38); +
    + +

    Specifying foreground/background color in strings

    + +

    Colors can be changed using a trivial syntax, %c{ foreground } and %b{ background }. Empty color name switches to default.

    +
    +var display = new ROT.Display({width:40, height:5}); +SHOW(display.getContainer()); + +var str = "Goodbye %c{red}cr%b{blue}u%b{}el %c{}world" +display.drawText(5, 2, str); +
    + diff --git a/lib/rotjs-library/manual/pages/engine.html b/lib/rotjs-library/manual/pages/engine.html new file mode 100644 index 0000000000000000000000000000000000000000..4899c192ffd756f6aa3376bdff8af0844dec5934 --- /dev/null +++ b/lib/rotjs-library/manual/pages/engine.html @@ -0,0 +1,44 @@ +

    Asynchronous game engine

    + +

    Client-side JavaScript is non-blocking: all long-running operations are asynchronous. The ROT.Engine loop is well suited for orchestrating the possibly-async coordination of various game actors.

    + +

    To control a game loop, you add individual entities (called actors) to the engine. Every entity must implement the getSpeed() method (since it is fed to the built-in scheduler and the act() method. Once the engine is started, it correctly calls the act() method on proper actors. It is possible to recursively stop (lock) the engine, should some operation (such as displaying a dialog or waiting for user input) block the execution. Once all lock levels are unlocked, the engine continues its execution.

    + +
    +var engine = new ROT.Engine(); +var output = []; + +/* sample actor: pauses the execution when dead */ +var actor1 = { + getSpeed: function() { return 100; }, + lives: 3, + act: function() { + output.push("."); + this.lives--; + if (!this.lives) { + engine.removeActor(actor1); + engine.lock(); /* pause execution */ + setTimeout(unlock, 500); /* wait for 500ms */ + } + } +} +engine.addActor(actor1); + +var unlock = function() { /* called asynchronously */ + var actor2 = { + getSpeed: function() { return 100; }, + act: function() { + output.push("@"); + engine.removeActor(actor2); + } + } + + output = []; + engine.addActor(actor2); /* add second actor */ + engine.unlock(); /* continue execution */ + SHOW(output.join("")); +} + +engine.start(); +SHOW(output.join("")); +
    diff --git a/lib/rotjs-library/manual/pages/format.html b/lib/rotjs-library/manual/pages/format.html new file mode 100644 index 0000000000000000000000000000000000000000..e130e98604952ef879cbae79d139d61d33f85935 --- /dev/null +++ b/lib/rotjs-library/manual/pages/format.html @@ -0,0 +1,64 @@ +

    String formatting

    + +

    The String.format function is used to perform complex replacements within string templates. This functionality is also available in String.prototype for your convenience:

    + +
    +SHOW( + String.format("%s %s", "hello", "world"), + "%s %s".format("hello", "world") +);
    + +

    It is possible to alter and enrich the behavior of this function by adding mappings to the String.format.map object. Keys correspond to individual formatting specifiers; values are method names to be called. The default value of String.format.map is {s:"toString"}.

    + +
    +var myObj = { + foo: function() { return "bar"; } +} +String.format.map.f = "foo"; + +SHOW( "%f".format(myObj) ); +
    + +

    Finally, using formatting specifier with an upper-case letter will result in a capitalized replacement. Let's show a more convoluted example:

    + +
    +var Item = function(name) { + this._name = name; +} +Item.prototype.a = function() { + var first = this._name.charAt(0); + return (first.match(/[aeiouy]/i) ? "an" : "a") + " " + this._name; +} +Item.prototype.the = function() { + return "the " + this._name; +} + +String.format.map.a = "a"; +String.format.map.the = "the"; + +var apple = new Item("apple"); +var banana = new Item("banana"); +var template = "You eat %a. %The was delicious."; + +SHOW( template.format(apple, apple) ); +SHOW( template.format(banana, banana) ); +
    + +

    It is possible to pass additional arguments to the formatting function, using the {,} notation.

    + +
    +var Animal = function(name) { + this._name = name; +} + +Animal.prototype.adjective = function(x) { + return x + " " + this._name; +} + +String.format.map.adjective = "adjective"; + +var cat = new Animal("cat"); +var template = "You see a %{adjective,black}."; + +SHOW( template.format(cat) ); +
    diff --git a/lib/rotjs-library/manual/pages/fov.html b/lib/rotjs-library/manual/pages/fov.html new file mode 100644 index 0000000000000000000000000000000000000000..55c988edcb350b336a73bc1531308bddab363c04 --- /dev/null +++ b/lib/rotjs-library/manual/pages/fov.html @@ -0,0 +1,58 @@ +

    Field of View (FOV) computation

    + +

    FOV algorithms return a set coordinates, visible from a starting place. Computing these works in the same fashion +as Map generators do: using a user-supplied callback function. This time, however, user has to supply two callbacks:

    + +
      +
    • Input callback, passed as a constructor argument, which provides visiblity information;
    • +
    • Output callback, passed as an argument to the compute method, which receives FOV data.
    • +
    + +

    Input callback is called by the FOV algorithm to retrieve visibility information for a given coordinate pair. This callback must return true (light passes) +or false (light does nto pass). Output callback is called with these arguments: x, y, r and visibility: +the meaning is that "the place at [x,y] is visible with a distance of r". The last argument specifies the amount of visibility (0..1).

    + +

    FOV computation is initiated by calling the compute method with the following arguments:

    + +
      +
    1. x
    2. +
    3. y
    4. +
    5. r – maximum visibility radius
    6. +
    7. callback – output callback function
    8. +
    + +

    Precise shadowcasting

    + +

    For now, there is only one FOV algorithm available: the Precise Shadowcasting.

    + +
    +ROT.RNG.setSeed(12345); +ROT.DEFAULT_WIDTH = 80; +ROT.DEFAULT_HEIGHT = 30; + +var display = new ROT.Display({fontSize:12}); +SHOW(display.getContainer()); + +/* create a map */ +var data = {}; +new ROT.Map.Uniform().create(function(x, y, type) { + data[x+","+y] = type; + display.DEBUG(x, y, type); +}); + +/* input callback */ +var lightPasses = function(x, y) { + var key = x+","+y; + if (key in data) { return (data[key] == 0); } + return false; +} + +var fov = new ROT.FOV.PreciseShadowcasting(lightPasses); + +/* output callback */ +fov.compute(50, 22, 10, function(x, y, r, visibility) { + var ch = (r ? "" : "@"); + var color = (data[x+","+y] ? "#aa0": "#660"); + display.draw(x, y, ch, "#fff", color); +}); +
    diff --git a/lib/rotjs-library/manual/pages/hex/about.html b/lib/rotjs-library/manual/pages/hex/about.html new file mode 100644 index 0000000000000000000000000000000000000000..f1e3638b2b4cff3141ee4c1aed45e390f0e8cf8b --- /dev/null +++ b/lib/rotjs-library/manual/pages/hex/about.html @@ -0,0 +1,156 @@ +

    Hex support

    + +

    Hexagonal cell layout is supported in several parts of the toolkit, most notably in Console display, Cellular generator, FOV and Pathfinding. This page explains how to uses hexes with rot.js.

    + +

    While hexagonal cells provide several advantages over the traditional square/rectangular topologies, there is one big complication associated with their usage: there is no canonical way to index individual hexes. A hexagonal indexing comparison document is available for reference; rot.js is using the third variant, called double width. + +

    Displaying hexes

    + +

    There is a very trivial trick to display a rudimentary hexagonal layout: skip even/odd cells in odd/even rows. No special adjustments are necessary. The result will look good as long as the font aspect ratio is close to 1:√3 – which is the case for most monospaced fonts.

    + +
    +var display = new ROT.Display({width:8, height:5}); +SHOW(display.getContainer()); + +for (var y = 0; y < 5; y++) { + for (var x = y%2; x < 8; x += 2) { + display.draw(x, y, "•"); + } +} +
    + +

    For more advanced hexagonal stuff, switch the display to "hex" layout. This has the following advantages:

    +
      +
    • Precisely computed positioning
    • +
    • Filled background hexes
    • +
    + +
    +var display = new ROT.Display({width:8, height:5, layout:"hex"}); +SHOW(display.getContainer()); + +for (var y = 0; y < 5; y++) { + for (var x = y%2; x < 8; x += 2) { + var bg = ["#333", "#666", "#999", "#ccc", "#fff"].random(); + display.draw(x, y, "•", "#000", bg); + } +} +
    + +

    Cellular dungeon generator

    + +

    Pass the topology:6 option to the ROT.Map.Cellular constructor to operate in hexagonal mode.

    + +
    +var w = 100, h = 50; +var display = new ROT.Display({width:w, height:h, fontSize:10, layout:"hex"}); +SHOW(display.getContainer()); + +/* hexagonal map and rules */ +var map = new ROT.Map.Cellular(w, h, { + topology: 6, + born: [4, 5, 6], + survive: [3, 4, 5, 6] +}); + +/* initialize with irregularly random values */ +for (var i=0; i<w; i++) { + for (var j=0; j<h; j++) { + var dx = i/w - 0.5; + var dy = j/h - 0.5; + var dist = Math.pow(dx*dx+dy*dy, 0.3); + if (ROT.RNG.getUniform() < dist) { map.set(i, j, 1); } + } +} + +/* generate four iterations, show the last one */ +for (var i=4; i>=0; i--) { + map.create(i ? null : display.DEBUG); +} +
    + +

    Pathfinding

    + +

    All pathfinding algorithms accept the topology:6 option as well.

    + +
    +var w = 150, h = 80; +ROT.RNG.setSeed(12345); +var display = new ROT.Display({width:w, height:h, fontSize:6, layout:"hex"}); +SHOW(display.getContainer()); + +/* generate map and store its data */ +var data = {}; +var map = new ROT.Map.Cellular(w, h, { + topology: 6, + born: [4, 5, 6], + survive: [3, 4, 5, 6] +}); +map.randomize(0.48); +map.create(); /* two iterations */ +map.create(function(x, y, value) { + data[x+","+y] = value; + display.DEBUG(x, y, value); +}); + +/* input callback informs about map structure */ +var passableCallback = function(x, y) { + return (data[x+","+y] === 0); +} + +/* prepare path to given coords */ +var dijkstra = new ROT.Path.Dijkstra(120, 64, passableCallback, {topology:6}); + +/* compute from given coords */ +dijkstra.compute(30, 16, function(x, y) { + display.draw(x, y, "", "", "#800"); +}); + +/* highlight */ +display.draw(30, 16, "", "", "#3f3"); +display.draw(120, 64, "", "", "#f33"); +
    + + +

    Field of View

    + +

    Precise Shadowcasting works in hexagonal topology as well.

    + +
    +ROT.RNG.setSeed(12345); +ROT.DEFAULT_WIDTH = 44; +ROT.DEFAULT_HEIGHT = 28; + +var display = new ROT.Display({fontSize:12, layout:"hex"}); +SHOW(display.getContainer()); + +/* generate map and store its data */ +var data = {}; +var map = new ROT.Map.Cellular(null, null, { + topology: 6, + born: [4, 5, 6], + survive: [3, 4, 5, 6] +}); +map.randomize(0.4); +map.create(function(x, y, value) { + data[x+","+y] = value; + display.DEBUG(x, y, value); +}); + + +/* input callback */ +var lightPasses = function(x, y) { + var key = x+","+y; + if (key in data) { return (data[key] == 0); } + return false; +} + +var fov = new ROT.FOV.PreciseShadowcasting(lightPasses, {topology:6}); + +/* output callback */ +fov.compute(20, 14, 6, function(x, y, r, vis) { + var ch = (r ? "" : "@"); + var color = (data[x+","+y] ? "#aa0": "#660"); + display.draw(x, y, ch, "#fff", color); +}); +
    diff --git a/lib/rotjs-library/manual/pages/hex/indexing.html b/lib/rotjs-library/manual/pages/hex/indexing.html new file mode 100644 index 0000000000000000000000000000000000000000..1135c23587fc4947b4530152132b3295a6f8013f --- /dev/null +++ b/lib/rotjs-library/manual/pages/hex/indexing.html @@ -0,0 +1,127 @@ +

    Comparison of different hex indexing approaches

    + +

    + This page summarizes various types of indexing hexagonal cells. Features examined: storage (in 2D array), neighbors, distance, straight lines. +

    + +

    #1: Non-orthogonal

    + +

    Horizontal lines have constant "y" coordinate. "x" coordinate increases "down & right".

    + +
      +
    • Distance: sign(dx) == sign(dy) ? max(|dx|, |dy|) : |dx|+|dy|
    • +
    • Storage: 2D array stores a parallelogram area
    • +
    • Neighbors: (−1,0); (1,0); (−1,−1); (1,−1); (−1,1); (1,1)
    • +
    • Straight lines: (x ± n, y); (x ± n, y ± n); (x ∓ n, y ± n)
    • +
    + +
    +var o = {width:6, height:4, layout:"hex", fg:"#000", spacing:4}; +var display = new ROT.Display(o); +SHOW(display.getContainer()); + +display.draw(0, 0, "0,0", "", "#fff"); +display.draw(2, 0, "1,0", "", "#ccc"); +display.draw(4, 0, "2,0", "", "#888"); +display.draw(1, 1, "1,1", "", "#888"); +display.draw(3, 1, "2,1", "", "#fff"); +display.draw(5, 1, "3,1", "", "#ccc"); +display.draw(0, 2, "0,2", "", "#fff"); +display.draw(2, 2, "1,2", "", "#ccc"); +display.draw(4, 2, "2,2", "", "#888"); +display.draw(1, 3, "1,3", "", "#888"); +display.draw(3, 3, "2,3", "", "#fff"); +display.draw(5, 3, "3,3", "", "#ccc"); +
    + +

    #2: Odd shift

    + +

    Horizontal lines have constant "y" coordinate. "x" coordinate increases "right". Odd lines are shifted to the right (half a cell).

    + +
      +
    • Distance: max(|dy|, |dx| + floor(|dy|/2) + penalty); penalty = ( (even(y1) && odd(y2) && (x1 < x2)) || (even(y2) && odd(y1) && (x2 < x1)) ) ? 1 : 0
    • +
    • Storage: visually corresponds to a 2D array
    • +
    • Neighbors: even lines (−1,0); (1,0); (−1,−1); (0,−1); (−1,1); (0,1), odd lines (−1,0); (1,0); (0,−1); (1,−1); (0,1); (1,1)
    • +
    • Straight lines: (x ± n, y); (x ± n/2, y ± n); (x ± n/2, y ± n), even and odd lines use different rounding
    • +
    + +
    +var o = {width:6, height:4, layout:"hex", fg:"#000", spacing:4}; +var display = new ROT.Display(o); +SHOW(display.getContainer()); + +display.draw(0, 0, "0,0", "", "#fff"); +display.draw(2, 0, "1,0", "", "#ccc"); +display.draw(4, 0, "2,0", "", "#888"); +display.draw(1, 1, "0,1", "", "#888"); +display.draw(3, 1, "1,1", "", "#fff"); +display.draw(5, 1, "2,1", "", "#ccc"); +display.draw(0, 2, "0,2", "", "#fff"); +display.draw(2, 2, "1,2", "", "#ccc"); +display.draw(4, 2, "2,2", "", "#888"); +display.draw(1, 3, "0,3", "", "#888"); +display.draw(3, 3, "1,3", "", "#fff"); +display.draw(5, 3, "2,3", "", "#ccc"); +
    + +

    #3: Double width

    + +

    Horizontal lines have constant "y" coordinate. "x" coordinate increases "right" by two. Even lines have even "x" values; odd lines have odd "x" values.

    + +
      +
    • Distance: |dy| + max(0, (|dx|−|dy|)/2)
    • +
    • Storage: needs twice the storage – half of the possible coordinate values (with odd sum) is not used at all.
    • +
    • Neighbors: (−2,0); (2,0); (−1,−1); (1,1); (−1,1); (1,−1)
    • +
    • Straight lines: (x ± 2n, y); (x ± n, y ± n); (x ∓ n, y ± n)
    • +
    • Remarks: x+y is always even.
    • +
    + +
    +var o = {width:6, height:4, layout:"hex", fg:"#000", spacing:4}; +var display = new ROT.Display(o); +SHOW(display.getContainer()); + +display.draw(0, 0, "0,0", "", "#fff"); +display.draw(2, 0, "2,0", "", "#ccc"); +display.draw(4, 0, "4,0", "", "#888"); +display.draw(1, 1, "1,1", "", "#888"); +display.draw(3, 1, "3,1", "", "#fff"); +display.draw(5, 1, "5,1", "", "#ccc"); +display.draw(0, 2, "0,2", "", "#fff"); +display.draw(2, 2, "2,2", "", "#ccc"); +display.draw(4, 2, "4,2", "", "#888"); +display.draw(1, 3, "1,3", "", "#888"); +display.draw(3, 3, "3,3", "", "#fff"); +display.draw(5, 3, "5,3", "", "#ccc"); +
    + +

    #4: Cube projection

    + +

    Horizontal lines have constant "y" coordinate. Diagonal lines have constant "x" and "z" coordinates. Neighboring cells differ by 1 in two coordinates.

    + +
      +
    • Distance: max(|dx|,|dy|,|dz|)
    • +
    • Storage: WTF
    • +
    • Neighbors: (1,0,−1); (−1,0,1); (0,1,−1); (0,−1,1); (1,−1,0); (−1,1,0)
    • +
    • Straight lines: (x ± n, y, z ∓ n); (x ± n, y ∓ n, z); (x, y ± n, z ∓ n)
    • +
    • Remarks: x+y+z = 0
    • +
    + +
    +var o = {width:6, height:4, layout:"hex", fg:"#000", spacing:4}; +var display = new ROT.Display(o); +SHOW(display.getContainer()); + +display.draw(0, 0, "0,0,0", "", "#fff"); +display.draw(2, 0, "1,0,-1", "", "#ccc"); +display.draw(4, 0, "2,0,-2", "", "#888"); +display.draw(1, 1, "1,-1,0", "", "#888"); +display.draw(3, 1, "2,-1,-1", "", "#fff"); +display.draw(5, 1, "3,-1,-2", "", "#ccc"); +display.draw(0, 2, "1,-2,1", "", "#fff"); +display.draw(2, 2, "2,-2,0", "", "#ccc"); +display.draw(4, 2, "3,-2,-1", "", "#888"); +display.draw(1, 3, "2,-3,1", "", "#888"); +display.draw(3, 3, "3,-3,0", "", "#fff"); +display.draw(5, 3, "4,-3,-1", "", "#ccc"); +
    diff --git a/lib/rotjs-library/manual/pages/intro.html b/lib/rotjs-library/manual/pages/intro.html new file mode 100644 index 0000000000000000000000000000000000000000..4dd31400850abacae330eed322669a86bc9fa4c6 --- /dev/null +++ b/lib/rotjs-library/manual/pages/intro.html @@ -0,0 +1,24 @@ +

    Introduction

    + +

    rot.js was designed to provide help with traditional chores of roguelike programming. It does not use or depend on any other JS framework or library. It is an Open Source Software released under the BSD License.

    + +

    Usage

    + +

    Just download the rot.js file and include it in your page. You can then start using the functions and objects in the ROT namespace.

    + +

    Examples

    + +

    This manual is interactive: click on any example to modify its source and re-run it by clicking elsewhere. Use the navigation menu to the left to access other chapters of this manual. +
    +Note: Examples in this manual use the SHOW function, which is not a part of rot.js. This helper function is available only to interactive examples.

    + +

    Browser support

    + +

    rot.js works in all recent versions of reasonably modern browsers. More specifically, those who support the HTML5 <canvas> element: +Firefox, Chrome, Safari, Opera, Internet Explorer 9. You can check if the browser is supported:

    + +
    +SHOW( + ROT.isSupported() +) +
    diff --git a/lib/rotjs-library/manual/pages/js.html b/lib/rotjs-library/manual/pages/js.html new file mode 100644 index 0000000000000000000000000000000000000000..c8eead38f461a90107eba699005084cd136be2ef --- /dev/null +++ b/lib/rotjs-library/manual/pages/js.html @@ -0,0 +1,61 @@ +

    JavaScript prototype improvements

    + +

    rot.js adds several new methods to JavaScript primordial objects: Array, String, Number, Date, Object and Function. Some of these are ECMAScript 5 +polyfills, some are purely syntactic sugar.

    + +

    Array

    + +
    +SHOW( + ["apples", "oranges", "zombies"].random(), + ["apples", "oranges", "zombies"].randomize() +);
    + +

    String

    + +

    A more verbose explanation about how String.format works is available on a dedicated string formatting page. + +

    +SHOW( + "hello world".capitalize(), + "hello %s, this is %s".format("world", "sparta"), + "7".lpad("0", 3), + "123".rpad(".", 6) +);
    + +

    Number

    + +

    The built-in modulus operator (%) yields negative results for negative arguments. Number.prototype.mod is guaranteed to return a positive value.

    + +
    +SHOW( + ( 15) % 7 , + (-15) % 7 , + ( 15).mod(7), + (-15).mod(7) +);
    + +

    Object

    + +

    Object.create is a standardized way to create a new object with a hidden prototype link to other given object.

    + +
    +var obj1 = {price: 100}; +var obj2 = Object.create(obj1); + +SHOW(obj2.price);
    + +

    Date

    + +
    SHOW(Date.now()); /* same as new Date().getTime() */
    + +

    Function

    + +
    +var F1 = function() {}; +F1.prototype.alert = function() { SHOW("hi"); } + +var F2 = function() {}; +F2.extend(F1); + +new F2().alert();
    diff --git a/lib/rotjs-library/manual/pages/keyboard.html b/lib/rotjs-library/manual/pages/keyboard.html new file mode 100644 index 0000000000000000000000000000000000000000..e3c8f66bf0568c5cd6b50ca057369b1f57b1ea1a --- /dev/null +++ b/lib/rotjs-library/manual/pages/keyboard.html @@ -0,0 +1,38 @@ +

    Keyboard handling

    + +

    Taking care of user input boils down to listening for proper keyboard events (keydown, keypress, keyup) and processing them. rot.js does not offer any support methods or objects; instead, it defines a large set of ROT.VK_* constants to distinguish between pressed keys. For a complete listing, please check out the generated docs.

    + +

    There are also several general keyboard-related JavaScript guidelines:

    + +
      +
    1. keydown and keyup events correspond to physical keys. Check their keyCode property and compare with ROT.VK_* constants.
    2. +
    3. keypress event corresponds to a printable character being generated. Check its charCode property; String.fromCharCode(x) will create the corresponding character.
    4. +
    5. Your mileage may vary across different browsers.
    6. +
    + +

    A very simple keyboard handler is shown below:

    + +
    +var input = document.createElement("input"); +var out1 = document.createElement("div"); +var out2 = document.createElement("div"); +SHOW(input, out1, out2); +input.focus(); + +input.addEventListener("keydown", function(e) { + var code = e.keyCode; + + var vk = "?"; /* find the corresponding constant */ + for (var name in ROT) { + if (ROT[name] == code && name.indexOf("VK_") == 0) { vk = name; } + } + + out1.innerHTML = "Keydown: code is " + code + " (" + vk + ")"; +}); + +input.addEventListener("keypress", function(e) { + var code = e.charCode; + var ch = String.fromCharCode(code); + out2.innerHTML = "Keypress: char is " + ch; +}); +
    diff --git a/lib/rotjs-library/manual/pages/lighting.html b/lib/rotjs-library/manual/pages/lighting.html new file mode 100644 index 0000000000000000000000000000000000000000..9583564481e5472f746c525ecce61b7c78e5b1e1 --- /dev/null +++ b/lib/rotjs-library/manual/pages/lighting.html @@ -0,0 +1,83 @@ +

    Global lighting

    + +

    Lighting module is one of the most convoluted parts of rot.js: it is a mix of various concepts introduced in simpler components. ROT.Lighting is used to compute how multiple light sources mix and reflect in a cellular map (using a highly simplified radiosity-like algorithm).

    + +

    To compute a lighting, you need the following:

    +
      +
    • a ROT.FOV instance, which is used to compute the areas lit by light sources;
    • +
    • a lightingCallback which notifies you about the resulting light for a given coordinates;
    • +
    • a set of lights, defined by their position (x, y) and color.
    • +
    + +

    If you decide to use a two-pass lighting (more light, more realistic light spread, more computation time), you also need:

    +
      +
    • a reflectivityCallback which is used to return how much individual map cells reflect incoming light. Please note that wall cells should not reflect any light for the purpose of lighting computation.
    • +
    + +

    Finally, the ROT.Lighting function accepts an optional configuration object as its second argument. This object may contain:

    +
      +
    • range – maximum range for the most powerful light source
    • +
    • passes – number of computation passes (1: no reflectivity used, 2: reflectivity used)
    • +
    • emissionThreshold – minimal amount of light at a cell to be re-emited (only for passes>1)
    • +
    + +
    +ROT.RNG.setSeed(12345); + +ROT.DEFAULT_WIDTH = 60; +ROT.DEFAULT_HEIGHT = 40; +var mapData = {}; +var lightData = {}; + +/* build a map */ +var map = new ROT.Map.Cellular().randomize(0.5); +var createCallback = function(x, y, value) { + mapData[x+","+y] = value; +} +for (var i=0; i<4; i++) { + map.create(createCallback); +} + +/* prepare a FOV algorithm */ +var lightPasses = function(x, y) { + return (mapData[x+","+y] == 1); +} +var fov = new ROT.FOV.PreciseShadowcasting(lightPasses, {topology:4}); + +/* prepare a lighting algorithm */ +var reflectivity = function(x, y) { + return (mapData[x+","+y] == 1 ? 0.3 : 0); +} +var lighting = new ROT.Lighting(reflectivity, {range:12, passes:2}); +lighting.setFOV(fov); +lighting.setLight(12, 12, [240, 240, 30]); +lighting.setLight(20, 20, [240, 60, 60]); +lighting.setLight(45, 25, [200, 200, 200]); + +var lightingCallback = function(x, y, color) { + lightData[x+","+y] = color; +} +lighting.compute(lightingCallback); + +/* draw the resulting mix of mapData and lightData */ +var display = new ROT.Display({fontSize:8}); +SHOW(display.getContainer()); + +/* all cells are lit by ambient light; some are also lit by light sources */ +var ambientLight = [100, 100, 100]; +for (var id in mapData) { + var parts = id.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + + var baseColor = (mapData[id] ? [100, 100, 100] : [50, 50, 50]); + var light = ambientLight; + + if (id in lightData) { /* add light from our computation */ + light = ROT.Color.add(light, lightData[id]); + } + + var finalColor = ROT.Color.multiply(baseColor, light); + display.draw(x, y, null, null, ROT.Color.toRGB(finalColor)); +} +
    diff --git a/lib/rotjs-library/manual/pages/map.html b/lib/rotjs-library/manual/pages/map.html new file mode 100644 index 0000000000000000000000000000000000000000..a39b2f05119fd6d91b05b244a95a63522814a01a --- /dev/null +++ b/lib/rotjs-library/manual/pages/map.html @@ -0,0 +1,45 @@ +

    Map generation

    + +

    There are several map generator tools in rot.js; they all share the same usage pattern. You first need to instantialize the proper ROT.Map.* +object and pass size (plus any additional relevant options) to its constructor; you can then call the main create method (repeatedly, if you want).

    + +

    This toolkit does not force usage of any particular memory structure to store the map data. Instead, the map creation process is callback-based: +you supply a callback function as an argument to the create method; +the map creator will call your function repeatedly and pass it the generated map information. Your callback should accept these arguments:

    + +
      +
    • x – horizontal coordinate of a map's cell
    • +
    • y – vertical coordinate of a map's cell
    • +
    • value – integer value corresponding to the type of generated cell (different values might be supplied by different map generators)
    • +
    + +

    These examples use the simplest map generator, Arena: a fully dug room.

    + +
    +var map = new ROT.Map.Arena(3, 3); +var userCallback = function(x, y, value) { + SHOW("Value %s generated at [%s,%s]".format(value, x, y)); +} +map.create(userCallback); +
    + +

    We can use ROT.Display to show the generated map (although it would make more sense to store the generated data as well). For debugging purposes, +ROT.Display provides a built-in convenience method DEBUG, which works as a universal debugging callback.

    + +
    +var map = new ROT.Map.Arena(10, 5); + +var display1 = new ROT.Display({width:10, height:5, fontSize:18}); +SHOW(display1.getContainer()); + +map.create(function(x, y, wall) { + display1.draw(x, y, wall ? "#" : "."); +}); + +/* debugging with small font */ +var display2 = new ROT.Display({width:10, height:5, fontSize:8}); +SHOW(display2.getContainer()); +map.create(display2.DEBUG); +
    + +

    Read more about various types of generators: Maze, Cellular and Dungeon.

    diff --git a/lib/rotjs-library/manual/pages/map/cellular.html b/lib/rotjs-library/manual/pages/map/cellular.html new file mode 100644 index 0000000000000000000000000000000000000000..4c24ac9e04e276c0de68c56915bfa9fbc91db054 --- /dev/null +++ b/lib/rotjs-library/manual/pages/map/cellular.html @@ -0,0 +1,62 @@ +

    Cellular automata generator

    + +

    Interesting cave systems can be created using ROT.Map.Cellular, a generator which simulates a cellular automaton. Using this generator is a bit more complex, +because it offers richer features and is more configurable.

    + +

    Apart from the traditional width and height arguments, ROT.Map.Cellular accepts also a configuration object with the following optional keys:

    +
      +
    • born – array of neighbor counts; when an empty cell has this number of neighbors, a new cell is born
    • +
    • survive – array of neighbor counts; when an existing cell has this number of neighbors, it will survive into next iteration
    • +
    • topology – how are neighbors defined: a cell can have four, six or eight neighbors. Six neighbors correspond to the "hex" layouting algorithm + of ROT.Display.
    • +
    + +

    It is also possible to initialize/set values for the first generation of cells. Two methods are provided:

    +
      +
    • set(x, y, value) to directly set a cell
    • +
    • randomize(probability) set all cells to "alive" with a given probability (0 = no cells, 1 = all cells)
    • +
    + +

    It is possible (and desirable) to call the create method repeatedly: every call will create a new generation. There is no need to specify a callback, +if you only want to advance into next generation, without actually retrieving the current map data. By default, the born and survive options +are set according to this Roguebasin article.

    + +

    ROT.Map.Cellular uses the following callback values:

    +
      +
    • 0: no cell
    • +
    • 1: alive cell
    • +
    + +
    +var w = 80, h = 40; +var map = new ROT.Map.Cellular(w, h); + +/* cells with 1/2 probability */ +map.randomize(0.5); + +/* generate and show four generations */ +for (var i=0; i<4; i++) { + var display = new ROT.Display({width:w, height:h, fontSize:4}); + SHOW(display.getContainer()); + map.create(display.DEBUG); +} +
    + +
    +var w = 100, h = 60; +var display = new ROT.Display({width:w, height:h, fontSize:6}); +SHOW(display.getContainer()); + +/* custom born/survive rules */ +var map = new ROT.Map.Cellular(w, h, { + born: [4, 5, 6, 7, 8], + survive: [2, 3, 4, 5] +}); + +map.randomize(0.9); + +/* generate fifty iterations, show the last one */ +for (var i=49; i>=0; i--) { + map.create(i ? null : display.DEBUG); +} +
    diff --git a/lib/rotjs-library/manual/pages/map/dungeon.html b/lib/rotjs-library/manual/pages/map/dungeon.html new file mode 100644 index 0000000000000000000000000000000000000000..dde196f6990fb9f72b6c6eb12242b4fda17f1f48 --- /dev/null +++ b/lib/rotjs-library/manual/pages/map/dungeon.html @@ -0,0 +1,67 @@ +

    Dungeon generators

    + +

    This family of map generators produces corridors and rooms. Room information can be retrieved after the map has been created by calling getRooms(); corridor information can be retrieved via getCorridors():

    + +
    +ROT.RNG.setSeed(1234); +var map = new ROT.Map.Digger(); +var display = new ROT.Display({fontSize:8}); +SHOW(display.getContainer()); +map.create(display.DEBUG); + +var rooms = map.getRooms(); +for (var i=0; i<rooms.length; i++) { + var room = rooms[i]; + SHOW("Room #%s: [%s, %s] => [%s, %s]".format( + (i+1), + room.getLeft(), room.getTop(), + room.getRight(), room.getBottom() + )); +} +
    + +

    Digger

    + +

    Random dungeon generator using human-like digging patterns; based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at +Roguebasin. +Third constructor argument is a configuration object; allowed options:

    +
      +
    • roomWidth – [min, max] room size
    • +
    • roomHeight – [min, max] room size
    • +
    • corridorLength – [min, max] corridor length
    • +
    • dugPercentage – algorithm stops after this fraction of map area has been dug out; default = 0.2
    • +
    • timeLimit – algorithm stops after this amount of milliseconds has passed
    • +
    + +
    +var w = 40, h = 25; +var map = new ROT.Map.Digger(w, h); + +for (var i=0; i<4; i++) { + var display = new ROT.Display({width:w, height:h, fontSize:6}); + SHOW(display.getContainer()); + map.create(display.DEBUG); +} +
    + +

    Uniform

    + +

    Generates a set of rooms; tries to connect them afterwards. Third constructor argument is a configuration object; allowed options:

    +
      +
    • roomWidth – [min, max] room size
    • +
    • roomHeight – [min, max] room size
    • +
    • roomDugPercentage – algorithm stops after this fraction of map area has been filled with rooms; default = 0.2
    • +
    • timeLimit – algorithm stops after this amount of milliseconds has passed
    • +
    + + +
    +var w = 40, h = 25; +var map = new ROT.Map.Uniform(w, h); + +for (var i=0; i<4; i++) { + var display = new ROT.Display({width:w, height:h, fontSize:6}); + SHOW(display.getContainer()); + map.create(display.DEBUG); +} +
    diff --git a/lib/rotjs-library/manual/pages/map/maze.html b/lib/rotjs-library/manual/pages/map/maze.html new file mode 100644 index 0000000000000000000000000000000000000000..9a06fc6b097277d4834a68c1fed334aa9abfe941 --- /dev/null +++ b/lib/rotjs-library/manual/pages/map/maze.html @@ -0,0 +1,59 @@ +

    Maze generators

    + +

    This family of algorithms uses the following callback values:

    +
      +
    • 0: empty space
    • +
    • 1: wall
    • +
    + +

    DividedMaze

    + +

    Based on a Recursive division method.

    + +
    +var w = 39, h = 25; +var dm = new ROT.Map.DividedMaze(w, h); + +for (var i=0; i<4; i++) { + var display = new ROT.Display({width:w, height:h, fontSize:6}); + SHOW(display.getContainer()); + + dm.create(display.DEBUG); +} +
    + +

    Icey's Maze

    + +

    Cool mazes with a configurable regularity can be created using this algorithm, +taken from a Rogue Basin wiki. Regularity is an integer value, specified as a third argument; 0 = most random.

    + +
    +var w = 39, h = 25; + +for (var i=0; i<4; i++) { + var display = new ROT.Display({width:w, height:h, fontSize:6}); + SHOW(display.getContainer()); + + var maze = new ROT.Map.IceyMaze(w, h, 4*i); + maze.create(display.DEBUG); +} +
    + +

    Eller's Perfect Maze

    + +

    For a full explanation of this wonderful Eller's algorithm, please see +http://homepages.cwi.nl/~tromp/maze.html. +Not only it generates a Perfect maze (every two cells are connected by exactly one path), +but it only requires 2*N memory to generate a maze of N*N size!

    + +
    +var w = 39, h = 25; +var em = new ROT.Map.EllerMaze(w, h); + +for (var i=0; i<4; i++) { + var display = new ROT.Display({width:w, height:h, fontSize:6}); + SHOW(display.getContainer()); + + em.create(display.DEBUG); +} +
    diff --git a/lib/rotjs-library/manual/pages/noise.html b/lib/rotjs-library/manual/pages/noise.html new file mode 100644 index 0000000000000000000000000000000000000000..eb539034a7c599d844ec938957f7635b320a1cf3 --- /dev/null +++ b/lib/rotjs-library/manual/pages/noise.html @@ -0,0 +1,39 @@ +

    Noise generation

    + +
    +var w = 256; +var h = 100; +var noise = new ROT.Noise.Simplex(); + +var display = new ROT.Display({width:w, height:h, fontSize:3}); +SHOW(display.getContainer()); + +for (var j=0;j<h;j++) { + for (var i=0;i<w;i++) { + var val = noise.get(i/20, j/20) * 255; + + var r = ~~(val>0 ? val : 0); + var g = ~~(val<0 ? -val : 0); + display.draw(i, j, "", "", "rgb("+r+","+g+",0)"); + } +} +
    + +
    +var w = 120; +var h = 50; +var noise = new ROT.Noise.Simplex(); + +var display = new ROT.Display({width:w, height:h, fontSize:12, layout:"hex"}); +SHOW(display.getContainer()); + +for (var j=0;j<h;j++) { + for (var i=j%2;i<w;i+=2) { + var val = noise.get(i/60, j/60) * 255; + + var r = ~~(val>0 ? val : 0); + var g = ~~(val<0 ? -val : 0); + display.draw(i, j, "", "", "rgb("+r+","+g+",0)"); + } +} +
    \ No newline at end of file diff --git a/lib/rotjs-library/manual/pages/path.html b/lib/rotjs-library/manual/pages/path.html new file mode 100644 index 0000000000000000000000000000000000000000..59bb9badf603115885124d4b49d3f847e5805b2a --- /dev/null +++ b/lib/rotjs-library/manual/pages/path.html @@ -0,0 +1,104 @@ +

    Pathfinding algorithms

    + +

    The ROT.Path namespace provides utils for pathfinding: retrieving a set of coordinates represeting shortest route between two points. All pathfinding algorithms share the same usage paradigm:

    +
      +
    1. Create an input callback; function that returns passability info (true/false) for a given coordinates
    2. +
    3. Instantialize the pathfinder; pass the values of targetX, targetY and inputCallback to the constructor +
        +
      • Fourth constructor option is a configuration object; so far, only one key is supported: topology (values 4/6/8)
      • +
      +
    4. +
    5. Call the compute method with three arguments: sourceX, sourceY and outputCallback
    6. +
    + +

    The pathfinder will periodically call your outputCallback; once for every cell in the path from [sourceX, sourceY] to [targetX, targetY]. +If no such path exists, outputCallback will never be called.

    + +

    NOTE: you can call the compute method multiple times +(which is especially useful, performance-wise, when using ROT.Path.Dijkstra), +but you must make sure that the passability information of the map never changes once +the pathfinder is created.

    + +

    Dijkstra's algorithm

    + +

    Simplified version of Dijkstra's algorithm: all edges have a length of 1.

    + +
    +var w = 150, h = 80; +ROT.RNG.setSeed(12345); +var display = new ROT.Display({width:w, height:h, fontSize:6}); +SHOW(display.getContainer()); + +/* generate map and store its data */ +var data = {}; +var map = new ROT.Map.Uniform(w, h); +map.create(function(x, y, value) { + data[x+","+y] = value; + display.DEBUG(x, y, value); +}); + +/* input callback informs about map structure */ +var passableCallback = function(x, y) { + return (data[x+","+y] === 0); +} + +/* prepare path to given coords */ +var dijkstra = new ROT.Path.Dijkstra(98, 38, passableCallback); + +/* compute from given coords #1 */ +dijkstra.compute(8, 45, function(x, y) { + display.draw(x, y, "", "", "#800"); +}); + +/* compute from given coords #2 */ +dijkstra.compute(130, 8, function(x, y) { + display.draw(x, y, "", "", "#800"); +}); + +/* highlight */ +display.draw(8, 45, "", "", "#3f3"); +display.draw(130, 8, "", "", "#3f3"); +display.draw(98, 38, "", "", "#f33"); +
    + +

    A* algorithm

    + +

    Simplified version of A* algorithm: all edges have a length of 1.

    + +
    +var w = 150, h = 80; +ROT.RNG.setSeed(12345); +var display = new ROT.Display({width:w, height:h, fontSize:6}); +SHOW(display.getContainer()); + +/* generate map and store its data */ +var data = {}; +var map = new ROT.Map.Uniform(w, h); +map.create(function(x, y, value) { + data[x+","+y] = value; + display.DEBUG(x, y, value); +}); + +/* input callback informs about map structure */ +var passableCallback = function(x, y) { + return (data[x+","+y] === 0); +} + +/* prepare path to given coords */ +var astar = new ROT.Path.AStar(98, 38, passableCallback); + +/* compute from given coords #1 */ +astar.compute(8, 45, function(x, y) { + display.draw(x, y, "", "", "#800"); +}); + +/* compute from given coords #2 */ +astar.compute(130, 8, function(x, y) { + display.draw(x, y, "", "", "#800"); +}); + +/* highlight */ +display.draw(8, 45, "", "", "#3f3"); +display.draw(130, 8, "", "", "#3f3"); +display.draw(98, 38, "", "", "#f33"); +
    diff --git a/lib/rotjs-library/manual/pages/performance.html b/lib/rotjs-library/manual/pages/performance.html new file mode 100644 index 0000000000000000000000000000000000000000..3c9365e0052b9cffebf87e70e82120549cf9b8ba --- /dev/null +++ b/lib/rotjs-library/manual/pages/performance.html @@ -0,0 +1,11 @@ +

    Performance tips

    + +
      +
    • The JS file is too large? Feed it to your favorite JS minification tool, such as Google Closure Compiler.
    • + +
    • Slow display output? If you use a rectangular layout, you can enable glyph caching by calling ROT.Display.Rect.cache = true. This enables rendering into tiny cacheable canvases, but will improve performance only if you do not use too many glyph/color/bgcolor combinations. Your mileage may vary.
    • + +
    • + Too much time spent in lighting computations? Decrease the maximum light range or switch to 1-pass lighting.
    • + +
    diff --git a/lib/rotjs-library/manual/pages/rng.html b/lib/rotjs-library/manual/pages/rng.html new file mode 100644 index 0000000000000000000000000000000000000000..45fd8fc01248105a4d46fb4a27e9a90d269b4dba --- /dev/null +++ b/lib/rotjs-library/manual/pages/rng.html @@ -0,0 +1,79 @@ +

    Random Number Generator

    + +

    While the built-in Math.random() function provides suitable results for game development purposes, it has its own weaknesses. +Most notably, it is not possible to seed the generator in order to reproduce a deterministic sequence of values. This is where ROT.RNG object comes to play.

    + +

    Note: We use the excellent Alea algorithm, developed by Johannes Baagøe. For more information about the code, please see +his article on RNGs in JavaScript. Alea is distributed under the MIT License.

    + +

    Generating random values

    + +

    Three main modes of operation are available:

    + +
      +
    • ROT.RNG.getUniform() – random number [0..1) with uniform distribution (similar to Math.random())
    • +
    • ROT.RNG.getNormal(mean, stddev) – random number with normal distribution, parametrized by a mean value and standard deviation
    • +
    • ROT.RNG.getPercentage() – random integer 1..100
    • +
    + +
    +SHOW( + ROT.RNG.getUniform(), + ROT.RNG.getNormal(0, 10), + ROT.RNG.getPercentage() +) +
    + +
    +var canvas = document.createElement("canvas"); +canvas.width = 500; +canvas.height = 200; +SHOW(canvas); + +var ctx = canvas.getContext("2d"); +ctx.fillStyle = "#fff"; +ctx.fillRect(0, 0, canvas.width, canvas.height); +ctx.fillStyle = "#f00"; + +var data = []; +for (var i=0;i<40000;i++) { /* generate histogram */ + var num = Math.round(ROT.RNG.getNormal(250, 100)); + data[num] = (data[num] || 0) + 1; +} + +for (var i=0;i<data.length;i++) { /* plot histogram */ + ctx.fillRect(i, canvas.height-data[i], 1, data[i]); +} +
    + + +

    Working with RNG state

    + +

    RNG's internal state can be retrieved and set to produce identical results.

    + +
    +var state = ROT.RNG.getState(); +SHOW(ROT.RNG.getUniform()); + +ROT.RNG.setState(state); +SHOW(ROT.RNG.getUniform()); +
    + +

    The RNG can be seeded by a given number. Seeding initializes RNG's internal state. +Retrieving the current seed is not very useful, but might come handy if you want to reproduce a behavior resulting from a random seed.

    + +
    +var seed = ROT.RNG.getSeed(); + +ROT.RNG.setSeed(12345); +SHOW( + ROT.RNG.getUniform(), + ROT.RNG.getUniform() +); + +ROT.RNG.setSeed(12345); +SHOW( + ROT.RNG.getUniform(), + ROT.RNG.getUniform() +); +
    diff --git a/lib/rotjs-library/manual/pages/scheduler.html b/lib/rotjs-library/manual/pages/scheduler.html new file mode 100644 index 0000000000000000000000000000000000000000..916b5698a868d253b846c55153d4e3ec661a1905 --- /dev/null +++ b/lib/rotjs-library/manual/pages/scheduler.html @@ -0,0 +1,37 @@ +

    Turn scheduling

    + +

    In turn-based games, actors (player, enemies, everything that moves or acts) often differ by their speed. However, since the game happens in turns, +the speed is more accurately described as a frequency in which turns happen for a particular actor. ROT.Scheduler is a simple tool designed to +simplify the task of selecting proper actor for a turn, based on the abstract speed of all actors.

    + +

    First, you need to fill the scheduler instance with actors. There are very few requirements on actors: they need to be JS objects with method getSpeed(), +which returns a number. An actor with speed=100 will get twice as many turns as actor with speed=50.
    +You can then repeatedly call the scheduler's next() method: it returns the actor whose turn should start.

    + +
    +var scheduler = new ROT.Scheduler(); +var getSpeed = function() { + return this.speed; +} + +/* generate four actors */ +for (var i=0;i<4;i++) { + var actor = { + speed: ROT.RNG.getPercentage(), + number: i+1, + getSpeed: getSpeed + } + scheduler.add(actor); + SHOW("Object #%s has speed %s.".format(actor.number, actor.speed)); +} + +/* simulate several turns */ +var turns = []; +for (var i=0;i<40;i++) { + var next = scheduler.next(); + turns.push(next.number); +} + +SHOW("\nGenerated order of turns:"); +SHOW(turns.join(" ") + " ..."); +
    diff --git a/lib/rotjs-library/manual/pages/stringgenerator.html b/lib/rotjs-library/manual/pages/stringgenerator.html new file mode 100644 index 0000000000000000000000000000000000000000..b171fa9284bf42985774828c6c9731fd628ec7e7 --- /dev/null +++ b/lib/rotjs-library/manual/pages/stringgenerator.html @@ -0,0 +1,34 @@ +

    String generator

    + +

    ROT.StringGenerator is an implementation of a high order Markov process. This machine learning technique needs to be trained first (with a set of typical strings); after training, it generates strings similar to those used as a training set.

    + +

    Read more about the implementation (Dirichlet prior, simplified Katz back-off) in this RogueBasin article. The constructor accepts an optional configuration object with the following keys:

    + +
      +
    • words – use word mode? (default: false, use letters instead)
    • +
    • order – how many preceding characters are used to generate next character
    • +
    • prior – default probability weight for all (unexpected) events (Dirichlet prior)
    • +
    + +

    There are only two important public methods: observe() for training and generate() for producing results. In the following example, we will use all standard Java 7 class names as a training set; let's see what new Java stuff our generator produces.

    + +
    +var sg = new ROT.StringGenerator(); + +var r = new XMLHttpRequest(); +r.open("get", "java.txt", true); +r.send(); + +r.onreadystatechange = function() { + if (r.readyState != 4) { return; } + + var lines = r.responseText.split("\n"); + while (lines.length) { + var line = lines.pop().trim(); + if (!line) { continue; } + sg.observe(line); + } + + for (var i=0; i<20; i++) { SHOW(sg.generate()); } +} +
    diff --git a/lib/rotjs-library/manual/syntax/syntax-js.js b/lib/rotjs-library/manual/syntax/syntax-js.js new file mode 100644 index 0000000000000000000000000000000000000000..dbc2243050092a0f285e36eafb0746cd9eb1d647 --- /dev/null +++ b/lib/rotjs-library/manual/syntax/syntax-js.js @@ -0,0 +1,41 @@ +;(function(){ + var patterns = []; + + patterns.push({ + token: "string", + re: /(".*?")/g, + index: 1 + }); + + patterns.push({ + token: "number", + re: /([^0-9#a-z])(-?[0-9]+(\.[0-9]+)?)/ig, + index: 2 + }); + + patterns.push({ + token: "comment", + re: /(\/\*[\s\S]*?\*\/)/g, + index: 1 + }); + + patterns.push({ + token: "comment", + re: /([^:])(\/\/.*)/g, + index: 2 + }); + + var keywords = ["break", "case", "catch", "continue", "default", "delete", "do", "else", + "finally", "for", "function", "if", "in", "instanceof", "new", "return", + "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with", "__proto__", + "true", "false", "null", "NaN", "prototype", "call", "apply", "constructor"]; + + var kw = new RegExp("(^|\\s|\\.|\\(|!)("+keywords.join("|")+")(?=\\s|\\.|\\(|\\)|\\[|\\]|;|$|,)","gm"); + patterns.push({ + token: "keyword", + re: kw, + index: 2 + }); + + Syntax.register("js", patterns); +})(); diff --git a/lib/rotjs-library/manual/syntax/syntax.css b/lib/rotjs-library/manual/syntax/syntax.css new file mode 100644 index 0000000000000000000000000000000000000000..73b638281a885b1796ce970553f915ed3e184b98 --- /dev/null +++ b/lib/rotjs-library/manual/syntax/syntax.css @@ -0,0 +1,15 @@ +.keyword { + color: #33a; +} + +.number { + color: #a33; +} + +.string, .string * { + color: #555; +} + +.comment, .comment * { + color: #282; +} diff --git a/lib/rotjs-library/manual/syntax/syntax.js b/lib/rotjs-library/manual/syntax/syntax.js new file mode 100644 index 0000000000000000000000000000000000000000..facc9de238318de2e58cc051fc04b46124c11297 --- /dev/null +++ b/lib/rotjs-library/manual/syntax/syntax.js @@ -0,0 +1,119 @@ +var Syntax = { + base: "", /* base path */ + tab: " ", + + _registry: {}, + _todo: {}, + + /* apply to all elements */ + all: function() { + var all = document.getElementsByTagName("*"); + var todo = []; + for (var i=0;i/g, ">"); + + for (var i=0;i 1) { + for (var j=1;j$"+index+""; + + code = code.replace(pattern.re, replacement); + } + + code = code.replace(/\t/g, this.tab); + + if (node.outerHTML) { /* IE hack; innerHTML normalizes whitespace */ + node.innerHTML = ""; + + var tmp = document.createElement("div"); + tmp.style.display = "none"; + document.body.insertBefore(tmp, document.body.firstChild); + + var pre = document.createElement("pre"); + tmp.appendChild(pre); + pre.outerHTML = "
    " + code + "
    "; + + while (tmp.firstChild.firstChild) { node.appendChild(tmp.firstChild.firstChild); } + tmp.parentNode.removeChild(tmp); + } else { + node.innerHTML = code; + } + }, + + _append: function(syntax) { + var s = document.createElement("script"); + s.src = this.base + "syntax-"+syntax+".js"; + + var thisp = this; + var loaded = function() { thisp._loaded(); } + + if (s.addEventListener) { + s.addEventListener("load", loaded, false); + } else { + s.attachEvent("onreadystatechange", loaded); + } + + document.body.insertBefore(s, document.body.firstChild); + }, + + _loaded: function() { + for (var syntax in this._registry) { + if (!(syntax in this._todo)) { continue; } + while (this._todo[syntax].length) { + this._process(this._todo[syntax].shift(), syntax); + } + delete this._todo[syntax]; + } + } +}; + +Syntax.init(); + diff --git a/lib/rotjs-library/push.sh b/lib/rotjs-library/push.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd2116ab07700874a9da60521ce44e7b5f15636f --- /dev/null +++ b/lib/rotjs-library/push.sh @@ -0,0 +1,6 @@ +#!/bin/sh + +hg bookmark -f master +hg bookmark -f gh-pages +hg push github +hg push -B master -B gh-pages diff --git a/lib/rotjs-library/rot.js b/lib/rotjs-library/rot.js new file mode 100644 index 0000000000000000000000000000000000000000..c4226b9e019dcf617ae11b87abb4442260d0805f --- /dev/null +++ b/lib/rotjs-library/rot.js @@ -0,0 +1,4092 @@ +/* + This is rot.js, the ROguelike Toolkit in JavaScript. + Version 0.4~dev, generated on Fri Mar 8 11:07:22 CET 2013. +*/ + +/** + * @namespace Top-level ROT namespace + */ +var ROT = { + /** + * @returns {bool} Is rot.js supported by this browser? + */ + isSupported: function() { + return !!(document.createElement("canvas").getContext && Function.prototype.bind); + }, + + /** Default with for display and map generators */ + DEFAULT_WIDTH: 80, + /** Default height for display and map generators */ + DEFAULT_HEIGHT: 25, + + /** Directional constants. Ordering is important! */ + DIRS: { + "4": [ + [ 0, -1], + [ 1, 0], + [ 0, 1], + [-1, 0] + ], + "8": [ + [ 0, -1], + [ 1, -1], + [ 1, 0], + [ 1, 1], + [ 0, 1], + [-1, 1], + [-1, 0], + [-1, -1] + ], + "6": [ + [-1, -1], + [ 1, -1], + [ 2, 0], + [ 1, 1], + [-1, 1], + [-2, 0] + ] + }, + + /** Cancel key. */ + VK_CANCEL: 3, + /** Help key. */ + VK_HELP: 6, + /** Backspace key. */ + VK_BACK_SPACE: 8, + /** Tab key. */ + VK_TAB: 9, + /** 5 key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key. */ + VK_CLEAR: 12, + /** Return/enter key on the main keyboard. */ + VK_RETURN: 13, + /** Reserved, but not used. */ + VK_ENTER: 14, + /** Shift key. */ + VK_SHIFT: 16, + /** Control key. */ + VK_CONTROL: 17, + /** Alt (Option on Mac) key. */ + VK_ALT: 18, + /** Pause key. */ + VK_PAUSE: 19, + /** Caps lock. */ + VK_CAPS_LOCK: 20, + /** Escape key. */ + VK_ESCAPE: 27, + /** Space bar. */ + VK_SPACE: 32, + /** Page Up key. */ + VK_PAGE_UP: 33, + /** Page Down key. */ + VK_PAGE_DOWN: 34, + /** End key. */ + VK_END: 35, + /** Home key. */ + VK_HOME: 36, + /** Left arrow. */ + VK_LEFT: 37, + /** Up arrow. */ + VK_UP: 38, + /** Right arrow. */ + VK_RIGHT: 39, + /** Down arrow. */ + VK_DOWN: 40, + /** Print Screen key. */ + VK_PRINTSCREEN: 44, + /** Ins(ert) key. */ + VK_INSERT: 45, + /** Del(ete) key. */ + VK_DELETE: 46, + /***/ + VK_0: 48, + /***/ + VK_1: 49, + /***/ + VK_2: 50, + /***/ + VK_3: 51, + /***/ + VK_4: 52, + /***/ + VK_5: 53, + /***/ + VK_6: 54, + /***/ + VK_7: 55, + /***/ + VK_8: 56, + /***/ + VK_9: 57, + /** Colon (:) key. Requires Gecko 15.0 */ + VK_COLON: 58, + /** Semicolon (;) key. */ + VK_SEMICOLON: 59, + /** Less-than (<) key. Requires Gecko 15.0 */ + VK_LESS_THAN: 60, + /** Equals (=) key. */ + VK_EQUALS: 61, + /** Greater-than (>) key. Requires Gecko 15.0 */ + VK_GREATER_THAN: 62, + /** Question mark (?) key. Requires Gecko 15.0 */ + VK_QUESTION_MARK: 63, + /** Atmark (@) key. Requires Gecko 15.0 */ + VK_AT: 64, + /***/ + VK_A: 65, + /***/ + VK_B: 66, + /***/ + VK_C: 67, + /***/ + VK_D: 68, + /***/ + VK_E: 69, + /***/ + VK_F: 70, + /***/ + VK_G: 71, + /***/ + VK_H: 72, + /***/ + VK_I: 73, + /***/ + VK_J: 74, + /***/ + VK_K: 75, + /***/ + VK_L: 76, + /***/ + VK_M: 77, + /***/ + VK_N: 78, + /***/ + VK_O: 79, + /***/ + VK_P: 80, + /***/ + VK_Q: 81, + /***/ + VK_R: 82, + /***/ + VK_S: 83, + /***/ + VK_T: 84, + /***/ + VK_U: 85, + /***/ + VK_V: 86, + /***/ + VK_W: 87, + /***/ + VK_X: 88, + /***/ + VK_Y: 89, + /***/ + VK_Z: 90, + /***/ + VK_CONTEXT_MENU: 93, + /** 0 on the numeric keypad. */ + VK_NUMPAD0: 96, + /** 1 on the numeric keypad. */ + VK_NUMPAD1: 97, + /** 2 on the numeric keypad. */ + VK_NUMPAD2: 98, + /** 3 on the numeric keypad. */ + VK_NUMPAD3: 99, + /** 4 on the numeric keypad. */ + VK_NUMPAD4: 100, + /** 5 on the numeric keypad. */ + VK_NUMPAD5: 101, + /** 6 on the numeric keypad. */ + VK_NUMPAD6: 102, + /** 7 on the numeric keypad. */ + VK_NUMPAD7: 103, + /** 8 on the numeric keypad. */ + VK_NUMPAD8: 104, + /** 9 on the numeric keypad. */ + VK_NUMPAD9: 105, + /** * on the numeric keypad. */ + VK_MULTIPLY: 106, + /** + on the numeric keypad. */ + VK_ADD: 107, + /***/ + VK_SEPARATOR: 108, + /** - on the numeric keypad. */ + VK_SUBTRACT: 109, + /** Decimal point on the numeric keypad. */ + VK_DECIMAL: 110, + /** / on the numeric keypad. */ + VK_DIVIDE: 111, + /** F1 key. */ + VK_F1: 112, + /** F2 key. */ + VK_F2: 113, + /** F3 key. */ + VK_F3: 114, + /** F4 key. */ + VK_F4: 115, + /** F5 key. */ + VK_F5: 116, + /** F6 key. */ + VK_F6: 117, + /** F7 key. */ + VK_F7: 118, + /** F8 key. */ + VK_F8: 119, + /** F9 key. */ + VK_F9: 120, + /** F10 key. */ + VK_F10: 121, + /** F11 key. */ + VK_F11: 122, + /** F12 key. */ + VK_F12: 123, + /** F13 key. */ + VK_F13: 124, + /** F14 key. */ + VK_F14: 125, + /** F15 key. */ + VK_F15: 126, + /** F16 key. */ + VK_F16: 127, + /** F17 key. */ + VK_F17: 128, + /** F18 key. */ + VK_F18: 129, + /** F19 key. */ + VK_F19: 130, + /** F20 key. */ + VK_F20: 131, + /** F21 key. */ + VK_F21: 132, + /** F22 key. */ + VK_F22: 133, + /** F23 key. */ + VK_F23: 134, + /** F24 key. */ + VK_F24: 135, + /** Num Lock key. */ + VK_NUM_LOCK: 144, + /** Scroll Lock key. */ + VK_SCROLL_LOCK: 145, + /** Circumflex (^) key. Requires Gecko 15.0 */ + VK_CIRCUMFLEX: 160, + /** Exclamation (!) key. Requires Gecko 15.0 */ + VK_EXCLAMATION: 161, + /** Double quote () key. Requires Gecko 15.0 */ + VK_DOUBLE_QUOTE: 162, + /** Hash (#) key. Requires Gecko 15.0 */ + VK_HASH: 163, + /** Dollar sign ($) key. Requires Gecko 15.0 */ + VK_DOLLAR: 164, + /** Percent (%) key. Requires Gecko 15.0 */ + VK_PERCENT: 165, + /** Ampersand (&) key. Requires Gecko 15.0 */ + VK_AMPERSAND: 166, + /** Underscore (_) key. Requires Gecko 15.0 */ + VK_UNDERSCORE: 167, + /** Open parenthesis (() key. Requires Gecko 15.0 */ + VK_OPEN_PAREN: 168, + /** Close parenthesis ()) key. Requires Gecko 15.0 */ + VK_CLOSE_PAREN: 169, + /* Asterisk (*) key. Requires Gecko 15.0 */ + VK_ASTERISK: 170, + /** Plus (+) key. Requires Gecko 15.0 */ + VK_PLUS: 171, + /** Pipe (|) key. Requires Gecko 15.0 */ + VK_PIPE: 172, + /** Hyphen-US/docs/Minus (-) key. Requires Gecko 15.0 */ + VK_HYPHEN_MINUS: 173, + /** Open curly bracket ({) key. Requires Gecko 15.0 */ + VK_OPEN_CURLY_BRACKET: 174, + /** Close curly bracket (}) key. Requires Gecko 15.0 */ + VK_CLOSE_CURLY_BRACKET: 175, + /** Tilde (~) key. Requires Gecko 15.0 */ + VK_TILDE: 176, + /** Comma (,) key. */ + VK_COMMA: 188, + /** Period (.) key. */ + VK_PERIOD: 190, + /** Slash (/) key. */ + VK_SLASH: 191, + /** Back tick (`) key. */ + VK_BACK_QUOTE: 192, + /** Open square bracket ([) key. */ + VK_OPEN_BRACKET: 219, + /** Back slash (\) key. */ + VK_BACK_SLASH: 220, + /** Close square bracket (]) key. */ + VK_CLOSE_BRACKET: 221, + /** Quote (''') key. */ + VK_QUOTE: 222, + /** Meta key on Linux, Command key on Mac. */ + VK_META: 224, + /** AltGr key on Linux. Requires Gecko 15.0 */ + VK_ALTGR: 225, + /** Windows logo key on Windows. Or Super or Hyper key on Linux. Requires Gecko 15.0 */ + VK_WIN: 91, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANA: 21, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANGUL: 21, + /** 英数 key on Japanese Mac keyboard. Requires Gecko 15.0 */ + VK_EISU: 22, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_JUNJA: 23, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_FINAL: 24, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANJA: 25, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANJI: 25, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_CONVERT: 28, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_NONCONVERT: 29, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_ACCEPT: 30, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_MODECHANGE: 31, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SELECT: 41, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_PRINT: 42, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_EXECUTE: 43, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SLEEP: 95 +}; +/** + * @namespace + * Contains text tokenization and breaking routines + */ +ROT.Text = { + RE_COLORS: /%([bc]){([^}]*)}/g, + + /* token types */ + TYPE_TEXT: 0, + TYPE_NEWLINE: 1, + TYPE_FG: 2, + TYPE_BG: 3, + + /** + * Measure size of a resulting text block + */ + measure: function(str, maxWidth) { + var result = {width:0, height:1}; + var tokens = this.tokenize(str, maxWidth); + var lineWidth = 0; + + for (var i=0;i maxWidth) { /* line too long, find a suitable breaking spot */ + + /* is it possible to break within this token? */ + var index = -1; + while (1) { + var nextIndex = token.value.indexOf(" ", index+1); + if (nextIndex == -1) { break; } + if (lineLength + nextIndex > maxWidth) { break; } + index = nextIndex; + } + + if (index != -1) { /* break at space within this one */ + token.value = this._breakInsideToken(tokens, i, index, true); + } else if (lastTokenWithSpace != -1) { /* is there a previous token where a break can occur? */ + var token = tokens[lastTokenWithSpace]; + var breakIndex = token.value.lastIndexOf(" "); + token.value = this._breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true); + i = lastTokenWithSpace; + } else { /* force break in this token */ + token.value = this._breakInsideToken(tokens, i, maxWidth-lineLength, false); + } + + } else { /* line not long, continue */ + lineLength += token.value.length; + if (token.value.indexOf(" ") != -1) { lastTokenWithSpace = i; } + } + + i++; /* advance to next token */ + } + + + tokens.push({type: ROT.Text.TYPE_NEWLINE}); /* insert fake newline to fix the last text line */ + + /* remove trailing space from text tokens before newlines */ + var lastTextToken = null; + for (var i=0;i minItem.item.getSpeed()) { + minItem = item; + } + } + + if (minBucket) { /* non-zero value; subtract from all buckets */ + for (var i=0;i 1) { /* too wide with current aspect ratio */ + boxHeight = Math.floor(boxHeight / widthFraction); + } + return Math.floor(boxHeight / this._options.spacing); +} +/** + * @class Hexagonal backend + * @private + */ +ROT.Display.Hex = function(context) { + ROT.Display.Backend.call(this, context); + + this._spacingX = 0; + this._spacingY = 0; + this._hexSize = 0; + this._options = {}; +} +ROT.Display.Hex.extend(ROT.Display.Backend); + +ROT.Display.Hex.prototype.compute = function(options) { + this._options = options; + + var charWidth = Math.ceil(this._context.measureText("W").width); + this._hexSize = Math.floor(options.spacing * (options.fontSize + charWidth/Math.sqrt(3)) / 2); + this._spacingX = this._hexSize * Math.sqrt(3) / 2; + this._spacingY = this._hexSize * 1.5; + this._context.canvas.width = Math.ceil( (options.width + 1) * this._spacingX ); + this._context.canvas.height = Math.ceil( (options.height - 1) * this._spacingY + 2*this._hexSize ); +} + +ROT.Display.Hex.prototype.draw = function(data, clearBefore) { + var x = data[0]; + var y = data[1]; + var ch = data[2]; + var fg = data[3]; + var bg = data[4]; + + var cx = (x+1) * this._spacingX; + var cy = y * this._spacingY + this._hexSize; + + if (clearBefore) { + this._context.fillStyle = bg; + this._fill(cx, cy); + } + + if (!ch) { return; } + + this._context.fillStyle = fg; + this._context.fillText(ch, cx, cy); +} + + +ROT.Display.Hex.prototype.computeSize = function(availWidth, availHeight) { + var width = Math.floor(availWidth / this._spacingX) - 1; + var height = Math.floor((availHeight - 2*this._hexSize) / this._spacingY + 1); + return [width, height]; +} + +ROT.Display.Hex.prototype.computeFontSize = function(availWidth, availHeight) { + var hexSizeWidth = 2*availWidth / ((this._options.width+1) * Math.sqrt(3)) - 1; + var hexSizeHeight = availHeight / (2 + 1.5*(this._options.height-1)); + var hexSize = Math.min(hexSizeWidth, hexSizeHeight); + + /* compute char ratio */ + var oldFont = this._context.font; + this._context.font = "100px " + this._options.fontFamily; + var width = Math.ceil(this._context.measureText("W").width); + this._context.font = oldFont; + var ratio = width / 100; + + hexSize = Math.floor(hexSize)+1; /* closest larger hexSize */ + + var fontSize = 2*hexSize / (this._options.spacing * (1 + ratio / Math.sqrt(3))); + + /* closest smaller fontSize */ + return Math.ceil(fontSize)-1; +} + +ROT.Display.Hex.prototype._fill = function(cx, cy) { + var a = this._hexSize; + var b = this._options.border; + + this._context.beginPath(); + this._context.moveTo(cx, cy-a+b); + this._context.lineTo(cx + this._spacingX - b, cy-a/2+b); + this._context.lineTo(cx + this._spacingX - b, cy+a/2-b); + this._context.lineTo(cx, cy+a-b); + this._context.lineTo(cx - this._spacingX + b, cy+a/2-b); + this._context.lineTo(cx - this._spacingX + b, cy-a/2+b); + this._context.lineTo(cx, cy-a+b); + this._context.fill(); +} +/** + * @namespace + * This code is an implementation of Alea algorithm; (C) 2010 Johannes Baagøe. + * Alea is licensed according to the http://en.wikipedia.org/wiki/MIT_License. + */ +ROT.RNG = { + /** + * @returns {number} + */ + getSeed: function() { + return this._seed; + }, + + /** + * @param {number} seed Seed the number generator + */ + setSeed: function(seed) { + seed = (seed < 1 ? 1/seed : seed); + + this._seed = seed; + this._s0 = (seed >>> 0) * this._frac; + + seed = (seed*69069 + 1) >>> 0; + this._s1 = seed * this._frac; + + seed = (seed*69069 + 1) >>> 0; + this._s2 = seed * this._frac; + + this._c = 1; + return this; + }, + + /** + * @returns {float} Pseudorandom value [0,1), uniformly distributed + */ + getUniform: function() { + var t = 2091639 * this._s0 + this._c * this._frac; + this._s0 = this._s1; + this._s1 = this._s2; + this._c = t | 0; + this._s2 = t - this._c; + return this._s2; + }, + + /** + * @param {float} [mean=0] Mean value + * @param {float} [stddev=1] Standard deviation. ~95% of the absolute values will be lower than 2*stddev. + * @returns {float} A normally distributed pseudorandom value + */ + getNormal: function(mean, stddev) { + do { + var u = 2*this.getUniform()-1; + var v = 2*this.getUniform()-1; + var r = u*u + v*v; + } while (r > 1 || r == 0); + + var gauss = u * Math.sqrt(-2*Math.log(r)/r); + return (mean || 0) + gauss*(stddev || 1); + }, + + /** + * @returns {int} Pseudorandom value [1,100] inclusive, uniformly distributed + */ + getPercentage: function() { + return 1 + Math.floor(this.getUniform()*100); + }, + + /** + * @param {object} data key=whatever, value=weight (relative probability) + * @returns {string} whatever + */ + getWeightedValue: function(data) { + var avail = []; + var total = 0; + + for (var id in data) { + total += data[id]; + } + var random = Math.floor(this.getUniform()*total); + + var part = 0; + for (var id in data) { + part += data[id]; + if (random < part) { return id; } + } + + return null; + }, + + /** + * Get RNG state. Useful for storing the state and re-setting it via setState. + * @returns {?} Internal state + */ + getState: function() { + return [this._s0, this._s1, this._s2, this._c]; + }, + + /** + * Set a previously retrieved state. + * @param {?} state + */ + setState: function(state) { + this._s0 = state[0]; + this._s1 = state[1]; + this._s2 = state[2]; + this._c = state[3]; + return this; + }, + + _s0: 0, + _s1: 0, + _s2: 0, + _c: 0, + _frac: 2.3283064365386963e-10 /* 2^-32 */ +} + +ROT.RNG.setSeed(Date.now()); +/** + * @class (Markov process)-based string generator. + * Copied from a RogueBasin article. + * Offers configurable order and prior. + * @param {object} [options] + * @param {bool} [options.words=false] Use word mode? + * @param {int} [options.order=3] + * @param {float} [options.prior=0.001] + */ +ROT.StringGenerator = function(options) { + this._options = { + words: false, + order: 3, + prior: 0.001 + } + for (var p in options) { this._options[p] = options[p]; } + + this._boundary = String.fromCharCode(0); + this._suffix = this._boundary; + this._prefix = []; + for (var i=0;i this._options.order) { + context = context.slice(-this._options.order); + } else if (context.length < this._options.order) { + context = this._prefix.slice(0, this._options.order - context.length).concat(context); + } + + while (!(this._join(context) in this._data) && context.length > 0) { context = context.slice(1); } + + return context; +} + + +ROT.StringGenerator.prototype._pickRandom = function(data) { + var total = 0; + + for (var id in data) { + total += data[id]; + } + var random = ROT.RNG.getUniform()*total; + + var part = 0; + for (var id in data) { + part += data[id]; + if (random < part) { return id; } + } +} +/** + * @class Base map generator + * @param {int} [width=ROT.DEFAULT_WIDTH] + * @param {int} [height=ROT.DEFAULT_HEIGHT] + */ +ROT.Map = function(width, height) { + this._width = width || ROT.DEFAULT_WIDTH; + this._height = height || ROT.DEFAULT_HEIGHT; +}; + +ROT.Map.prototype.create = function(callback) {} + +ROT.Map.prototype._fillMap = function(value) { + var map = []; + for (var i=0;i= width || y >= height) { return false; } + return map[x][y]; +} +/** + * @class Maze generator - Eller's algorithm + * See http://homepages.cwi.nl/~tromp/maze.html for explanation + * @augments ROT.Map + */ +ROT.Map.EllerMaze = function(width, height) { + ROT.Map.call(this, width, height); +} +ROT.Map.EllerMaze.extend(ROT.Map); + +ROT.Map.EllerMaze.prototype.create = function(callback) { + var map = this._fillMap(1); + var w = Math.ceil((this._width-2)/2); + + var rand = 9/24; + + var L = []; + var R = []; + + for (var i=0;i rand) { + this._addToList(i, L, R); + map[x+1][y] = 0; + } + + /* bottom connection */ + if (i != L[i] && ROT.RNG.getUniform() > rand) { + /* remove connection */ + this._removeFromList(i, L, R); + } else { + /* create connection */ + map[x][y+1] = 0; + } + } + } + + /* last row */ + for (var i=0;i rand)) { + /* dig right also if the cell is separated, so it gets connected to the rest of maze */ + this._addToList(i, L, R); + map[x+1][y] = 0; + } + + this._removeFromList(i, L, R); + } + + for (var i=0;i= this._width || x < 0 || y >= this._width) { continue; } + result += (this._map[x][y] == 1 ? 1 : 0); + } + + return result; +} +/** + * @class Dungeon map: has rooms and corridors + * @augments ROT.Map + */ +ROT.Map.Dungeon = function(width, height) { + ROT.Map.call(this, width, height); + this._rooms = []; /* list of all rooms */ + this._corridors = []; +} +ROT.Map.Dungeon.extend(ROT.Map); + +/** + * Get all generated rooms + * @returns {ROT.Map.Feature.Room[]} + */ +ROT.Map.Dungeon.prototype.getRooms = function() { + return this._rooms; +} + +/** + * Get all generated corridors + * @returns {ROT.Map.Feature.Corridor[]} + */ +ROT.Map.Dungeon.prototype.getCorridors = function() { + return this._corridors; +} +/** + * @class Random dungeon generator using human-like digging patterns. + * Heavily based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at + * http://www.roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm. + * @augments ROT.Map.Dungeon + */ +ROT.Map.Digger = function(width, height, options) { + ROT.Map.Dungeon.call(this, width, height); + + this._options = { + roomWidth: [3, 9], /* room minimum and maximum width */ + roomHeight: [3, 5], /* room minimum and maximum height */ + corridorLength: [3, 10], /* corridor minimum and maximum length */ + dugPercentage: 0.2, /* we stop after this percentage of level area has been dug out */ + timeLimit: 1000 /* we stop after this much time has passed (msec) */ + } + for (var p in options) { this._options[p] = options[p]; } + + this._features = { + "Room": 4, + "Corridor": 4 + } + this._featureAttempts = 20; /* how many times do we try to create a feature on a suitable wall */ + this._walls = {}; /* these are available for digging */ + + this._digCallback = this._digCallback.bind(this); + this._canBeDugCallback = this._canBeDugCallback.bind(this); + this._isWallCallback = this._isWallCallback.bind(this); + this._priorityWallCallback = this._priorityWallCallback.bind(this); +} +ROT.Map.Digger.extend(ROT.Map.Dungeon); + +/** + * Create a map + * @see ROT.Map#create + */ +ROT.Map.Digger.prototype.create = function(callback) { + this._rooms = []; + this._corridors = []; + this._map = this._fillMap(1); + this._walls = {}; + this._dug = 0; + var area = (this._width-2) * (this._height-2); + + this._firstRoom(); + + var t1 = Date.now(); + + do { + var t2 = Date.now(); + if (t2 - t1 > this._options.timeLimit) { break; } + + /* find a good wall */ + var wall = this._findWall(); + if (!wall) { break; } /* no more walls */ + + var parts = wall.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + var dir = this._getDiggingDirection(x, y); + if (!dir) { continue; } /* this wall is not suitable */ + +// console.log("wall", x, y); + + /* try adding a feature */ + var featureAttempts = 0; + do { + featureAttempts++; + if (this._tryFeature(x, y, dir[0], dir[1])) { /* feature added */ + if (this._rooms.length + this._corridors.length == 2) { this._rooms[0].addDoor(x, y); } /* first room oficially has doors */ + this._removeSurroundingWalls(x, y); + this._removeSurroundingWalls(x-dir[0], y-dir[1]); + break; + } + } while (featureAttempts < this._featureAttempts); + + var priorityWalls = 0; + for (var id in this._walls) { + if (this._walls[id] > 1) { priorityWalls++; } + } + + } while (this._dug/area < this._options.dugPercentage || priorityWalls); /* fixme number of priority walls */ + + if (callback) { + for (var i=0;i= this._width || y >= this._height) { return false; } + return (this._map[x][y] == 1); +} + +ROT.Map.Digger.prototype._canBeDugCallback = function(x, y) { + if (x < 1 || y < 1 || x+1 >= this._width || y+1 >= this._height) { return false; } + return (this._map[x][y] == 1); +} + +ROT.Map.Digger.prototype._priorityWallCallback = function(x, y) { + this._walls[x+","+y] = 2; +} + +ROT.Map.Digger.prototype._firstRoom = function() { + var cx = Math.floor(this._width/2); + var cy = Math.floor(this._height/2); + var room = ROT.Map.Feature.Room.createRandomCenter(cx, cy, this._options); + this._rooms.push(room); + room.create(this._digCallback); +} + +/** + * Get a suitable wall + */ +ROT.Map.Digger.prototype._findWall = function() { + var prio1 = []; + var prio2 = []; + for (var id in this._walls) { + var prio = this._walls[id]; + if (prio == 2) { + prio2.push(id); + } else { + prio1.push(id); + } + } + + var arr = (prio2.length ? prio2 : prio1); + if (!arr.length) { return null; } /* no walls :/ */ + + var id = arr.random(); + delete this._walls[id]; + + return id; +} + +/** + * Tries adding a feature + * @returns {bool} was this a successful try? + */ +ROT.Map.Digger.prototype._tryFeature = function(x, y, dx, dy) { + var feature = null; + var total = 0; + for (var p in this._features) { total += this._features[p]; } + var random = Math.floor(ROT.RNG.getUniform()*total); + + var sub = 0; + for (var p in this._features) { + sub += this._features[p]; + if (random < sub) { + feature = ROT.Map.Feature[p]; + break; + } + } + + feature = feature.createRandomAt(x, y, dx, dy, this._options); + + if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) { +// console.log("not valid"); +// feature.debug(); + return false; + } + + feature.create(this._digCallback); +// feature.debug(); + + if (feature instanceof ROT.Map.Feature.Room) { this._rooms.push(feature); } + if (feature instanceof ROT.Map.Feature.Corridor) { + feature.createPriorityWalls(this._priorityWallCallback); + this._corridors.push(feature); + } + + return true; +} + +ROT.Map.Digger.prototype._removeSurroundingWalls = function(cx, cy) { + var deltas = ROT.DIRS[4]; + + for (var i=0;i= this._width || y >= this._width) { return null; } + + if (!this._map[x][y]) { /* there already is another empty neighbor! */ + if (result) { return null; } + result = delta; + } + } + + /* no empty neighbor */ + if (!result) { return null; } + + return [-result[0], -result[1]]; +} +/** + * @class Dungeon generator which tries to fill the space evenly. Generates independent rooms and tries to connect them. + * @augments ROT.Map.Dungeon + */ +ROT.Map.Uniform = function(width, height, options) { + ROT.Map.Dungeon.call(this, width, height); + + this._options = { + roomWidth: [3, 9], /* room minimum and maximum width */ + roomHeight: [3, 5], /* room minimum and maximum height */ + roomDugPercentage: 0.1, /* we stop after this percentage of level area has been dug out by rooms */ + timeLimit: 1000 /* we stop after this much time has passed (msec) */ + } + for (var p in options) { this._options[p] = options[p]; } + + this._roomAttempts = 20; /* new room is created N-times until is considered as impossible to generate */ + this._corridorAttempts = 20; /* corridors are tried N-times until the level is considered as impossible to connect */ + + this._connected = []; /* list of already connected rooms */ + this._unconnected = []; /* list of remaining unconnected rooms */ + + this._digCallback = this._digCallback.bind(this); + this._canBeDugCallback = this._canBeDugCallback.bind(this); + this._isWallCallback = this._isWallCallback.bind(this); +} +ROT.Map.Uniform.extend(ROT.Map.Dungeon); + +/** + * Create a map. If the time limit has been hit, returns null. + * @see ROT.Map#create + */ +ROT.Map.Uniform.prototype.create = function(callback) { + var t1 = Date.now(); + while (1) { + var t2 = Date.now(); + if (t2 - t1 > this._options.timeLimit) { return null; } /* time limit! */ + + this._map = this._fillMap(1); + this._dug = 0; + this._rooms = []; + this._unconnected = []; + this._generateRooms(); + if (this._generateCorridors()) { break; } + } + + if (callback) { + for (var i=0;i this._options.roomDugPercentage) { break; } /* achieved requested amount of free space */ + } while (room); + + /* either enough rooms, or not able to generate more of them :) */ +} + +/** + * Try to generate one room + */ +ROT.Map.Uniform.prototype._generateRoom = function() { + var count = 0; + while (count < this._roomAttempts) { + count++; + + var room = ROT.Map.Feature.Room.createRandom(this._width, this._height, this._options); + if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) { continue; } + + room.create(this._digCallback); + this._rooms.push(room); + return room; + } + + /* no room was generated in a given number of attempts */ + return null; +} + +/** + * Generates connectors beween rooms + * @returns {bool} success Was this attempt successfull? + */ +ROT.Map.Uniform.prototype._generateCorridors = function() { + var cnt = 0; + while (cnt < this._corridorAttempts) { + cnt++; + this._corridors = []; + + /* dig rooms into a clear map */ + this._map = this._fillMap(1); + for (var i=0;i 0 ? 2 : 0); + var dirIndex2 = (dirIndex1 + 2) % 4; + var min = room2.getLeft(); + var max = room2.getRight(); + var index = 0; + } else { /* first try connecting east-west walls */ + var dirIndex1 = (diffX > 0 ? 1 : 3); + var dirIndex2 = (dirIndex1 + 2) % 4; + var min = room2.getTop(); + var max = room2.getBottom(); + var index = 1; + } + + var start = this._placeInWall(room1, dirIndex1); /* corridor will start here */ + if (!start) { return false; } + + if (start[index] >= min && start[index] <= max) { /* possible to connect with straight line (I-like) */ + var end = start.slice(); + var value = null; + switch (dirIndex2) { + case 0: value = room2.getTop()-1; break; + case 1: value = room2.getRight()+1; break; + case 2: value = room2.getBottom()+1; break; + case 3: value = room2.getLeft()-1; break; + } + end[(index+1)%2] = value; + this._digLine([start, end]); + + } else if (start[index] < min-1 || start[index] > max+1) { /* need to switch target wall (L-like) */ + + var diff = start[index] - center2[index]; + switch (dirIndex2) { + case 0: + case 1: var rotation = (diff < 0 ? 3 : 1); break; + case 2: + case 3: var rotation = (diff < 0 ? 1 : 3); break; + } + dirIndex2 = (dirIndex2 + rotation) % 4; + + var end = this._placeInWall(room2, dirIndex2); + if (!end) { return false; } + + var mid = [0, 0]; + mid[index] = start[index]; + var index2 = (index+1)%2; + mid[index2] = end[index2]; + this._digLine([start, mid, end]); + + } else { /* use current wall pair, but adjust the line in the middle (S-like) */ + + var index2 = (index+1)%2; + var end = this._placeInWall(room2, dirIndex2); + if (!end) { return; } + var mid = Math.round((end[index2] + start[index2])/2); + + var mid1 = [0, 0]; + var mid2 = [0, 0]; + mid1[index] = start[index]; + mid1[index2] = mid; + mid2[index] = end[index]; + mid2[index2] = mid; + this._digLine([start, mid1, mid2, end]); + } + + room1.addDoor(start[0], start[1]); + room2.addDoor(end[0], end[1]); + + var index = this._unconnected.indexOf(room1); + if (index != -1) { + this._unconnected.splice(index, 1); + this._connected.push(room1); + } + + var index = this._unconnected.indexOf(room2); + if (index != -1) { + this._unconnected.splice(index, 1); + this._connected.push(room2); + } + + return true; +} + +ROT.Map.Uniform.prototype._placeInWall = function(room, dirIndex) { + var start = [0, 0]; + var dir = [0, 0]; + var length = 0; + + switch (dirIndex) { + case 0: + dir = [1, 0]; + start = [room.getLeft(), room.getTop()-1]; + length = room.getRight()-room.getLeft()+1; + break; + case 1: + dir = [0, 1]; + start = [room.getRight()+1, room.getTop()]; + length = room.getBottom()-room.getTop()+1; + break; + case 2: + dir = [1, 0]; + start = [room.getLeft(), room.getBottom()+1]; + length = room.getRight()-room.getLeft()+1; + break; + case 3: + dir = [0, 1]; + start = [room.getLeft()-1, room.getTop()]; + length = room.getBottom()-room.getTop()+1; + break; + } + + var avail = []; + var lastBadIndex = -2; + + for (var i=0;i=0; i--) { + if (!avail[i]) { avail.splice(i, 1); } + } + return (avail.length ? avail.random() : null); +} + +/** + * Dig a polyline. + */ +ROT.Map.Uniform.prototype._digLine = function(points) { + for (var i=1;i= this._width || y >= this._height) { return false; } + return (this._map[x][y] == 1); +} + +ROT.Map.Uniform.prototype._canBeDugCallback = function(x, y) { + if (x < 1 || y < 1 || x+1 >= this._width || y+1 >= this._height) { return false; } + return (this._map[x][y] == 1); +} + +/** + * @class + * Dungeon feature; has own .create() method + */ +ROT.Map.Feature = function() {} +ROT.Map.Feature.prototype.isValid = function(canBeDugCallback) {} +ROT.Map.Feature.prototype.create = function(digCallback) {} +ROT.Map.Feature.prototype.debug = function() {} +ROT.Map.Feature.createRandomAt = function(x, y, dx, dy, options) {} + +/** + * @class Room + * @augments ROT.Map.Feature + * @param {int} x1 + * @param {int} y1 + * @param {int} x2 + * @param {int} y2 + * @param {int} [doorX] + * @param {int} [doorY] + */ +ROT.Map.Feature.Room = function(x1, y1, x2, y2, doorX, doorY) { + this._x1 = x1; + this._y1 = y1; + this._x2 = x2; + this._y2 = y2; + this._doors = {}; + if (arguments.length > 4) { this.addDoor(doorX, doorY); } +} +ROT.Map.Feature.Room.extend(ROT.Map.Feature); + +/** + * Room of random size, with a given doors and direction + */ +ROT.Map.Feature.Room.createRandomAt = function(x, y, dx, dy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var min = options.roomHeight[0]; + var max = options.roomHeight[1]; + var height = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + if (dx == 1) { /* to the right */ + var y2 = y - Math.floor(ROT.RNG.getUniform() * height); + return new this(x+1, y2, x+width, y2+height-1, x, y); + } + + if (dx == -1) { /* to the left */ + var y2 = y - Math.floor(ROT.RNG.getUniform() * height); + return new this(x-width, y2, x-1, y2+height-1, x, y); + } + + if (dy == 1) { /* to the bottom */ + var x2 = x - Math.floor(ROT.RNG.getUniform() * width); + return new this(x2, y+1, x2+width-1, y+height, x, y); + } + + if (dy == -1) { /* to the top */ + var x2 = x - Math.floor(ROT.RNG.getUniform() * width); + return new this(x2, y-height, x2+width-1, y-1, x, y); + } +} + +/** + * Room of random size, positioned around center coords + */ +ROT.Map.Feature.Room.createRandomCenter = function(cx, cy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var min = options.roomHeight[0]; + var max = options.roomHeight[1]; + var height = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var x1 = cx - Math.floor(ROT.RNG.getUniform()*width); + var y1 = cy - Math.floor(ROT.RNG.getUniform()*height); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + + return new this(x1, y1, x2, y2); +} + +/** + * Room of random size within a given dimensions + */ +ROT.Map.Feature.Room.createRandom = function(availWidth, availHeight, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var min = options.roomHeight[0]; + var max = options.roomHeight[1]; + var height = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var left = availWidth - width - 1; + var top = availHeight - height - 1; + + var x1 = 1 + Math.floor(ROT.RNG.getUniform()*left); + var y1 = 1 + Math.floor(ROT.RNG.getUniform()*top); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + + return new this(x1, y1, x2, y2); +} + +ROT.Map.Feature.Room.prototype.addDoor = function(x, y) { + this._doors[x+","+y] = 1; +} + +/** + * @param {function} + */ +ROT.Map.Feature.Room.prototype.getDoors = function(callback) { + for (var key in this._doors) { + var parts = key.split(","); + callback(parseInt(parts[0]), parseInt(parts[1])); + } +} + +ROT.Map.Feature.Room.prototype.clearDoors = function() { + this._doors = {}; + return this; +} + +ROT.Map.Feature.Room.prototype.debug = function() { + console.log("room", this._x1, this._y1, this._x2, this._y2); +} + +ROT.Map.Feature.Room.prototype.isValid = function(isWallCallback, canBeDugCallback) { + var left = this._x1-1; + var right = this._x2+1; + var top = this._y1-1; + var bottom = this._y2+1; + + for (var x=left; x<=right; x++) { + for (var y=top; y<=bottom; y++) { + if (x == left || x == right || y == top || y == bottom) { + if (!isWallCallback(x, y)) { return false; } + } else { + if (!canBeDugCallback(x, y)) { return false; } + } + } + } + + return true; +} + +/** + * @param {function} digCallback Dig callback with a signature (x, y, value). Values: 0 = empty, 1 = wall, 2 = door. Multiple doors are allowed. + */ +ROT.Map.Feature.Room.prototype.create = function(digCallback) { + var left = this._x1-1; + var right = this._x2+1; + var top = this._y1-1; + var bottom = this._y2+1; + + var value = 0; + for (var x=left; x<=right; x++) { + for (var y=top; y<=bottom; y++) { + if (x+","+y in this._doors) { + value = 2; + } else if (x == left || x == right || y == top || y == bottom) { + value = 1; + } else { + value = 0; + } + digCallback(x, y, value); + } + } +} + +ROT.Map.Feature.Room.prototype.getCenter = function() { + return [Math.round((this._x1 + this._x2)/2), Math.round((this._y1 + this._y2)/2)]; +} + +ROT.Map.Feature.Room.prototype.getLeft = function() { + return this._x1; +} + +ROT.Map.Feature.Room.prototype.getRight = function() { + return this._x2; +} + +ROT.Map.Feature.Room.prototype.getTop = function() { + return this._y1; +} + +ROT.Map.Feature.Room.prototype.getBottom = function() { + return this._y2; +} + +/** + * @class Corridor + * @augments ROT.Map.Feature + * @param {int} startX + * @param {int} startY + * @param {int} endX + * @param {int} endY + */ +ROT.Map.Feature.Corridor = function(startX, startY, endX, endY) { + this._startX = startX; + this._startY = startY; + this._endX = endX; + this._endY = endY; + this._endsWithAWall = true; +} +ROT.Map.Feature.Corridor.extend(ROT.Map.Feature); + +ROT.Map.Feature.Corridor.createRandomAt = function(x, y, dx, dy, options) { + var min = options.corridorLength[0]; + var max = options.corridorLength[1]; + var length = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + return new this(x, y, x + dx*length, y + dy*length); +} + +ROT.Map.Feature.Corridor.prototype.debug = function() { + console.log("corridor", this._startX, this._startY, this._endX, this._endY); +} + +ROT.Map.Feature.Corridor.prototype.isValid = function(isWallCallback, canBeDugCallback){ + var sx = this._startX; + var sy = this._startY; + var dx = this._endX-sx; + var dy = this._endY-sy; + var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); + + if (dx) { dx = dx/Math.abs(dx); } + if (dy) { dy = dy/Math.abs(dy); } + var nx = dy; + var ny = -dx; + + var ok = true; + for (var i=0; i y0) { + i1 = 1; + j1 = 0; + } else { // lower triangle, XY order: (0,0)->(1,0)->(1,1) + i1 = 0; + j1 = 1; + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + + // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + // c = (3-sqrt(3))/6 + var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + var y1 = y0 - j1 + G2; + var x2 = x0 - 1 + 2*G2; // Offsets for last corner in (x,y) unskewed coords + var y2 = y0 - 1 + 2*G2; + + // Work out the hashed gradient indices of the three simplex corners + var ii = i.mod(count); + var jj = j.mod(count); + + // Calculate the contribution from the three corners + var t0 = 0.5 - x0*x0 - y0*y0; + if (t0 >= 0) { + t0 *= t0; + gi = indexes[ii+perms[jj]]; + var grad = this._gradients[gi]; + n0 = t0 * t0 * (grad[0] * x0 + grad[1] * y0); + } + + var t1 = 0.5 - x1*x1 - y1*y1; + if (t1 >= 0) { + t1 *= t1; + gi = indexes[ii+i1+perms[jj+j1]]; + var grad = this._gradients[gi]; + n1 = t1 * t1 * (grad[0] * x1 + grad[1] * y1); + } + + var t2 = 0.5 - x2*x2 - y2*y2; + if (t2 >= 0) { + t2 *= t2; + gi = indexes[ii+1+perms[jj+1]]; + var grad = this._gradients[gi]; + n2 = t2 * t2 * (grad[0] * x2 + grad[1] * y2); + } + + // Add contributions from each corner to get the final noise value. + // The result is scaled to return values in the interval [-1,1]. + return 70 * (n0 + n1 + n2); +} +/** + * @class Abstract FOV algorithm + * @param {function} lightPassesCallback Does the light pass through x,y? + * @param {object} [options] + * @param {int} [options.topology=8] 4/6/8 + */ +ROT.FOV = function(lightPassesCallback, options) { + this._lightPasses = lightPassesCallback; + this._options = { + topology: 8 + } + for (var p in options) { this._options[p] = options[p]; } +}; + +/** + * Compute visibility + * @param {int} x + * @param {int} y + * @param {int} R Maximum visibility radius + * @param {function} callback + */ +ROT.FOV.prototype.compute = function(x, y, R, callback) {} + +/** + * Return all neighbors in a concentric ring + * @param {int} cx center-x + * @param {int} cy center-y + * @param {int} r range + */ +ROT.FOV.prototype._getCircle = function(cx, cy, r) { + var result = []; + var dirs, countFactor, startOffset; + + switch (this._options.topology) { + case 4: + countFactor = 1; + startOffset = [0, 1]; + dirs = [ + ROT.DIRS[8][7], + ROT.DIRS[8][1], + ROT.DIRS[8][3], + ROT.DIRS[8][5] + ] + break; + + case 6: + dirs = ROT.DIRS[6]; + countFactor = 1; + startOffset = [-1, 1]; + break; + + case 8: + dirs = ROT.DIRS[4]; + countFactor = 2; + startOffset = [-1, 1]; + break; + } + + /* starting neighbor */ + var x = cx + startOffset[0]*r; + var y = cy + startOffset[1]*r; + + /* circle */ + for (var i=0;i A2[0]) { /* split into two sub-arcs */ + var v1 = this._checkVisibility(A1, [A1[1], A1[1]], blocks, SHADOWS); + var v2 = this._checkVisibility([0, 1], A2, blocks, SHADOWS); + return (v1+v2)/2; + } + + /* index1: first shadow >= A1 */ + var index1 = 0, edge1 = false; + while (index1 < SHADOWS.length) { + var old = SHADOWS[index1]; + var diff = old[0]*A1[1] - A1[0]*old[1]; + if (diff >= 0) { /* old >= A1 */ + if (diff == 0 && !(index1 % 2)) { edge1 = true; } + break; + } + index1++; + } + + /* index2: last shadow <= A2 */ + var index2 = SHADOWS.length, edge2 = false; + while (index2--) { + var old = SHADOWS[index2]; + var diff = A2[0]*old[1] - old[0]*A2[1]; + if (diff >= 0) { /* old <= A2 */ + if (diff == 0 && (index2 % 2)) { edge2 = true; } + break; + } + } + + var visible = true; + if (index1 == index2 && (edge1 || edge2)) { /* subset of existing shadow, one of the edges match */ + visible = false; + } else if (edge1 && edge2 && index1+1==index2 && (index2 % 2)) { /* completely equivalent with existing shadow */ + visible = false; + } else if (index1 > index2 && (index1 % 2)) { /* subset of existing shadow, not touching */ + visible = false; + } + + if (!visible) { return 0; } /* fast case: not visible */ + + var visibleLength, P; + + /* compute the length of visible arc, adjust list of shadows (if blocking) */ + var remove = index2-index1+1; + if (remove % 2) { + if (index1 % 2) { /* first edge within existing shadow, second outside */ + var P = SHADOWS[index1]; + visibleLength = (A2[0]*P[1] - P[0]*A2[1]) / (P[1] * A2[1]); + if (blocks) { SHADOWS.splice(index1, remove, A2); } + } else { /* second edge within existing shadow, first outside */ + var P = SHADOWS[index2]; + visibleLength = (P[0]*A1[1] - A1[0]*P[1]) / (A1[1] * P[1]); + if (blocks) { SHADOWS.splice(index1, remove, A1); } + } + } else { + if (index1 % 2) { /* both edges within existing shadows */ + var P1 = SHADOWS[index1]; + var P2 = SHADOWS[index2]; + visibleLength = (P2[0]*P1[1] - P1[0]*P2[1]) / (P1[1] * P2[1]); + if (blocks) { SHADOWS.splice(index1, remove); } + } else { /* both edges outside existing shadows */ + if (blocks) { SHADOWS.splice(index1, remove, A1, A2); } + return 1; /* whole arc visible! */ + } + } + + var arcLength = (A2[0]*A1[1] - A1[0]*A2[1]) / (A1[1] * A2[1]); + + return visibleLength/arcLength; +} +/** + * @namespace Color operations + */ +ROT.Color = { + fromString: function(str) { + var cached, r; + if (str in this._cache) { + cached = this._cache[str]; + } else { + if (str.charAt(0) == "#") { /* hex rgb */ + + var values = str.match(/[0-9a-f]/gi).map(function(x) { return parseInt(x, 16); }); + if (values.length == 3) { + cached = values.map(function(x) { return x*17; }); + } else { + for (var i=0;i<3;i++) { + values[i+1] += 16*values[i]; + values.splice(i, 1); + } + cached = values; + } + + } else if (r = str.match(/rgb\(([0-9, ]+)\)/i)) { /* decimal rgb */ + cached = r[1].split(/\s*,\s*/).map(function(x) { return parseInt(x); }); + } else { /* html name */ + cached = [0, 0, 0]; + } + + this._cache[str] = cached; + } + + return cached.slice(); + }, + + /** + * Add two or more colors + * @param {number[]} color1 + * @param {number[]} color2 + * @returns {number[]} + */ + add: function(color1, color2) { + var result = color1.slice(); + for (var i=0;i<3;i++) { + for (var j=1;j 0.5 ? d / (2 - max - min) : d / (max + min)); + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + + return [h, s, l]; + }, + + /** + * Converts an HSL color value to RGB. Expects 0..1 inputs, produces 0..255 outputs. + * @param {number[]} color + * @returns {number[]} + */ + hsl2rgb: function(color) { + var l = color[2]; + + if (color[1] == 0) { + l *= 255; + return [l, l, l]; + } else { + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1/6) return p + (q - p) * 6 * t; + if (t < 1/2) return q; + if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; + } + + var s = color[1]; + var q = (l < 0.5 ? l * (1 + s) : l + s - l * s); + var p = 2 * l - q; + var r = hue2rgb(p, q, color[0] + 1/3); + var g = hue2rgb(p, q, color[0]); + var b = hue2rgb(p, q, color[0] - 1/3); + return [Math.round(r*255), Math.round(g*255), Math.round(b*255)]; + } + }, + + toRGB: function(color) { + return "rgb(" + this._clamp(color[0]) + "," + this._clamp(color[1]) + "," + this._clamp(color[2]) + ")"; + }, + + toHex: function(color) { + var parts = []; + for (var i=0;i<3;i++) { + parts.push(this._clamp(color[i]).toString(16).lpad("0", 2)); + } + return "#" + parts.join(""); + }, + + _clamp: function(num) { + if (num < 0) { + return 0; + } else if (num > 255) { + return 255; + } else { + return num; + } + }, + + _cache: { + "black": [0,0,0], + "navy": [0,0,128], + "darkblue": [0,0,139], + "mediumblue": [0,0,205], + "blue": [0,0,255], + "darkgreen": [0,100,0], + "green": [0,128,0], + "teal": [0,128,128], + "darkcyan": [0,139,139], + "deepskyblue": [0,191,255], + "darkturquoise": [0,206,209], + "mediumspringgreen": [0,250,154], + "lime": [0,255,0], + "springgreen": [0,255,127], + "aqua": [0,255,255], + "cyan": [0,255,255], + "midnightblue": [25,25,112], + "dodgerblue": [30,144,255], + "forestgreen": [34,139,34], + "seagreen": [46,139,87], + "darkslategray": [47,79,79], + "darkslategrey": [47,79,79], + "limegreen": [50,205,50], + "mediumseagreen": [60,179,113], + "turquoise": [64,224,208], + "royalblue": [65,105,225], + "steelblue": [70,130,180], + "darkslateblue": [72,61,139], + "mediumturquoise": [72,209,204], + "indigo": [75,0,130], + "darkolivegreen": [85,107,47], + "cadetblue": [95,158,160], + "cornflowerblue": [100,149,237], + "mediumaquamarine": [102,205,170], + "dimgray": [105,105,105], + "dimgrey": [105,105,105], + "slateblue": [106,90,205], + "olivedrab": [107,142,35], + "slategray": [112,128,144], + "slategrey": [112,128,144], + "lightslategray": [119,136,153], + "lightslategrey": [119,136,153], + "mediumslateblue": [123,104,238], + "lawngreen": [124,252,0], + "chartreuse": [127,255,0], + "aquamarine": [127,255,212], + "maroon": [128,0,0], + "purple": [128,0,128], + "olive": [128,128,0], + "gray": [128,128,128], + "grey": [128,128,128], + "skyblue": [135,206,235], + "lightskyblue": [135,206,250], + "blueviolet": [138,43,226], + "darkred": [139,0,0], + "darkmagenta": [139,0,139], + "saddlebrown": [139,69,19], + "darkseagreen": [143,188,143], + "lightgreen": [144,238,144], + "mediumpurple": [147,112,216], + "darkviolet": [148,0,211], + "palegreen": [152,251,152], + "darkorchid": [153,50,204], + "yellowgreen": [154,205,50], + "sienna": [160,82,45], + "brown": [165,42,42], + "darkgray": [169,169,169], + "darkgrey": [169,169,169], + "lightblue": [173,216,230], + "greenyellow": [173,255,47], + "paleturquoise": [175,238,238], + "lightsteelblue": [176,196,222], + "powderblue": [176,224,230], + "firebrick": [178,34,34], + "darkgoldenrod": [184,134,11], + "mediumorchid": [186,85,211], + "rosybrown": [188,143,143], + "darkkhaki": [189,183,107], + "silver": [192,192,192], + "mediumvioletred": [199,21,133], + "indianred": [205,92,92], + "peru": [205,133,63], + "chocolate": [210,105,30], + "tan": [210,180,140], + "lightgray": [211,211,211], + "lightgrey": [211,211,211], + "palevioletred": [216,112,147], + "thistle": [216,191,216], + "orchid": [218,112,214], + "goldenrod": [218,165,32], + "crimson": [220,20,60], + "gainsboro": [220,220,220], + "plum": [221,160,221], + "burlywood": [222,184,135], + "lightcyan": [224,255,255], + "lavender": [230,230,250], + "darksalmon": [233,150,122], + "violet": [238,130,238], + "palegoldenrod": [238,232,170], + "lightcoral": [240,128,128], + "khaki": [240,230,140], + "aliceblue": [240,248,255], + "honeydew": [240,255,240], + "azure": [240,255,255], + "sandybrown": [244,164,96], + "wheat": [245,222,179], + "beige": [245,245,220], + "whitesmoke": [245,245,245], + "mintcream": [245,255,250], + "ghostwhite": [248,248,255], + "salmon": [250,128,114], + "antiquewhite": [250,235,215], + "linen": [250,240,230], + "lightgoldenrodyellow": [250,250,210], + "oldlace": [253,245,230], + "red": [255,0,0], + "fuchsia": [255,0,255], + "magenta": [255,0,255], + "deeppink": [255,20,147], + "orangered": [255,69,0], + "tomato": [255,99,71], + "hotpink": [255,105,180], + "coral": [255,127,80], + "darkorange": [255,140,0], + "lightsalmon": [255,160,122], + "orange": [255,165,0], + "lightpink": [255,182,193], + "pink": [255,192,203], + "gold": [255,215,0], + "peachpuff": [255,218,185], + "navajowhite": [255,222,173], + "moccasin": [255,228,181], + "bisque": [255,228,196], + "mistyrose": [255,228,225], + "blanchedalmond": [255,235,205], + "papayawhip": [255,239,213], + "lavenderblush": [255,240,245], + "seashell": [255,245,238], + "cornsilk": [255,248,220], + "lemonchiffon": [255,250,205], + "floralwhite": [255,250,240], + "snow": [255,250,250], + "yellow": [255,255,0], + "lightyellow": [255,255,224], + "ivory": [255,255,240], + "white": [255,255,255] + } +} +/** + * @class Lighting computation, based on a traditional FOV for multiple light sources and multiple passes. + * @param {function} reflectivityCallback Callback to retrieve cell reflectivity (0..1) + * @param {object} [options] + * @param {int} [options.passes=1] Number of passes. 1 equals to simple FOV of all light sources, >1 means a *highly simplified* radiosity-like algorithm. + * @param {int} [options.emissionThreshold=100] Cells with emissivity > threshold will be treated as light source in the next pass. + * @param {int} [options.range=10] Max light range + */ +ROT.Lighting = function(reflectivityCallback, options) { + this._reflectivityCallback = reflectivityCallback; + this._options = { + passes: 1, + emissionThreshold: 100, + range: 10 + }; + this._fov = null; + + this._lights = {}; + this._reflectivityCache = {}; + this._fovCache = {}; + + this.setOptions(options); +} + +/** + * Adjust options at runtime + * @see ROT.Lighting + * @param {object} [options] + */ +ROT.Lighting.prototype.setOptions = function(options) { + for (var p in options) { this._options[p] = options[p]; } + if (options.range) { this.reset(); } + return this; +} + +/** + * Set the used Field-Of-View algo + * @param {ROT.FOV} fov + */ +ROT.Lighting.prototype.setFOV = function(fov) { + this._fov = fov; + this._fovCache = {}; + return this; +} + +/** + * Set (or remove) a light source + * @param {int} x + * @param {int} y + * @param {null || string || number[3]} color + */ +ROT.Lighting.prototype.setLight = function(x, y, color) { + var key = x+","+y; + + if (color) { + this._lights[key] = (typeof(color) == "string" ? ROT.Color.fromString(color) : color); + } else { + delete this._lights[key]; + } + return this; +} + +/** + * Reset the pre-computed topology values. Call whenever the underlying map changes its light-passability. + */ +ROT.Lighting.prototype.reset = function() { + this._reflectivityCache = {}; + this._fovCache = {}; + + return this; +} + +/** + * Compute the lighting + * @param {function} lightingCallback Will be called with (x, y, color) for every lit cell + */ +ROT.Lighting.prototype.compute = function(lightingCallback) { + var doneCells = {}; + var emittingCells = {}; + var litCells = {}; + + for (var key in this._lights) { /* prepare emitters for first pass */ + var light = this._lights[key]; + if (!(key in emittingCells)) { emittingCells[key] = [0, 0, 0]; } + + ROT.Color.add_(emittingCells[key], light); + } + + for (var i=0;i this._options.emissionThreshold) { result[key] = emission; } + } + + return result; +} + +/** + * Compute one iteration from one cell + * @param {int} x + * @param {int} y + * @param {number[]} color + * @param {object} litCells Cell data to by updated + */ +ROT.Lighting.prototype._emitLightFromCell = function(x, y, color, litCells) { + var key = x+","+y; + if (key in this._fovCache) { + var fov = this._fovCache[key]; + } else { + var fov = this._updateFOV(x, y); + } + + for (var fovKey in fov) { + var formFactor = fov[fovKey]; + + if (fovKey in litCells) { /* already lit */ + var result = litCells[fovKey]; + } else { /* newly lit */ + var result = [0, 0, 0]; + litCells[fovKey] = result; + } + + for (var i=0;i<3;i++) { result[i] += Math.round(color[i]*formFactor); } /* add light color */ + } + + return this; +} + +/** + * Compute FOV ("form factor") for a potential light source at [x,y] + * @param {int} x + * @param {int} y + * @returns {object} + */ +ROT.Lighting.prototype._updateFOV = function(x, y) { + var key1 = x+","+y; + var cache = {}; + this._fovCache[key1] = cache; + var range = this._options.range; + var cb = function(x, y, r, vis) { + var key2 = x+","+y; + var formFactor = vis * (1-r/range); + if (formFactor == 0) { return; } + cache[key2] = formFactor; + } + this._fov.compute(x, y, range, cb.bind(this)); + + return cache; +} +/** + * @class Abstract pathfinder + * @param {int} toX Target X coord + * @param {int} toY Target Y coord + * @param {function} passableCallback Callback to determine map passability + * @param {object} [options] + * @param {int} [options.topology=8] + */ +ROT.Path = function(toX, toY, passableCallback, options) { + this._toX = toX; + this._toY = toY; + this._fromX = null; + this._fromY = null; + this._passableCallback = passableCallback; + this._options = { + topology: 8 + } + for (var p in options) { this._options[p] = options[p]; } + + this._dirs = ROT.DIRS[this._options.topology]; +} + +/** + * Compute a path from a given point + * @param {int} fromX + * @param {int} fromY + * @param {function} callback Will be called for every path item with arguments "x" and "y" + */ +ROT.Path.prototype.compute = function(fromX, fromY, callback) { +} + +ROT.Path.prototype._getNeighbors = function(cx, cy) { + var result = []; + for (var i=0;i 0.5 ? d / (2 - max - min) : d / (max + min)); + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + + return [h, s, l]; + }, + + /** + * Converts an HSL color value to RGB. Expects 0..1 inputs, produces 0..255 outputs. + * @param {number[]} color + * @returns {number[]} + */ + hsl2rgb: function(color) { + var l = color[2]; + + if (color[1] == 0) { + l *= 255; + return [l, l, l]; + } else { + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1/6) return p + (q - p) * 6 * t; + if (t < 1/2) return q; + if (t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; + } + + var s = color[1]; + var q = (l < 0.5 ? l * (1 + s) : l + s - l * s); + var p = 2 * l - q; + var r = hue2rgb(p, q, color[0] + 1/3); + var g = hue2rgb(p, q, color[0]); + var b = hue2rgb(p, q, color[0] - 1/3); + return [Math.round(r*255), Math.round(g*255), Math.round(b*255)]; + } + }, + + toRGB: function(color) { + return "rgb(" + this._clamp(color[0]) + "," + this._clamp(color[1]) + "," + this._clamp(color[2]) + ")"; + }, + + toHex: function(color) { + var parts = []; + for (var i=0;i<3;i++) { + parts.push(this._clamp(color[i]).toString(16).lpad("0", 2)); + } + return "#" + parts.join(""); + }, + + _clamp: function(num) { + if (num < 0) { + return 0; + } else if (num > 255) { + return 255; + } else { + return num; + } + }, + + _cache: { + "black": [0,0,0], + "navy": [0,0,128], + "darkblue": [0,0,139], + "mediumblue": [0,0,205], + "blue": [0,0,255], + "darkgreen": [0,100,0], + "green": [0,128,0], + "teal": [0,128,128], + "darkcyan": [0,139,139], + "deepskyblue": [0,191,255], + "darkturquoise": [0,206,209], + "mediumspringgreen": [0,250,154], + "lime": [0,255,0], + "springgreen": [0,255,127], + "aqua": [0,255,255], + "cyan": [0,255,255], + "midnightblue": [25,25,112], + "dodgerblue": [30,144,255], + "forestgreen": [34,139,34], + "seagreen": [46,139,87], + "darkslategray": [47,79,79], + "darkslategrey": [47,79,79], + "limegreen": [50,205,50], + "mediumseagreen": [60,179,113], + "turquoise": [64,224,208], + "royalblue": [65,105,225], + "steelblue": [70,130,180], + "darkslateblue": [72,61,139], + "mediumturquoise": [72,209,204], + "indigo": [75,0,130], + "darkolivegreen": [85,107,47], + "cadetblue": [95,158,160], + "cornflowerblue": [100,149,237], + "mediumaquamarine": [102,205,170], + "dimgray": [105,105,105], + "dimgrey": [105,105,105], + "slateblue": [106,90,205], + "olivedrab": [107,142,35], + "slategray": [112,128,144], + "slategrey": [112,128,144], + "lightslategray": [119,136,153], + "lightslategrey": [119,136,153], + "mediumslateblue": [123,104,238], + "lawngreen": [124,252,0], + "chartreuse": [127,255,0], + "aquamarine": [127,255,212], + "maroon": [128,0,0], + "purple": [128,0,128], + "olive": [128,128,0], + "gray": [128,128,128], + "grey": [128,128,128], + "skyblue": [135,206,235], + "lightskyblue": [135,206,250], + "blueviolet": [138,43,226], + "darkred": [139,0,0], + "darkmagenta": [139,0,139], + "saddlebrown": [139,69,19], + "darkseagreen": [143,188,143], + "lightgreen": [144,238,144], + "mediumpurple": [147,112,216], + "darkviolet": [148,0,211], + "palegreen": [152,251,152], + "darkorchid": [153,50,204], + "yellowgreen": [154,205,50], + "sienna": [160,82,45], + "brown": [165,42,42], + "darkgray": [169,169,169], + "darkgrey": [169,169,169], + "lightblue": [173,216,230], + "greenyellow": [173,255,47], + "paleturquoise": [175,238,238], + "lightsteelblue": [176,196,222], + "powderblue": [176,224,230], + "firebrick": [178,34,34], + "darkgoldenrod": [184,134,11], + "mediumorchid": [186,85,211], + "rosybrown": [188,143,143], + "darkkhaki": [189,183,107], + "silver": [192,192,192], + "mediumvioletred": [199,21,133], + "indianred": [205,92,92], + "peru": [205,133,63], + "chocolate": [210,105,30], + "tan": [210,180,140], + "lightgray": [211,211,211], + "lightgrey": [211,211,211], + "palevioletred": [216,112,147], + "thistle": [216,191,216], + "orchid": [218,112,214], + "goldenrod": [218,165,32], + "crimson": [220,20,60], + "gainsboro": [220,220,220], + "plum": [221,160,221], + "burlywood": [222,184,135], + "lightcyan": [224,255,255], + "lavender": [230,230,250], + "darksalmon": [233,150,122], + "violet": [238,130,238], + "palegoldenrod": [238,232,170], + "lightcoral": [240,128,128], + "khaki": [240,230,140], + "aliceblue": [240,248,255], + "honeydew": [240,255,240], + "azure": [240,255,255], + "sandybrown": [244,164,96], + "wheat": [245,222,179], + "beige": [245,245,220], + "whitesmoke": [245,245,245], + "mintcream": [245,255,250], + "ghostwhite": [248,248,255], + "salmon": [250,128,114], + "antiquewhite": [250,235,215], + "linen": [250,240,230], + "lightgoldenrodyellow": [250,250,210], + "oldlace": [253,245,230], + "red": [255,0,0], + "fuchsia": [255,0,255], + "magenta": [255,0,255], + "deeppink": [255,20,147], + "orangered": [255,69,0], + "tomato": [255,99,71], + "hotpink": [255,105,180], + "coral": [255,127,80], + "darkorange": [255,140,0], + "lightsalmon": [255,160,122], + "orange": [255,165,0], + "lightpink": [255,182,193], + "pink": [255,192,203], + "gold": [255,215,0], + "peachpuff": [255,218,185], + "navajowhite": [255,222,173], + "moccasin": [255,228,181], + "bisque": [255,228,196], + "mistyrose": [255,228,225], + "blanchedalmond": [255,235,205], + "papayawhip": [255,239,213], + "lavenderblush": [255,240,245], + "seashell": [255,245,238], + "cornsilk": [255,248,220], + "lemonchiffon": [255,250,205], + "floralwhite": [255,250,240], + "snow": [255,250,250], + "yellow": [255,255,0], + "lightyellow": [255,255,224], + "ivory": [255,255,240], + "white": [255,255,255] + } +} diff --git a/lib/rotjs-library/src/display/backend.js b/lib/rotjs-library/src/display/backend.js new file mode 100644 index 0000000000000000000000000000000000000000..8a9efda098d19d356b18f5d202af4c510b566856 --- /dev/null +++ b/lib/rotjs-library/src/display/backend.js @@ -0,0 +1,19 @@ +/** + * @class Abstract display backend module + * @private + */ +ROT.Display.Backend = function(context) { + this._context = context; +} + +ROT.Display.Backend.prototype.compute = function(options) { +} + +ROT.Display.Backend.prototype.draw = function(data, clearBefore) { +} + +ROT.Display.Backend.prototype.computeSize = function(availWidth, availHeight) { +} + +ROT.Display.Backend.prototype.computeFontSize = function(availWidth, availHeight) { +} diff --git a/lib/rotjs-library/src/display/display.js b/lib/rotjs-library/src/display/display.js new file mode 100644 index 0000000000000000000000000000000000000000..19b36efaf18741e525e1163004d605c91326fd8d --- /dev/null +++ b/lib/rotjs-library/src/display/display.js @@ -0,0 +1,215 @@ +/** + * @class Visual map display + * @param {object} [options] + * @param {int} [options.width=ROT.DEFAULT_WIDTH] + * @param {int} [options.height=ROT.DEFAULT_HEIGHT] + * @param {int} [options.fontSize=15] + * @param {string} [options.fontFamily="monospace"] + * @param {string} [options.fontStyle=""] bold/italic/none/both + * @param {string} [options.fg="#ccc"] + * @param {string} [options.bg="#000"] + * @param {int} [options.fps=25] + * @param {float} [options.spacing=1] + * @param {float} [options.border=0] + * @param {string} [options.layout="rect"] + */ +ROT.Display = function(options) { + var canvas = document.createElement("canvas"); + this._context = canvas.getContext("2d"); + this._data = {}; + this._dirty = false; /* false = nothing, true = all, object = dirty cells */ + this._options = {}; + this._backend = null; + + var defaultOptions = { + width: ROT.DEFAULT_WIDTH, + height: ROT.DEFAULT_HEIGHT, + layout: "rect", + fontSize: 15, + fps: 25, + spacing: 1, + border: 0, + fontFamily: "monospace", + fontStyle: "", + fg: "#ccc", + bg: "#000" + }; + for (var p in options) { defaultOptions[p] = options[p]; } + this.setOptions(defaultOptions); + this.DEBUG = this.DEBUG.bind(this); + + this._interval = setInterval(this._tick.bind(this), 1000/this._options.fps); +} + +/** + * Debug helper, ideal as a map generator callback. Always bound to this. + * @param {int} x + * @param {int} y + * @param {int} what + */ +ROT.Display.prototype.DEBUG = function(x, y, what) { + var colors = [this._options.bg, this._options.fg]; + this.draw(x, y, null, null, colors[what % colors.length]); +} + +/** + * Clear the whole display (cover it with background color) + */ +ROT.Display.prototype.clear = function() { + this._data = {}; + this._dirty = true; +} + +/** + * @see ROT.Display + */ +ROT.Display.prototype.setOptions = function(options) { + for (var p in options) { this._options[p] = options[p]; } + if (options.width || options.height || options.fontSize || options.fontFamily || options.spacing || options.layout) { + if (options.layout) { + this._backend = new ROT.Display[options.layout.capitalize()](this._context); + } + + var font = (this._options.fontStyle ? this._options.fontStyle + " " : "") + this._options.fontSize + "px " + this._options.fontFamily; + this._context.font = font; + this._backend.compute(this._options); + this._context.font = font; + this._context.textAlign = "center"; + this._context.textBaseline = "middle"; + this._dirty = true; + } + return this; +} + +/** + * Returns currently set options + * @returns {object} Current options object + */ +ROT.Display.prototype.getOptions = function() { + return this._options; +} + +/** + * Returns the DOM node of this display + * @returns {node} DOM node + */ +ROT.Display.prototype.getContainer = function() { + return this._context.canvas; +} + +/** + * Compute the maximum width/height to fit into a set of given constraints + * @param {int} availWidth Maximum allowed pixel width + * @param {int} availHeight Maximum allowed pixel height + * @returns {int[2]} cellWidth,cellHeight + */ +ROT.Display.prototype.computeSize = function(availWidth, availHeight) { + return this._backend.computeSize(availWidth, availHeight, this._options); +} + +/** + * Compute the maximum font size to fit into a set of given constraints + * @param {int} availWidth Maximum allowed pixel width + * @param {int} availHeight Maximum allowed pixel height + * @returns {int} fontSize + */ +ROT.Display.prototype.computeFontSize = function(availWidth, availHeight) { + return this._backend.computeFontSize(availWidth, availHeight, this._options); +} + +/** + * @param {int} x + * @param {int} y + * @param {string} ch + * @param {string} [fg] foreground color + * @param {string} [bg] background color + */ +ROT.Display.prototype.draw = function(x, y, ch, fg, bg) { + if (!fg) { fg = this._options.fg; } + if (!bg) { bg = this._options.bg; } + this._data[x+","+y] = [x, y, ch, fg, bg]; + + if (this._dirty === true) { return; } /* will already redraw everything */ + if (!this._dirty) { this._dirty = {}; } /* first! */ + this._dirty[x+","+y] = true; +} + +/** + * Draws a text at given position. Optionally wraps at a maximum length. Currently does not work with hex layout. + * @param {int} x + * @param {int} y + * @param {string} text May contain color/background format specifiers, %c{name}/%b{name}, both optional. %c{}/%b{} resets to default. + * @param {int} [maxWidth] wrap at what width? + * @returns {int} lines drawn + */ +ROT.Display.prototype.drawText = function(x, y, text, maxWidth) { + var fg = null; + var bg = null; + var cx = x; + var cy = y; + var lines = 1; + if (!maxWidth) { maxWidth = this._options.width-x; } + + var tokens = ROT.Text.tokenize(text, maxWidth); + + while (tokens.length) { /* interpret tokenized opcode stream */ + var token = tokens.shift(); + switch (token.type) { + case ROT.Text.TYPE_TEXT: + for (var i=0;i 1) { /* too wide with current aspect ratio */ + boxHeight = Math.floor(boxHeight / widthFraction); + } + return Math.floor(boxHeight / this._options.spacing); +} diff --git a/lib/rotjs-library/src/engine.js b/lib/rotjs-library/src/engine.js new file mode 100644 index 0000000000000000000000000000000000000000..f91a398b6d01afaef584e25c0122049294ac948a --- /dev/null +++ b/lib/rotjs-library/src/engine.js @@ -0,0 +1,62 @@ +/** + * @class Asynchronous main loop + */ +ROT.Engine = function() { + this._scheduler = new ROT.Scheduler(); + this._lock = 1; +} + +/** + * @param {object} actor Anything with "getSpeed" and "act" methods + */ +ROT.Engine.prototype.addActor = function(actor) { + this._scheduler.add(actor); + return this; +} + +/** + * Remove a previously added actor + * @param {object} actor + */ +ROT.Engine.prototype.removeActor = function(actor) { + this._scheduler.remove(actor); + return this; +} + +/** + * Remove all actors + */ +ROT.Engine.prototype.clear = function() { + this._scheduler.clear(); + return this; +} + +/** + * Start the main loop. When this call returns, the loop is locked. + */ +ROT.Engine.prototype.start = function() { + return this.unlock(); +} + +/** + * Interrupt the engine by an asynchronous action + */ +ROT.Engine.prototype.lock = function() { + this._lock++; +} + +/** + * Resume execution (paused by a previous lock) + */ +ROT.Engine.prototype.unlock = function() { + if (!this._lock) { throw new Error("Cannot unlock unlocked engine"); } + this._lock--; + + while (!this._lock) { + var actor = this._scheduler.next(); + if (!actor) { return this.lock(); } /* no actors */ + actor.act(); + } + + return this; +} diff --git a/lib/rotjs-library/src/fov/discrete-shadowcasting.js b/lib/rotjs-library/src/fov/discrete-shadowcasting.js new file mode 100644 index 0000000000000000000000000000000000000000..611c40cf93426e188f7781ae51195fc889233d8e --- /dev/null +++ b/lib/rotjs-library/src/fov/discrete-shadowcasting.js @@ -0,0 +1,108 @@ +/** + * @class Discrete shadowcasting algorithm + * @augments ROT.FOV + */ +ROT.FOV.DiscreteShadowcasting = function(lightPassesCallback, options) { + ROT.FOV.call(this, lightPassesCallback, options); +} +ROT.FOV.DiscreteShadowcasting.extend(ROT.FOV); + +/** + * @see ROT.FOV#compute + */ +ROT.FOV.DiscreteShadowcasting.prototype.compute = function(x, y, R, callback) { + var center = this._coords; + var map = this._map; + + /* this place is always visible */ + callback(x, y, 0); + + /* standing in a dark place. FIXME is this a good idea? */ + if (!this._lightPasses(x, y)) { return; } + + /* start and end angles */ + var DATA = []; + + var A, B, cx, cy, blocks; + + /* analyze surrounding cells in concentric rings, starting from the center */ + for (var r=1; r<=R; r++) { + var neighbors = this._getCircle(x, y, r); + var angle = 360 / neighbors.length; + + for (var i=0;i A2[0]) { /* split into two sub-arcs */ + var v1 = this._checkVisibility(A1, [A1[1], A1[1]], blocks, SHADOWS); + var v2 = this._checkVisibility([0, 1], A2, blocks, SHADOWS); + return (v1+v2)/2; + } + + /* index1: first shadow >= A1 */ + var index1 = 0, edge1 = false; + while (index1 < SHADOWS.length) { + var old = SHADOWS[index1]; + var diff = old[0]*A1[1] - A1[0]*old[1]; + if (diff >= 0) { /* old >= A1 */ + if (diff == 0 && !(index1 % 2)) { edge1 = true; } + break; + } + index1++; + } + + /* index2: last shadow <= A2 */ + var index2 = SHADOWS.length, edge2 = false; + while (index2--) { + var old = SHADOWS[index2]; + var diff = A2[0]*old[1] - old[0]*A2[1]; + if (diff >= 0) { /* old <= A2 */ + if (diff == 0 && (index2 % 2)) { edge2 = true; } + break; + } + } + + var visible = true; + if (index1 == index2 && (edge1 || edge2)) { /* subset of existing shadow, one of the edges match */ + visible = false; + } else if (edge1 && edge2 && index1+1==index2 && (index2 % 2)) { /* completely equivalent with existing shadow */ + visible = false; + } else if (index1 > index2 && (index1 % 2)) { /* subset of existing shadow, not touching */ + visible = false; + } + + if (!visible) { return 0; } /* fast case: not visible */ + + var visibleLength, P; + + /* compute the length of visible arc, adjust list of shadows (if blocking) */ + var remove = index2-index1+1; + if (remove % 2) { + if (index1 % 2) { /* first edge within existing shadow, second outside */ + var P = SHADOWS[index1]; + visibleLength = (A2[0]*P[1] - P[0]*A2[1]) / (P[1] * A2[1]); + if (blocks) { SHADOWS.splice(index1, remove, A2); } + } else { /* second edge within existing shadow, first outside */ + var P = SHADOWS[index2]; + visibleLength = (P[0]*A1[1] - A1[0]*P[1]) / (A1[1] * P[1]); + if (blocks) { SHADOWS.splice(index1, remove, A1); } + } + } else { + if (index1 % 2) { /* both edges within existing shadows */ + var P1 = SHADOWS[index1]; + var P2 = SHADOWS[index2]; + visibleLength = (P2[0]*P1[1] - P1[0]*P2[1]) / (P1[1] * P2[1]); + if (blocks) { SHADOWS.splice(index1, remove); } + } else { /* both edges outside existing shadows */ + if (blocks) { SHADOWS.splice(index1, remove, A1, A2); } + return 1; /* whole arc visible! */ + } + } + + var arcLength = (A2[0]*A1[1] - A1[0]*A2[1]) / (A1[1] * A2[1]); + + return visibleLength/arcLength; +} diff --git a/lib/rotjs-library/src/gen-doc.sh b/lib/rotjs-library/src/gen-doc.sh new file mode 100644 index 0000000000000000000000000000000000000000..25f7c9f9fd5aef298ec55b4ab3d5b96388ee586e --- /dev/null +++ b/lib/rotjs-library/src/gen-doc.sh @@ -0,0 +1,3 @@ +#!/bin/sh +cd .. +jsdoc rot.js -s -a -d=doc/ diff --git a/lib/rotjs-library/src/gen-rot.sh b/lib/rotjs-library/src/gen-rot.sh new file mode 100644 index 0000000000000000000000000000000000000000..8379e1716df2f5bef57a30d7123fab940fdd429d --- /dev/null +++ b/lib/rotjs-library/src/gen-rot.sh @@ -0,0 +1,55 @@ +#!/bin/sh +LIST=" +rot.js +text.js +scheduler.js +engine.js +js/array.js +js/date.js +js/number.js +js/string.js +js/object.js +js/function.js +display/display.js +display/backend.js +display/rect.js +display/hex.js +rng.js +stringgenerator.js +map/map.js +map/arena.js +map/dividedmaze.js +map/iceymaze.js +map/ellermaze.js +map/cellular.js +map/dungeon.js +map/digger.js +map/uniform.js +map/features.js +noise/noise.js +noise/simplex.js +fov/fov.js +fov/discrete-shadowcasting.js +fov/precise-shadowcasting.js +color.js +lighting.js +path/path.js +path/dijkstra.js +path/astar.js +" + +TARGET=../rot.js +rm -f $TARGET + +VERSION=$(head -1 < ../VERSION) + +PROLOGUE="/* + This is rot.js, the ROguelike Toolkit in JavaScript. + Version $VERSION, generated on $(date). +*/ +" +echo "$PROLOGUE" >> $TARGET + +for FILE in $LIST; do + cat $FILE >> $TARGET +done diff --git a/lib/rotjs-library/src/js/array.js b/lib/rotjs-library/src/js/array.js new file mode 100644 index 0000000000000000000000000000000000000000..716a47fe11a8a6ee246d9c466f387a4af19b6988 --- /dev/null +++ b/lib/rotjs-library/src/js/array.js @@ -0,0 +1,20 @@ +/** + * @returns {any} Randomly picked item, null when length=0 + */ +Array.prototype.random = function() { + if (!this.length) { return null; } + return this[Math.floor(ROT.RNG.getUniform() * this.length)]; +} + +/** + * @returns {array} New array with randomized items + * FIXME destroys this! + */ +Array.prototype.randomize = function() { + var result = []; + while (this.length) { + var index = this.indexOf(this.random()); + result.push(this.splice(index, 1)[0]); + } + return result; +} diff --git a/lib/rotjs-library/src/js/date.js b/lib/rotjs-library/src/js/date.js new file mode 100644 index 0000000000000000000000000000000000000000..57dff3ed98a79308823e3849d414be4d254d3a3f --- /dev/null +++ b/lib/rotjs-library/src/js/date.js @@ -0,0 +1,6 @@ +if (!Date.now) { + /** + * @returns {int} Current timestamp (msec) + */ + Date.now = function() { return +(new Date); } +} diff --git a/lib/rotjs-library/src/js/function.js b/lib/rotjs-library/src/js/function.js new file mode 100644 index 0000000000000000000000000000000000000000..839e2f6def0714980ae55192b3e0590e0992b91f --- /dev/null +++ b/lib/rotjs-library/src/js/function.js @@ -0,0 +1,9 @@ +/** + * Sets prototype of this function to an instance of parent function + * @param {function} parent + */ +Function.prototype.extend = function(parent) { + this.prototype = Object.create(parent.prototype); + this.prototype.constructor = this; + return this; +} diff --git a/lib/rotjs-library/src/js/number.js b/lib/rotjs-library/src/js/number.js new file mode 100644 index 0000000000000000000000000000000000000000..802d5257051f33d293fd4f9e92e6a1e743baf0e5 --- /dev/null +++ b/lib/rotjs-library/src/js/number.js @@ -0,0 +1,8 @@ +/** + * Always positive modulus + * @param {int} n Modulus + * @returns {int} this modulo n + */ +Number.prototype.mod = function(n) { + return ((this%n)+n)%n; +} diff --git a/lib/rotjs-library/src/js/object.js b/lib/rotjs-library/src/js/object.js new file mode 100644 index 0000000000000000000000000000000000000000..fd81a107fd2481fd6be7a70856468f2e8f1be509 --- /dev/null +++ b/lib/rotjs-library/src/js/object.js @@ -0,0 +1,10 @@ +if (!Object.create) { + /** + * ES5 Object.create + */ + Object.create = function(o) { + var tmp = function() {}; + tmp.prototype = o; + return new tmp(); + }; +} diff --git a/lib/rotjs-library/src/js/string.js b/lib/rotjs-library/src/js/string.js new file mode 100644 index 0000000000000000000000000000000000000000..7ec2ac61c05a131cd3bf12ba426fe22bb0ca5cd4 --- /dev/null +++ b/lib/rotjs-library/src/js/string.js @@ -0,0 +1,81 @@ +/** + * @returns {string} First letter capitalized + */ +String.prototype.capitalize = function() { + return this.charAt(0).toUpperCase() + this.substring(1); +} + +/** + * Left pad + * @param {string} [character="0"] + * @param {int} [count=2] + */ +String.prototype.lpad = function(character, count) { + var ch = character || "0"; + var cnt = count || 2; + + var s = ""; + while (s.length < (cnt - this.length)) { s += ch; } + s = s.substring(0, cnt-this.length); + return s+this; +} + +/** + * Right pad + * @param {string} [character="0"] + * @param {int} [count=2] + */ +String.prototype.rpad = function(character, count) { + var ch = character || "0"; + var cnt = count || 2; + + var s = ""; + while (s.length < (cnt - this.length)) { s += ch; } + s = s.substring(0, cnt-this.length); + return this+s; +} + +/** + * Format a string in a flexible way. Scans for %s strings and replaces them with arguments. List of patterns is modifiable via String.format.map. + * @param {string} template + * @param {any} [argv] + */ +String.format = function(template) { + var map = String.format.map; + var args = Array.prototype.slice.call(arguments, 1); + + var replacer = function(match, group1, group2, index) { + if (template.charAt(index-1) == "%") { return match.substring(1); } + if (!args.length) { return match; } + var obj = args[0]; + + var group = group1 || group2; + var parts = group.split(","); + var name = parts.shift(); + var method = map[name.toLowerCase()]; + if (!method) { return match; } + + var obj = args.shift(); + var replaced = obj[method].apply(obj, parts); + + var first = name.charAt(0); + if (first != first.toLowerCase()) { replaced = replaced.capitalize(); } + + return replaced; + } + return template.replace(/%(?:([a-z]+)|(?:{([^}]+)}))/gi, replacer); +} + +String.format.map = { + "s": "toString" +} + +/** + * Convenience shortcut to String.format(this) + */ +String.prototype.format = function() { + var args = Array.prototype.slice.call(arguments); + args.unshift(this); + return String.format.apply(String, args); +} + diff --git a/lib/rotjs-library/src/lighting.js b/lib/rotjs-library/src/lighting.js new file mode 100644 index 0000000000000000000000000000000000000000..862d9856caa0cc9744265afccf518411c40eb3a0 --- /dev/null +++ b/lib/rotjs-library/src/lighting.js @@ -0,0 +1,213 @@ +/** + * @class Lighting computation, based on a traditional FOV for multiple light sources and multiple passes. + * @param {function} reflectivityCallback Callback to retrieve cell reflectivity (0..1) + * @param {object} [options] + * @param {int} [options.passes=1] Number of passes. 1 equals to simple FOV of all light sources, >1 means a *highly simplified* radiosity-like algorithm. + * @param {int} [options.emissionThreshold=100] Cells with emissivity > threshold will be treated as light source in the next pass. + * @param {int} [options.range=10] Max light range + */ +ROT.Lighting = function(reflectivityCallback, options) { + this._reflectivityCallback = reflectivityCallback; + this._options = { + passes: 1, + emissionThreshold: 100, + range: 10 + }; + this._fov = null; + + this._lights = {}; + this._reflectivityCache = {}; + this._fovCache = {}; + + this.setOptions(options); +} + +/** + * Adjust options at runtime + * @see ROT.Lighting + * @param {object} [options] + */ +ROT.Lighting.prototype.setOptions = function(options) { + for (var p in options) { this._options[p] = options[p]; } + if (options.range) { this.reset(); } + return this; +} + +/** + * Set the used Field-Of-View algo + * @param {ROT.FOV} fov + */ +ROT.Lighting.prototype.setFOV = function(fov) { + this._fov = fov; + this._fovCache = {}; + return this; +} + +/** + * Set (or remove) a light source + * @param {int} x + * @param {int} y + * @param {null || string || number[3]} color + */ +ROT.Lighting.prototype.setLight = function(x, y, color) { + var key = x+","+y; + + if (color) { + this._lights[key] = (typeof(color) == "string" ? ROT.Color.fromString(color) : color); + } else { + delete this._lights[key]; + } + return this; +} + +/** + * Reset the pre-computed topology values. Call whenever the underlying map changes its light-passability. + */ +ROT.Lighting.prototype.reset = function() { + this._reflectivityCache = {}; + this._fovCache = {}; + + return this; +} + +/** + * Compute the lighting + * @param {function} lightingCallback Will be called with (x, y, color) for every lit cell + */ +ROT.Lighting.prototype.compute = function(lightingCallback) { + var doneCells = {}; + var emittingCells = {}; + var litCells = {}; + + for (var key in this._lights) { /* prepare emitters for first pass */ + var light = this._lights[key]; + if (!(key in emittingCells)) { emittingCells[key] = [0, 0, 0]; } + + ROT.Color.add_(emittingCells[key], light); + } + + for (var i=0;i this._options.emissionThreshold) { result[key] = emission; } + } + + return result; +} + +/** + * Compute one iteration from one cell + * @param {int} x + * @param {int} y + * @param {number[]} color + * @param {object} litCells Cell data to by updated + */ +ROT.Lighting.prototype._emitLightFromCell = function(x, y, color, litCells) { + var key = x+","+y; + if (key in this._fovCache) { + var fov = this._fovCache[key]; + } else { + var fov = this._updateFOV(x, y); + } + + for (var fovKey in fov) { + var formFactor = fov[fovKey]; + + if (fovKey in litCells) { /* already lit */ + var result = litCells[fovKey]; + } else { /* newly lit */ + var result = [0, 0, 0]; + litCells[fovKey] = result; + } + + for (var i=0;i<3;i++) { result[i] += Math.round(color[i]*formFactor); } /* add light color */ + } + + return this; +} + +/** + * Compute FOV ("form factor") for a potential light source at [x,y] + * @param {int} x + * @param {int} y + * @returns {object} + */ +ROT.Lighting.prototype._updateFOV = function(x, y) { + var key1 = x+","+y; + var cache = {}; + this._fovCache[key1] = cache; + var range = this._options.range; + var cb = function(x, y, r, vis) { + var key2 = x+","+y; + var formFactor = vis * (1-r/range); + if (formFactor == 0) { return; } + cache[key2] = formFactor; + } + this._fov.compute(x, y, range, cb.bind(this)); + + return cache; +} diff --git a/lib/rotjs-library/src/map/arena.js b/lib/rotjs-library/src/map/arena.js new file mode 100644 index 0000000000000000000000000000000000000000..5c3e5d23e3a8b7b9a02a2ada281d4a85736ff252 --- /dev/null +++ b/lib/rotjs-library/src/map/arena.js @@ -0,0 +1,20 @@ +/** + * @class Simple empty rectangular room + * @augments ROT.Map + */ +ROT.Map.Arena = function(width, height) { + ROT.Map.call(this, width, height); +} +ROT.Map.Arena.extend(ROT.Map); + +ROT.Map.Arena.prototype.create = function(callback) { + var w = this._width-1; + var h = this._height-1; + for (var i=0;i<=w;i++) { + for (var j=0;j<=h;j++) { + var empty = (i && j && i= this._width || x < 0 || y >= this._width) { continue; } + result += (this._map[x][y] == 1 ? 1 : 0); + } + + return result; +} diff --git a/lib/rotjs-library/src/map/digger.js b/lib/rotjs-library/src/map/digger.js new file mode 100644 index 0000000000000000000000000000000000000000..c529f7ff6f85bab1a918d0a02e0ad13c0741d6e8 --- /dev/null +++ b/lib/rotjs-library/src/map/digger.js @@ -0,0 +1,230 @@ +/** + * @class Random dungeon generator using human-like digging patterns. + * Heavily based on Mike Anderson's ideas from the "Tyrant" algo, mentioned at + * http://www.roguebasin.roguelikedevelopment.org/index.php?title=Dungeon-Building_Algorithm. + * @augments ROT.Map.Dungeon + */ +ROT.Map.Digger = function(width, height, options) { + ROT.Map.Dungeon.call(this, width, height); + + this._options = { + roomWidth: [3, 9], /* room minimum and maximum width */ + roomHeight: [3, 5], /* room minimum and maximum height */ + corridorLength: [3, 10], /* corridor minimum and maximum length */ + dugPercentage: 0.2, /* we stop after this percentage of level area has been dug out */ + timeLimit: 1000 /* we stop after this much time has passed (msec) */ + } + for (var p in options) { this._options[p] = options[p]; } + + this._features = { + "Room": 4, + "Corridor": 4 + } + this._featureAttempts = 20; /* how many times do we try to create a feature on a suitable wall */ + this._walls = {}; /* these are available for digging */ + + this._digCallback = this._digCallback.bind(this); + this._canBeDugCallback = this._canBeDugCallback.bind(this); + this._isWallCallback = this._isWallCallback.bind(this); + this._priorityWallCallback = this._priorityWallCallback.bind(this); +} +ROT.Map.Digger.extend(ROT.Map.Dungeon); + +/** + * Create a map + * @see ROT.Map#create + */ +ROT.Map.Digger.prototype.create = function(callback) { + this._rooms = []; + this._corridors = []; + this._map = this._fillMap(1); + this._walls = {}; + this._dug = 0; + var area = (this._width-2) * (this._height-2); + + this._firstRoom(); + + var t1 = Date.now(); + + do { + var t2 = Date.now(); + if (t2 - t1 > this._options.timeLimit) { break; } + + /* find a good wall */ + var wall = this._findWall(); + if (!wall) { break; } /* no more walls */ + + var parts = wall.split(","); + var x = parseInt(parts[0]); + var y = parseInt(parts[1]); + var dir = this._getDiggingDirection(x, y); + if (!dir) { continue; } /* this wall is not suitable */ + +// console.log("wall", x, y); + + /* try adding a feature */ + var featureAttempts = 0; + do { + featureAttempts++; + if (this._tryFeature(x, y, dir[0], dir[1])) { /* feature added */ + if (this._rooms.length + this._corridors.length == 2) { this._rooms[0].addDoor(x, y); } /* first room oficially has doors */ + this._removeSurroundingWalls(x, y); + this._removeSurroundingWalls(x-dir[0], y-dir[1]); + break; + } + } while (featureAttempts < this._featureAttempts); + + var priorityWalls = 0; + for (var id in this._walls) { + if (this._walls[id] > 1) { priorityWalls++; } + } + + } while (this._dug/area < this._options.dugPercentage || priorityWalls); /* fixme number of priority walls */ + + if (callback) { + for (var i=0;i= this._width || y >= this._height) { return false; } + return (this._map[x][y] == 1); +} + +ROT.Map.Digger.prototype._canBeDugCallback = function(x, y) { + if (x < 1 || y < 1 || x+1 >= this._width || y+1 >= this._height) { return false; } + return (this._map[x][y] == 1); +} + +ROT.Map.Digger.prototype._priorityWallCallback = function(x, y) { + this._walls[x+","+y] = 2; +} + +ROT.Map.Digger.prototype._firstRoom = function() { + var cx = Math.floor(this._width/2); + var cy = Math.floor(this._height/2); + var room = ROT.Map.Feature.Room.createRandomCenter(cx, cy, this._options); + this._rooms.push(room); + room.create(this._digCallback); +} + +/** + * Get a suitable wall + */ +ROT.Map.Digger.prototype._findWall = function() { + var prio1 = []; + var prio2 = []; + for (var id in this._walls) { + var prio = this._walls[id]; + if (prio == 2) { + prio2.push(id); + } else { + prio1.push(id); + } + } + + var arr = (prio2.length ? prio2 : prio1); + if (!arr.length) { return null; } /* no walls :/ */ + + var id = arr.random(); + delete this._walls[id]; + + return id; +} + +/** + * Tries adding a feature + * @returns {bool} was this a successful try? + */ +ROT.Map.Digger.prototype._tryFeature = function(x, y, dx, dy) { + var feature = null; + var total = 0; + for (var p in this._features) { total += this._features[p]; } + var random = Math.floor(ROT.RNG.getUniform()*total); + + var sub = 0; + for (var p in this._features) { + sub += this._features[p]; + if (random < sub) { + feature = ROT.Map.Feature[p]; + break; + } + } + + feature = feature.createRandomAt(x, y, dx, dy, this._options); + + if (!feature.isValid(this._isWallCallback, this._canBeDugCallback)) { +// console.log("not valid"); +// feature.debug(); + return false; + } + + feature.create(this._digCallback); +// feature.debug(); + + if (feature instanceof ROT.Map.Feature.Room) { this._rooms.push(feature); } + if (feature instanceof ROT.Map.Feature.Corridor) { + feature.createPriorityWalls(this._priorityWallCallback); + this._corridors.push(feature); + } + + return true; +} + +ROT.Map.Digger.prototype._removeSurroundingWalls = function(cx, cy) { + var deltas = ROT.DIRS[4]; + + for (var i=0;i= this._width || y >= this._width) { return null; } + + if (!this._map[x][y]) { /* there already is another empty neighbor! */ + if (result) { return null; } + result = delta; + } + } + + /* no empty neighbor */ + if (!result) { return null; } + + return [-result[0], -result[1]]; +} diff --git a/lib/rotjs-library/src/map/dividedmaze.js b/lib/rotjs-library/src/map/dividedmaze.js new file mode 100644 index 0000000000000000000000000000000000000000..c256c8b6304a3508bafb5e6849344d39c94fb26e --- /dev/null +++ b/lib/rotjs-library/src/map/dividedmaze.js @@ -0,0 +1,108 @@ +/** + * @class Recursively divided maze, http://en.wikipedia.org/wiki/Maze_generation_algorithm#Recursive_division_method + * @augments ROT.Map + */ +ROT.Map.DividedMaze = function(width, height) { + ROT.Map.call(this, width, height); + this._stack = []; +} +ROT.Map.DividedMaze.extend(ROT.Map); + +ROT.Map.DividedMaze.prototype.create = function(callback) { + var w = this._width; + var h = this._height; + + this._map = []; + + for (var i=0;i rand) { + this._addToList(i, L, R); + map[x+1][y] = 0; + } + + /* bottom connection */ + if (i != L[i] && ROT.RNG.getUniform() > rand) { + /* remove connection */ + this._removeFromList(i, L, R); + } else { + /* create connection */ + map[x][y+1] = 0; + } + } + } + + /* last row */ + for (var i=0;i rand)) { + /* dig right also if the cell is separated, so it gets connected to the rest of maze */ + this._addToList(i, L, R); + map[x+1][y] = 0; + } + + this._removeFromList(i, L, R); + } + + for (var i=0;i 4) { this.addDoor(doorX, doorY); } +} +ROT.Map.Feature.Room.extend(ROT.Map.Feature); + +/** + * Room of random size, with a given doors and direction + */ +ROT.Map.Feature.Room.createRandomAt = function(x, y, dx, dy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var min = options.roomHeight[0]; + var max = options.roomHeight[1]; + var height = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + if (dx == 1) { /* to the right */ + var y2 = y - Math.floor(ROT.RNG.getUniform() * height); + return new this(x+1, y2, x+width, y2+height-1, x, y); + } + + if (dx == -1) { /* to the left */ + var y2 = y - Math.floor(ROT.RNG.getUniform() * height); + return new this(x-width, y2, x-1, y2+height-1, x, y); + } + + if (dy == 1) { /* to the bottom */ + var x2 = x - Math.floor(ROT.RNG.getUniform() * width); + return new this(x2, y+1, x2+width-1, y+height, x, y); + } + + if (dy == -1) { /* to the top */ + var x2 = x - Math.floor(ROT.RNG.getUniform() * width); + return new this(x2, y-height, x2+width-1, y-1, x, y); + } +} + +/** + * Room of random size, positioned around center coords + */ +ROT.Map.Feature.Room.createRandomCenter = function(cx, cy, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var min = options.roomHeight[0]; + var max = options.roomHeight[1]; + var height = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var x1 = cx - Math.floor(ROT.RNG.getUniform()*width); + var y1 = cy - Math.floor(ROT.RNG.getUniform()*height); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + + return new this(x1, y1, x2, y2); +} + +/** + * Room of random size within a given dimensions + */ +ROT.Map.Feature.Room.createRandom = function(availWidth, availHeight, options) { + var min = options.roomWidth[0]; + var max = options.roomWidth[1]; + var width = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var min = options.roomHeight[0]; + var max = options.roomHeight[1]; + var height = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + var left = availWidth - width - 1; + var top = availHeight - height - 1; + + var x1 = 1 + Math.floor(ROT.RNG.getUniform()*left); + var y1 = 1 + Math.floor(ROT.RNG.getUniform()*top); + var x2 = x1 + width - 1; + var y2 = y1 + height - 1; + + return new this(x1, y1, x2, y2); +} + +ROT.Map.Feature.Room.prototype.addDoor = function(x, y) { + this._doors[x+","+y] = 1; +} + +/** + * @param {function} + */ +ROT.Map.Feature.Room.prototype.getDoors = function(callback) { + for (var key in this._doors) { + var parts = key.split(","); + callback(parseInt(parts[0]), parseInt(parts[1])); + } +} + +ROT.Map.Feature.Room.prototype.clearDoors = function() { + this._doors = {}; + return this; +} + +ROT.Map.Feature.Room.prototype.debug = function() { + console.log("room", this._x1, this._y1, this._x2, this._y2); +} + +ROT.Map.Feature.Room.prototype.isValid = function(isWallCallback, canBeDugCallback) { + var left = this._x1-1; + var right = this._x2+1; + var top = this._y1-1; + var bottom = this._y2+1; + + for (var x=left; x<=right; x++) { + for (var y=top; y<=bottom; y++) { + if (x == left || x == right || y == top || y == bottom) { + if (!isWallCallback(x, y)) { return false; } + } else { + if (!canBeDugCallback(x, y)) { return false; } + } + } + } + + return true; +} + +/** + * @param {function} digCallback Dig callback with a signature (x, y, value). Values: 0 = empty, 1 = wall, 2 = door. Multiple doors are allowed. + */ +ROT.Map.Feature.Room.prototype.create = function(digCallback) { + var left = this._x1-1; + var right = this._x2+1; + var top = this._y1-1; + var bottom = this._y2+1; + + var value = 0; + for (var x=left; x<=right; x++) { + for (var y=top; y<=bottom; y++) { + if (x+","+y in this._doors) { + value = 2; + } else if (x == left || x == right || y == top || y == bottom) { + value = 1; + } else { + value = 0; + } + digCallback(x, y, value); + } + } +} + +ROT.Map.Feature.Room.prototype.getCenter = function() { + return [Math.round((this._x1 + this._x2)/2), Math.round((this._y1 + this._y2)/2)]; +} + +ROT.Map.Feature.Room.prototype.getLeft = function() { + return this._x1; +} + +ROT.Map.Feature.Room.prototype.getRight = function() { + return this._x2; +} + +ROT.Map.Feature.Room.prototype.getTop = function() { + return this._y1; +} + +ROT.Map.Feature.Room.prototype.getBottom = function() { + return this._y2; +} + +/** + * @class Corridor + * @augments ROT.Map.Feature + * @param {int} startX + * @param {int} startY + * @param {int} endX + * @param {int} endY + */ +ROT.Map.Feature.Corridor = function(startX, startY, endX, endY) { + this._startX = startX; + this._startY = startY; + this._endX = endX; + this._endY = endY; + this._endsWithAWall = true; +} +ROT.Map.Feature.Corridor.extend(ROT.Map.Feature); + +ROT.Map.Feature.Corridor.createRandomAt = function(x, y, dx, dy, options) { + var min = options.corridorLength[0]; + var max = options.corridorLength[1]; + var length = min + Math.floor(ROT.RNG.getUniform()*(max-min+1)); + + return new this(x, y, x + dx*length, y + dy*length); +} + +ROT.Map.Feature.Corridor.prototype.debug = function() { + console.log("corridor", this._startX, this._startY, this._endX, this._endY); +} + +ROT.Map.Feature.Corridor.prototype.isValid = function(isWallCallback, canBeDugCallback){ + var sx = this._startX; + var sy = this._startY; + var dx = this._endX-sx; + var dy = this._endY-sy; + var length = 1 + Math.max(Math.abs(dx), Math.abs(dy)); + + if (dx) { dx = dx/Math.abs(dx); } + if (dy) { dy = dy/Math.abs(dy); } + var nx = dy; + var ny = -dx; + + var ok = true; + for (var i=0; i= width || y >= height) { return false; } + return map[x][y]; +} diff --git a/lib/rotjs-library/src/map/map.js b/lib/rotjs-library/src/map/map.js new file mode 100644 index 0000000000000000000000000000000000000000..00094285c972bbb5e2301baf9f69fb3380661182 --- /dev/null +++ b/lib/rotjs-library/src/map/map.js @@ -0,0 +1,20 @@ +/** + * @class Base map generator + * @param {int} [width=ROT.DEFAULT_WIDTH] + * @param {int} [height=ROT.DEFAULT_HEIGHT] + */ +ROT.Map = function(width, height) { + this._width = width || ROT.DEFAULT_WIDTH; + this._height = height || ROT.DEFAULT_HEIGHT; +}; + +ROT.Map.prototype.create = function(callback) {} + +ROT.Map.prototype._fillMap = function(value) { + var map = []; + for (var i=0;i this._options.timeLimit) { return null; } /* time limit! */ + + this._map = this._fillMap(1); + this._dug = 0; + this._rooms = []; + this._unconnected = []; + this._generateRooms(); + if (this._generateCorridors()) { break; } + } + + if (callback) { + for (var i=0;i this._options.roomDugPercentage) { break; } /* achieved requested amount of free space */ + } while (room); + + /* either enough rooms, or not able to generate more of them :) */ +} + +/** + * Try to generate one room + */ +ROT.Map.Uniform.prototype._generateRoom = function() { + var count = 0; + while (count < this._roomAttempts) { + count++; + + var room = ROT.Map.Feature.Room.createRandom(this._width, this._height, this._options); + if (!room.isValid(this._isWallCallback, this._canBeDugCallback)) { continue; } + + room.create(this._digCallback); + this._rooms.push(room); + return room; + } + + /* no room was generated in a given number of attempts */ + return null; +} + +/** + * Generates connectors beween rooms + * @returns {bool} success Was this attempt successfull? + */ +ROT.Map.Uniform.prototype._generateCorridors = function() { + var cnt = 0; + while (cnt < this._corridorAttempts) { + cnt++; + this._corridors = []; + + /* dig rooms into a clear map */ + this._map = this._fillMap(1); + for (var i=0;i 0 ? 2 : 0); + var dirIndex2 = (dirIndex1 + 2) % 4; + var min = room2.getLeft(); + var max = room2.getRight(); + var index = 0; + } else { /* first try connecting east-west walls */ + var dirIndex1 = (diffX > 0 ? 1 : 3); + var dirIndex2 = (dirIndex1 + 2) % 4; + var min = room2.getTop(); + var max = room2.getBottom(); + var index = 1; + } + + var start = this._placeInWall(room1, dirIndex1); /* corridor will start here */ + if (!start) { return false; } + + if (start[index] >= min && start[index] <= max) { /* possible to connect with straight line (I-like) */ + var end = start.slice(); + var value = null; + switch (dirIndex2) { + case 0: value = room2.getTop()-1; break; + case 1: value = room2.getRight()+1; break; + case 2: value = room2.getBottom()+1; break; + case 3: value = room2.getLeft()-1; break; + } + end[(index+1)%2] = value; + this._digLine([start, end]); + + } else if (start[index] < min-1 || start[index] > max+1) { /* need to switch target wall (L-like) */ + + var diff = start[index] - center2[index]; + switch (dirIndex2) { + case 0: + case 1: var rotation = (diff < 0 ? 3 : 1); break; + case 2: + case 3: var rotation = (diff < 0 ? 1 : 3); break; + } + dirIndex2 = (dirIndex2 + rotation) % 4; + + var end = this._placeInWall(room2, dirIndex2); + if (!end) { return false; } + + var mid = [0, 0]; + mid[index] = start[index]; + var index2 = (index+1)%2; + mid[index2] = end[index2]; + this._digLine([start, mid, end]); + + } else { /* use current wall pair, but adjust the line in the middle (S-like) */ + + var index2 = (index+1)%2; + var end = this._placeInWall(room2, dirIndex2); + if (!end) { return; } + var mid = Math.round((end[index2] + start[index2])/2); + + var mid1 = [0, 0]; + var mid2 = [0, 0]; + mid1[index] = start[index]; + mid1[index2] = mid; + mid2[index] = end[index]; + mid2[index2] = mid; + this._digLine([start, mid1, mid2, end]); + } + + room1.addDoor(start[0], start[1]); + room2.addDoor(end[0], end[1]); + + var index = this._unconnected.indexOf(room1); + if (index != -1) { + this._unconnected.splice(index, 1); + this._connected.push(room1); + } + + var index = this._unconnected.indexOf(room2); + if (index != -1) { + this._unconnected.splice(index, 1); + this._connected.push(room2); + } + + return true; +} + +ROT.Map.Uniform.prototype._placeInWall = function(room, dirIndex) { + var start = [0, 0]; + var dir = [0, 0]; + var length = 0; + + switch (dirIndex) { + case 0: + dir = [1, 0]; + start = [room.getLeft(), room.getTop()-1]; + length = room.getRight()-room.getLeft()+1; + break; + case 1: + dir = [0, 1]; + start = [room.getRight()+1, room.getTop()]; + length = room.getBottom()-room.getTop()+1; + break; + case 2: + dir = [1, 0]; + start = [room.getLeft(), room.getBottom()+1]; + length = room.getRight()-room.getLeft()+1; + break; + case 3: + dir = [0, 1]; + start = [room.getLeft()-1, room.getTop()]; + length = room.getBottom()-room.getTop()+1; + break; + } + + var avail = []; + var lastBadIndex = -2; + + for (var i=0;i=0; i--) { + if (!avail[i]) { avail.splice(i, 1); } + } + return (avail.length ? avail.random() : null); +} + +/** + * Dig a polyline. + */ +ROT.Map.Uniform.prototype._digLine = function(points) { + for (var i=1;i= this._width || y >= this._height) { return false; } + return (this._map[x][y] == 1); +} + +ROT.Map.Uniform.prototype._canBeDugCallback = function(x, y) { + if (x < 1 || y < 1 || x+1 >= this._width || y+1 >= this._height) { return false; } + return (this._map[x][y] == 1); +} + diff --git a/lib/rotjs-library/src/noise/noise.js b/lib/rotjs-library/src/noise/noise.js new file mode 100644 index 0000000000000000000000000000000000000000..58ccee759e8609ab8f5628f1579116a189a52334 --- /dev/null +++ b/lib/rotjs-library/src/noise/noise.js @@ -0,0 +1,7 @@ +/** + * @class Base noise generator + */ +ROT.Noise = function() { +}; + +ROT.Noise.prototype.get = function(x, y) {} diff --git a/lib/rotjs-library/src/noise/simplex.js b/lib/rotjs-library/src/noise/simplex.js new file mode 100644 index 0000000000000000000000000000000000000000..aab11d3f374bb172d44a60d878212acc8569de35 --- /dev/null +++ b/lib/rotjs-library/src/noise/simplex.js @@ -0,0 +1,116 @@ +/** + * A simple 2d implementation of simplex noise by Ondrej Zara + * + * Based on a speed-improved simplex noise algorithm for 2D, 3D and 4D in Java. + * Which is based on example code by Stefan Gustavson (stegu@itn.liu.se). + * With Optimisations by Peter Eastman (peastman@drizzle.stanford.edu). + * Better rank ordering method by Stefan Gustavson in 2012. + */ + +/** + * @class 2D simplex noise generator + * @param {int} [gradients=256] Random gradients + */ +ROT.Noise.Simplex = function(gradients) { + ROT.Noise.call(this); + + this._F2 = 0.5 * (Math.sqrt(3) - 1); + this._G2 = (3 - Math.sqrt(3)) / 6; + + this._gradients = [ + [ 0, -1], + [ 1, -1], + [ 1, 0], + [ 1, 1], + [ 0, 1], + [-1, 1], + [-1, 0], + [-1, -1] + ]; + + var permutations = []; + var count = gradients || 256; + for (var i=0;i y0) { + i1 = 1; + j1 = 0; + } else { // lower triangle, XY order: (0,0)->(1,0)->(1,1) + i1 = 0; + j1 = 1; + } // upper triangle, YX order: (0,0)->(0,1)->(1,1) + + // A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and + // a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where + // c = (3-sqrt(3))/6 + var x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords + var y1 = y0 - j1 + G2; + var x2 = x0 - 1 + 2*G2; // Offsets for last corner in (x,y) unskewed coords + var y2 = y0 - 1 + 2*G2; + + // Work out the hashed gradient indices of the three simplex corners + var ii = i.mod(count); + var jj = j.mod(count); + + // Calculate the contribution from the three corners + var t0 = 0.5 - x0*x0 - y0*y0; + if (t0 >= 0) { + t0 *= t0; + gi = indexes[ii+perms[jj]]; + var grad = this._gradients[gi]; + n0 = t0 * t0 * (grad[0] * x0 + grad[1] * y0); + } + + var t1 = 0.5 - x1*x1 - y1*y1; + if (t1 >= 0) { + t1 *= t1; + gi = indexes[ii+i1+perms[jj+j1]]; + var grad = this._gradients[gi]; + n1 = t1 * t1 * (grad[0] * x1 + grad[1] * y1); + } + + var t2 = 0.5 - x2*x2 - y2*y2; + if (t2 >= 0) { + t2 *= t2; + gi = indexes[ii+1+perms[jj+1]]; + var grad = this._gradients[gi]; + n2 = t2 * t2 * (grad[0] * x2 + grad[1] * y2); + } + + // Add contributions from each corner to get the final noise value. + // The result is scaled to return values in the interval [-1,1]. + return 70 * (n0 + n1 + n2); +} diff --git a/lib/rotjs-library/src/path/astar.js b/lib/rotjs-library/src/path/astar.js new file mode 100644 index 0000000000000000000000000000000000000000..6df4d7b7f6036e2cabeed7256c67e40492fea3eb --- /dev/null +++ b/lib/rotjs-library/src/path/astar.js @@ -0,0 +1,91 @@ +/** + * @class Simplified A* algorithm: all edges have a value of 1 + * @augments ROT.Path + * @see ROT.Path + */ +ROT.Path.AStar = function(toX, toY, passableCallback, options) { + ROT.Path.call(this, toX, toY, passableCallback, options); + + this._todo = []; + this._done = {}; + this._fromX = null; + this._fromY = null; +} +ROT.Path.AStar.extend(ROT.Path); + +/** + * Compute a path from a given point + * @see ROT.Path#compute + */ +ROT.Path.AStar.prototype.compute = function(fromX, fromY, callback) { + this._todo = []; + this._done = {}; + this._fromX = fromX; + this._fromY = fromY; + this._add(this._toX, this._toY, null); + + while (this._todo.length) { + var item = this._todo.shift(); + if (item.x == fromX && item.y == fromY) { break; } + var neighbors = this._getNeighbors(item.x, item.y); + + for (var i=0;i>> 0) * this._frac; + + seed = (seed*69069 + 1) >>> 0; + this._s1 = seed * this._frac; + + seed = (seed*69069 + 1) >>> 0; + this._s2 = seed * this._frac; + + this._c = 1; + return this; + }, + + /** + * @returns {float} Pseudorandom value [0,1), uniformly distributed + */ + getUniform: function() { + var t = 2091639 * this._s0 + this._c * this._frac; + this._s0 = this._s1; + this._s1 = this._s2; + this._c = t | 0; + this._s2 = t - this._c; + return this._s2; + }, + + /** + * @param {float} [mean=0] Mean value + * @param {float} [stddev=1] Standard deviation. ~95% of the absolute values will be lower than 2*stddev. + * @returns {float} A normally distributed pseudorandom value + */ + getNormal: function(mean, stddev) { + do { + var u = 2*this.getUniform()-1; + var v = 2*this.getUniform()-1; + var r = u*u + v*v; + } while (r > 1 || r == 0); + + var gauss = u * Math.sqrt(-2*Math.log(r)/r); + return (mean || 0) + gauss*(stddev || 1); + }, + + /** + * @returns {int} Pseudorandom value [1,100] inclusive, uniformly distributed + */ + getPercentage: function() { + return 1 + Math.floor(this.getUniform()*100); + }, + + /** + * @param {object} data key=whatever, value=weight (relative probability) + * @returns {string} whatever + */ + getWeightedValue: function(data) { + var avail = []; + var total = 0; + + for (var id in data) { + total += data[id]; + } + var random = Math.floor(this.getUniform()*total); + + var part = 0; + for (var id in data) { + part += data[id]; + if (random < part) { return id; } + } + + return null; + }, + + /** + * Get RNG state. Useful for storing the state and re-setting it via setState. + * @returns {?} Internal state + */ + getState: function() { + return [this._s0, this._s1, this._s2, this._c]; + }, + + /** + * Set a previously retrieved state. + * @param {?} state + */ + setState: function(state) { + this._s0 = state[0]; + this._s1 = state[1]; + this._s2 = state[2]; + this._c = state[3]; + return this; + }, + + _s0: 0, + _s1: 0, + _s2: 0, + _c: 0, + _frac: 2.3283064365386963e-10 /* 2^-32 */ +} + +ROT.RNG.setSeed(Date.now()); diff --git a/lib/rotjs-library/src/rot.js b/lib/rotjs-library/src/rot.js new file mode 100644 index 0000000000000000000000000000000000000000..86b77ed44da6b180570cb81696295a9ce1e8f287 --- /dev/null +++ b/lib/rotjs-library/src/rot.js @@ -0,0 +1,353 @@ +/** + * @namespace Top-level ROT namespace + */ +var ROT = { + /** + * @returns {bool} Is rot.js supported by this browser? + */ + isSupported: function() { + return !!(document.createElement("canvas").getContext && Function.prototype.bind); + }, + + /** Default with for display and map generators */ + DEFAULT_WIDTH: 80, + /** Default height for display and map generators */ + DEFAULT_HEIGHT: 25, + + /** Directional constants. Ordering is important! */ + DIRS: { + "4": [ + [ 0, -1], + [ 1, 0], + [ 0, 1], + [-1, 0] + ], + "8": [ + [ 0, -1], + [ 1, -1], + [ 1, 0], + [ 1, 1], + [ 0, 1], + [-1, 1], + [-1, 0], + [-1, -1] + ], + "6": [ + [-1, -1], + [ 1, -1], + [ 2, 0], + [ 1, 1], + [-1, 1], + [-2, 0] + ] + }, + + /** Cancel key. */ + VK_CANCEL: 3, + /** Help key. */ + VK_HELP: 6, + /** Backspace key. */ + VK_BACK_SPACE: 8, + /** Tab key. */ + VK_TAB: 9, + /** 5 key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key. */ + VK_CLEAR: 12, + /** Return/enter key on the main keyboard. */ + VK_RETURN: 13, + /** Reserved, but not used. */ + VK_ENTER: 14, + /** Shift key. */ + VK_SHIFT: 16, + /** Control key. */ + VK_CONTROL: 17, + /** Alt (Option on Mac) key. */ + VK_ALT: 18, + /** Pause key. */ + VK_PAUSE: 19, + /** Caps lock. */ + VK_CAPS_LOCK: 20, + /** Escape key. */ + VK_ESCAPE: 27, + /** Space bar. */ + VK_SPACE: 32, + /** Page Up key. */ + VK_PAGE_UP: 33, + /** Page Down key. */ + VK_PAGE_DOWN: 34, + /** End key. */ + VK_END: 35, + /** Home key. */ + VK_HOME: 36, + /** Left arrow. */ + VK_LEFT: 37, + /** Up arrow. */ + VK_UP: 38, + /** Right arrow. */ + VK_RIGHT: 39, + /** Down arrow. */ + VK_DOWN: 40, + /** Print Screen key. */ + VK_PRINTSCREEN: 44, + /** Ins(ert) key. */ + VK_INSERT: 45, + /** Del(ete) key. */ + VK_DELETE: 46, + /***/ + VK_0: 48, + /***/ + VK_1: 49, + /***/ + VK_2: 50, + /***/ + VK_3: 51, + /***/ + VK_4: 52, + /***/ + VK_5: 53, + /***/ + VK_6: 54, + /***/ + VK_7: 55, + /***/ + VK_8: 56, + /***/ + VK_9: 57, + /** Colon (:) key. Requires Gecko 15.0 */ + VK_COLON: 58, + /** Semicolon (;) key. */ + VK_SEMICOLON: 59, + /** Less-than (<) key. Requires Gecko 15.0 */ + VK_LESS_THAN: 60, + /** Equals (=) key. */ + VK_EQUALS: 61, + /** Greater-than (>) key. Requires Gecko 15.0 */ + VK_GREATER_THAN: 62, + /** Question mark (?) key. Requires Gecko 15.0 */ + VK_QUESTION_MARK: 63, + /** Atmark (@) key. Requires Gecko 15.0 */ + VK_AT: 64, + /***/ + VK_A: 65, + /***/ + VK_B: 66, + /***/ + VK_C: 67, + /***/ + VK_D: 68, + /***/ + VK_E: 69, + /***/ + VK_F: 70, + /***/ + VK_G: 71, + /***/ + VK_H: 72, + /***/ + VK_I: 73, + /***/ + VK_J: 74, + /***/ + VK_K: 75, + /***/ + VK_L: 76, + /***/ + VK_M: 77, + /***/ + VK_N: 78, + /***/ + VK_O: 79, + /***/ + VK_P: 80, + /***/ + VK_Q: 81, + /***/ + VK_R: 82, + /***/ + VK_S: 83, + /***/ + VK_T: 84, + /***/ + VK_U: 85, + /***/ + VK_V: 86, + /***/ + VK_W: 87, + /***/ + VK_X: 88, + /***/ + VK_Y: 89, + /***/ + VK_Z: 90, + /***/ + VK_CONTEXT_MENU: 93, + /** 0 on the numeric keypad. */ + VK_NUMPAD0: 96, + /** 1 on the numeric keypad. */ + VK_NUMPAD1: 97, + /** 2 on the numeric keypad. */ + VK_NUMPAD2: 98, + /** 3 on the numeric keypad. */ + VK_NUMPAD3: 99, + /** 4 on the numeric keypad. */ + VK_NUMPAD4: 100, + /** 5 on the numeric keypad. */ + VK_NUMPAD5: 101, + /** 6 on the numeric keypad. */ + VK_NUMPAD6: 102, + /** 7 on the numeric keypad. */ + VK_NUMPAD7: 103, + /** 8 on the numeric keypad. */ + VK_NUMPAD8: 104, + /** 9 on the numeric keypad. */ + VK_NUMPAD9: 105, + /** * on the numeric keypad. */ + VK_MULTIPLY: 106, + /** + on the numeric keypad. */ + VK_ADD: 107, + /***/ + VK_SEPARATOR: 108, + /** - on the numeric keypad. */ + VK_SUBTRACT: 109, + /** Decimal point on the numeric keypad. */ + VK_DECIMAL: 110, + /** / on the numeric keypad. */ + VK_DIVIDE: 111, + /** F1 key. */ + VK_F1: 112, + /** F2 key. */ + VK_F2: 113, + /** F3 key. */ + VK_F3: 114, + /** F4 key. */ + VK_F4: 115, + /** F5 key. */ + VK_F5: 116, + /** F6 key. */ + VK_F6: 117, + /** F7 key. */ + VK_F7: 118, + /** F8 key. */ + VK_F8: 119, + /** F9 key. */ + VK_F9: 120, + /** F10 key. */ + VK_F10: 121, + /** F11 key. */ + VK_F11: 122, + /** F12 key. */ + VK_F12: 123, + /** F13 key. */ + VK_F13: 124, + /** F14 key. */ + VK_F14: 125, + /** F15 key. */ + VK_F15: 126, + /** F16 key. */ + VK_F16: 127, + /** F17 key. */ + VK_F17: 128, + /** F18 key. */ + VK_F18: 129, + /** F19 key. */ + VK_F19: 130, + /** F20 key. */ + VK_F20: 131, + /** F21 key. */ + VK_F21: 132, + /** F22 key. */ + VK_F22: 133, + /** F23 key. */ + VK_F23: 134, + /** F24 key. */ + VK_F24: 135, + /** Num Lock key. */ + VK_NUM_LOCK: 144, + /** Scroll Lock key. */ + VK_SCROLL_LOCK: 145, + /** Circumflex (^) key. Requires Gecko 15.0 */ + VK_CIRCUMFLEX: 160, + /** Exclamation (!) key. Requires Gecko 15.0 */ + VK_EXCLAMATION: 161, + /** Double quote () key. Requires Gecko 15.0 */ + VK_DOUBLE_QUOTE: 162, + /** Hash (#) key. Requires Gecko 15.0 */ + VK_HASH: 163, + /** Dollar sign ($) key. Requires Gecko 15.0 */ + VK_DOLLAR: 164, + /** Percent (%) key. Requires Gecko 15.0 */ + VK_PERCENT: 165, + /** Ampersand (&) key. Requires Gecko 15.0 */ + VK_AMPERSAND: 166, + /** Underscore (_) key. Requires Gecko 15.0 */ + VK_UNDERSCORE: 167, + /** Open parenthesis (() key. Requires Gecko 15.0 */ + VK_OPEN_PAREN: 168, + /** Close parenthesis ()) key. Requires Gecko 15.0 */ + VK_CLOSE_PAREN: 169, + /* Asterisk (*) key. Requires Gecko 15.0 */ + VK_ASTERISK: 170, + /** Plus (+) key. Requires Gecko 15.0 */ + VK_PLUS: 171, + /** Pipe (|) key. Requires Gecko 15.0 */ + VK_PIPE: 172, + /** Hyphen-US/docs/Minus (-) key. Requires Gecko 15.0 */ + VK_HYPHEN_MINUS: 173, + /** Open curly bracket ({) key. Requires Gecko 15.0 */ + VK_OPEN_CURLY_BRACKET: 174, + /** Close curly bracket (}) key. Requires Gecko 15.0 */ + VK_CLOSE_CURLY_BRACKET: 175, + /** Tilde (~) key. Requires Gecko 15.0 */ + VK_TILDE: 176, + /** Comma (,) key. */ + VK_COMMA: 188, + /** Period (.) key. */ + VK_PERIOD: 190, + /** Slash (/) key. */ + VK_SLASH: 191, + /** Back tick (`) key. */ + VK_BACK_QUOTE: 192, + /** Open square bracket ([) key. */ + VK_OPEN_BRACKET: 219, + /** Back slash (\) key. */ + VK_BACK_SLASH: 220, + /** Close square bracket (]) key. */ + VK_CLOSE_BRACKET: 221, + /** Quote (''') key. */ + VK_QUOTE: 222, + /** Meta key on Linux, Command key on Mac. */ + VK_META: 224, + /** AltGr key on Linux. Requires Gecko 15.0 */ + VK_ALTGR: 225, + /** Windows logo key on Windows. Or Super or Hyper key on Linux. Requires Gecko 15.0 */ + VK_WIN: 91, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANA: 21, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANGUL: 21, + /** 英数 key on Japanese Mac keyboard. Requires Gecko 15.0 */ + VK_EISU: 22, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_JUNJA: 23, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_FINAL: 24, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_HANJA: 25, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_KANJI: 25, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_CONVERT: 28, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_NONCONVERT: 29, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_ACCEPT: 30, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_MODECHANGE: 31, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SELECT: 41, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_PRINT: 42, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_EXECUTE: 43, + /** Linux support for this keycode was added in Gecko 4.0. */ + VK_SLEEP: 95 +}; diff --git a/lib/rotjs-library/src/scheduler.js b/lib/rotjs-library/src/scheduler.js new file mode 100644 index 0000000000000000000000000000000000000000..bd1a16aed60ba80c5a147ee8a1dd7cfcf691733b --- /dev/null +++ b/lib/rotjs-library/src/scheduler.js @@ -0,0 +1,73 @@ +/** + * @class Speed-based scheduler + */ +ROT.Scheduler = function() { + this._items = []; +} + +/** + * @param {object} item anything with "getSpeed" method + */ +ROT.Scheduler.prototype.add = function(item) { + var o = { + item: item, + bucket: 1/item.getSpeed() + } + this._items.push(o); + return this; +} + +/** + * Clear all actors + */ +ROT.Scheduler.prototype.clear = function() { + this._items = []; + return this; +} + +/** + * Remove a previously added item + * @param {object} item anything with "getSpeed" method + */ +ROT.Scheduler.prototype.remove = function(item) { + var it = null; + for (var i=0;i minItem.item.getSpeed()) { + minItem = item; + } + } + + if (minBucket) { /* non-zero value; subtract from all buckets */ + for (var i=0;iRogueBasin article. + * Offers configurable order and prior. + * @param {object} [options] + * @param {bool} [options.words=false] Use word mode? + * @param {int} [options.order=3] + * @param {float} [options.prior=0.001] + */ +ROT.StringGenerator = function(options) { + this._options = { + words: false, + order: 3, + prior: 0.001 + } + for (var p in options) { this._options[p] = options[p]; } + + this._boundary = String.fromCharCode(0); + this._suffix = this._boundary; + this._prefix = []; + for (var i=0;i this._options.order) { + context = context.slice(-this._options.order); + } else if (context.length < this._options.order) { + context = this._prefix.slice(0, this._options.order - context.length).concat(context); + } + + while (!(this._join(context) in this._data) && context.length > 0) { context = context.slice(1); } + + return context; +} + + +ROT.StringGenerator.prototype._pickRandom = function(data) { + var total = 0; + + for (var id in data) { + total += data[id]; + } + var random = ROT.RNG.getUniform()*total; + + var part = 0; + for (var id in data) { + part += data[id]; + if (random < part) { return id; } + } +} diff --git a/lib/rotjs-library/src/text.js b/lib/rotjs-library/src/text.js new file mode 100644 index 0000000000000000000000000000000000000000..7f81eb78fc9f413edc7f89e2945cb6c985868c44 --- /dev/null +++ b/lib/rotjs-library/src/text.js @@ -0,0 +1,194 @@ +/** + * @namespace + * Contains text tokenization and breaking routines + */ +ROT.Text = { + RE_COLORS: /%([bc]){([^}]*)}/g, + + /* token types */ + TYPE_TEXT: 0, + TYPE_NEWLINE: 1, + TYPE_FG: 2, + TYPE_BG: 3, + + /** + * Measure size of a resulting text block + */ + measure: function(str, maxWidth) { + var result = {width:0, height:1}; + var tokens = this.tokenize(str, maxWidth); + var lineWidth = 0; + + for (var i=0;i maxWidth) { /* line too long, find a suitable breaking spot */ + + /* is it possible to break within this token? */ + var index = -1; + while (1) { + var nextIndex = token.value.indexOf(" ", index+1); + if (nextIndex == -1) { break; } + if (lineLength + nextIndex > maxWidth) { break; } + index = nextIndex; + } + + if (index != -1) { /* break at space within this one */ + token.value = this._breakInsideToken(tokens, i, index, true); + } else if (lastTokenWithSpace != -1) { /* is there a previous token where a break can occur? */ + var token = tokens[lastTokenWithSpace]; + var breakIndex = token.value.lastIndexOf(" "); + token.value = this._breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true); + i = lastTokenWithSpace; + } else { /* force break in this token */ + token.value = this._breakInsideToken(tokens, i, maxWidth-lineLength, false); + } + + } else { /* line not long, continue */ + lineLength += token.value.length; + if (token.value.indexOf(" ") != -1) { lastTokenWithSpace = i; } + } + + i++; /* advance to next token */ + } + + + tokens.push({type: ROT.Text.TYPE_NEWLINE}); /* insert fake newline to fix the last text line */ + + /* remove trailing space from text tokens before newlines */ + var lastTextToken = null; + for (var i=0;i + + + + rot.js tests + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/rotjs-library/tests/lib/jasmine-1.2.0/MIT.LICENSE b/lib/rotjs-library/tests/lib/jasmine-1.2.0/MIT.LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7c435baaec86c0ebe2eb56b0550c11820c181b05 --- /dev/null +++ b/lib/rotjs-library/tests/lib/jasmine-1.2.0/MIT.LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2008-2011 Pivotal Labs + +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. diff --git a/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine-html.js b/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine-html.js new file mode 100644 index 0000000000000000000000000000000000000000..a0b06394ec4337b38d8e61d5dfda5819eb126400 --- /dev/null +++ b/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine-html.js @@ -0,0 +1,616 @@ +jasmine.HtmlReporterHelpers = {}; + +jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { + var el = document.createElement(type); + + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + + if (typeof child === 'string') { + el.appendChild(document.createTextNode(child)); + } else { + if (child) { + el.appendChild(child); + } + } + } + + for (var attr in attrs) { + if (attr == "className") { + el[attr] = attrs[attr]; + } else { + el.setAttribute(attr, attrs[attr]); + } + } + + return el; +}; + +jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { + var results = child.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.skipped) { + status = 'skipped'; + } + + return status; +}; + +jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { + var parentDiv = this.dom.summary; + var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; + var parent = child[parentSuite]; + + if (parent) { + if (typeof this.views.suites[parent.id] == 'undefined') { + this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); + } + parentDiv = this.views.suites[parent.id].element; + } + + parentDiv.appendChild(childElement); +}; + + +jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { + for(var fn in jasmine.HtmlReporterHelpers) { + ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; + } +}; + +jasmine.HtmlReporter = function(_doc) { + var self = this; + var doc = _doc || window.document; + + var reporterView; + + var dom = {}; + + // Jasmine Reporter Public Interface + self.logRunningSpecs = false; + + self.reportRunnerStarting = function(runner) { + var specs = runner.specs() || []; + + if (specs.length == 0) { + return; + } + + createReporterDom(runner.env.versionString()); + doc.body.appendChild(dom.reporter); + + reporterView = new jasmine.HtmlReporter.ReporterView(dom); + reporterView.addSpecs(specs, self.specFilter); + }; + + self.reportRunnerResults = function(runner) { + reporterView && reporterView.complete(); + }; + + self.reportSuiteResults = function(suite) { + reporterView.suiteComplete(suite); + }; + + self.reportSpecStarting = function(spec) { + if (self.logRunningSpecs) { + self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); + } + }; + + self.reportSpecResults = function(spec) { + reporterView.specComplete(spec); + }; + + self.log = function() { + var console = jasmine.getGlobal().console; + if (console && console.log) { + if (console.log.apply) { + console.log.apply(console, arguments); + } else { + console.log(arguments); // ie fix: console.log.apply doesn't exist on ie + } + } + }; + + self.specFilter = function(spec) { + if (!focusedSpecName()) { + return true; + } + + return spec.getFullName().indexOf(focusedSpecName()) === 0; + }; + + return self; + + function focusedSpecName() { + var specName; + + (function memoizeFocusedSpec() { + if (specName) { + return; + } + + var paramMap = []; + var params = doc.location.search.substring(1).split('&'); + + for (var i = 0; i < params.length; i++) { + var p = params[i].split('='); + paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); + } + + specName = paramMap.spec; + })(); + + return specName; + } + + function createReporterDom(version) { + dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, + dom.banner = self.createDom('div', { className: 'banner' }, + self.createDom('span', { className: 'title' }, "Jasmine "), + self.createDom('span', { className: 'version' }, version)), + + dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), + dom.alert = self.createDom('div', {className: 'alert'}), + dom.results = self.createDom('div', {className: 'results'}, + dom.summary = self.createDom('div', { className: 'summary' }), + dom.details = self.createDom('div', { id: 'details' })) + ); + } +}; +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);jasmine.HtmlReporter.ReporterView = function(dom) { + this.startedAt = new Date(); + this.runningSpecCount = 0; + this.completeSpecCount = 0; + this.passedCount = 0; + this.failedCount = 0; + this.skippedCount = 0; + + this.createResultsMenu = function() { + this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, + this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), + ' | ', + this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); + + this.summaryMenuItem.onclick = function() { + dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); + }; + + this.detailsMenuItem.onclick = function() { + showDetails(); + }; + }; + + this.addSpecs = function(specs, specFilter) { + this.totalSpecCount = specs.length; + + this.views = { + specs: {}, + suites: {} + }; + + for (var i = 0; i < specs.length; i++) { + var spec = specs[i]; + this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); + if (specFilter(spec)) { + this.runningSpecCount++; + } + } + }; + + this.specComplete = function(spec) { + this.completeSpecCount++; + + if (isUndefined(this.views.specs[spec.id])) { + this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); + } + + var specView = this.views.specs[spec.id]; + + switch (specView.status()) { + case 'passed': + this.passedCount++; + break; + + case 'failed': + this.failedCount++; + break; + + case 'skipped': + this.skippedCount++; + break; + } + + specView.refresh(); + this.refresh(); + }; + + this.suiteComplete = function(suite) { + var suiteView = this.views.suites[suite.id]; + if (isUndefined(suiteView)) { + return; + } + suiteView.refresh(); + }; + + this.refresh = function() { + + if (isUndefined(this.resultsMenu)) { + this.createResultsMenu(); + } + + // currently running UI + if (isUndefined(this.runningAlert)) { + this.runningAlert = this.createDom('a', {href: "?", className: "runningAlert bar"}); + dom.alert.appendChild(this.runningAlert); + } + this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); + + // skipped specs UI + if (isUndefined(this.skippedAlert)) { + this.skippedAlert = this.createDom('a', {href: "?", className: "skippedAlert bar"}); + } + + this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; + + if (this.skippedCount === 1 && isDefined(dom.alert)) { + dom.alert.appendChild(this.skippedAlert); + } + + // passing specs UI + if (isUndefined(this.passedAlert)) { + this.passedAlert = this.createDom('span', {href: "?", className: "passingAlert bar"}); + } + this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); + + // failing specs UI + if (isUndefined(this.failedAlert)) { + this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); + } + this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); + + if (this.failedCount === 1 && isDefined(dom.alert)) { + dom.alert.appendChild(this.failedAlert); + dom.alert.appendChild(this.resultsMenu); + } + + // summary info + this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); + this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; + }; + + this.complete = function() { + dom.alert.removeChild(this.runningAlert); + + this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; + + if (this.failedCount === 0) { + dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); + } else { + showDetails(); + } + + dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); + }; + + return this; + + function showDetails() { + if (dom.reporter.className.search(/showDetails/) === -1) { + dom.reporter.className += " showDetails"; + } + } + + function isUndefined(obj) { + return typeof obj === 'undefined'; + } + + function isDefined(obj) { + return !isUndefined(obj); + } + + function specPluralizedFor(count) { + var str = count + " spec"; + if (count > 1) { + str += "s" + } + return str; + } + +}; + +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); + + +jasmine.HtmlReporter.SpecView = function(spec, dom, views) { + this.spec = spec; + this.dom = dom; + this.views = views; + + this.symbol = this.createDom('li', { className: 'pending' }); + this.dom.symbolSummary.appendChild(this.symbol); + + this.summary = this.createDom('div', { className: 'specSummary' }, + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(this.spec.getFullName()), + title: this.spec.getFullName() + }, this.spec.description) + ); + + this.detail = this.createDom('div', { className: 'specDetail' }, + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(this.spec.getFullName()), + title: this.spec.getFullName() + }, this.spec.getFullName()) + ); +}; + +jasmine.HtmlReporter.SpecView.prototype.status = function() { + return this.getSpecStatus(this.spec); +}; + +jasmine.HtmlReporter.SpecView.prototype.refresh = function() { + this.symbol.className = this.status(); + + switch (this.status()) { + case 'skipped': + break; + + case 'passed': + this.appendSummaryToSuiteDiv(); + break; + + case 'failed': + this.appendSummaryToSuiteDiv(); + this.appendFailureDetail(); + break; + } +}; + +jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { + this.summary.className += ' ' + this.status(); + this.appendToSummary(this.spec, this.summary); +}; + +jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { + this.detail.className += ' ' + this.status(); + + var resultItems = this.spec.results().getItems(); + var messagesDiv = this.createDom('div', { className: 'messages' }); + + for (var i = 0; i < resultItems.length; i++) { + var result = resultItems[i]; + + if (result.type == 'log') { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); + } else if (result.type == 'expect' && result.passed && !result.passed()) { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); + + if (result.trace.stack) { + messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); + } + } + } + + if (messagesDiv.childNodes.length > 0) { + this.detail.appendChild(messagesDiv); + this.dom.details.appendChild(this.detail); + } +}; + +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { + this.suite = suite; + this.dom = dom; + this.views = views; + + this.element = this.createDom('div', { className: 'suite' }, + this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description) + ); + + this.appendToSummary(this.suite, this.element); +}; + +jasmine.HtmlReporter.SuiteView.prototype.status = function() { + return this.getSpecStatus(this.suite); +}; + +jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { + this.element.className += " " + this.status(); +}; + +jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); + +/* @deprecated Use jasmine.HtmlReporter instead + */ +jasmine.TrivialReporter = function(doc) { + this.document = doc || document; + this.suiteDivs = {}; + this.logRunningSpecs = false; +}; + +jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { + var el = document.createElement(type); + + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + + if (typeof child === 'string') { + el.appendChild(document.createTextNode(child)); + } else { + if (child) { el.appendChild(child); } + } + } + + for (var attr in attrs) { + if (attr == "className") { + el[attr] = attrs[attr]; + } else { + el.setAttribute(attr, attrs[attr]); + } + } + + return el; +}; + +jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { + var showPassed, showSkipped; + + this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, + this.createDom('div', { className: 'banner' }, + this.createDom('div', { className: 'logo' }, + this.createDom('span', { className: 'title' }, "Jasmine"), + this.createDom('span', { className: 'version' }, runner.env.versionString())), + this.createDom('div', { className: 'options' }, + "Show ", + showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), + this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), + showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), + this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") + ) + ), + + this.runnerDiv = this.createDom('div', { className: 'runner running' }, + this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), + this.runnerMessageSpan = this.createDom('span', {}, "Running..."), + this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) + ); + + this.document.body.appendChild(this.outerDiv); + + var suites = runner.suites(); + for (var i = 0; i < suites.length; i++) { + var suite = suites[i]; + var suiteDiv = this.createDom('div', { className: 'suite' }, + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), + this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); + this.suiteDivs[suite.id] = suiteDiv; + var parentDiv = this.outerDiv; + if (suite.parentSuite) { + parentDiv = this.suiteDivs[suite.parentSuite.id]; + } + parentDiv.appendChild(suiteDiv); + } + + this.startedAt = new Date(); + + var self = this; + showPassed.onclick = function(evt) { + if (showPassed.checked) { + self.outerDiv.className += ' show-passed'; + } else { + self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); + } + }; + + showSkipped.onclick = function(evt) { + if (showSkipped.checked) { + self.outerDiv.className += ' show-skipped'; + } else { + self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); + } + }; +}; + +jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { + var results = runner.results(); + var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; + this.runnerDiv.setAttribute("class", className); + //do it twice for IE + this.runnerDiv.setAttribute("className", className); + var specs = runner.specs(); + var specCount = 0; + for (var i = 0; i < specs.length; i++) { + if (this.specFilter(specs[i])) { + specCount++; + } + } + var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); + message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; + this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); + + this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); +}; + +jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { + var results = suite.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.totalCount === 0) { // todo: change this to check results.skipped + status = 'skipped'; + } + this.suiteDivs[suite.id].className += " " + status; +}; + +jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { + if (this.logRunningSpecs) { + this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); + } +}; + +jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { + var results = spec.results(); + var status = results.passed() ? 'passed' : 'failed'; + if (results.skipped) { + status = 'skipped'; + } + var specDiv = this.createDom('div', { className: 'spec ' + status }, + this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), + this.createDom('a', { + className: 'description', + href: '?spec=' + encodeURIComponent(spec.getFullName()), + title: spec.getFullName() + }, spec.description)); + + + var resultItems = results.getItems(); + var messagesDiv = this.createDom('div', { className: 'messages' }); + for (var i = 0; i < resultItems.length; i++) { + var result = resultItems[i]; + + if (result.type == 'log') { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); + } else if (result.type == 'expect' && result.passed && !result.passed()) { + messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); + + if (result.trace.stack) { + messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); + } + } + } + + if (messagesDiv.childNodes.length > 0) { + specDiv.appendChild(messagesDiv); + } + + this.suiteDivs[spec.suite.id].appendChild(specDiv); +}; + +jasmine.TrivialReporter.prototype.log = function() { + var console = jasmine.getGlobal().console; + if (console && console.log) { + if (console.log.apply) { + console.log.apply(console, arguments); + } else { + console.log(arguments); // ie fix: console.log.apply doesn't exist on ie + } + } +}; + +jasmine.TrivialReporter.prototype.getLocation = function() { + return this.document.location; +}; + +jasmine.TrivialReporter.prototype.specFilter = function(spec) { + var paramMap = {}; + var params = this.getLocation().search.substring(1).split('&'); + for (var i = 0; i < params.length; i++) { + var p = params[i].split('='); + paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); + } + + if (!paramMap.spec) { + return true; + } + return spec.getFullName().indexOf(paramMap.spec) === 0; +}; diff --git a/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine.css b/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine.css new file mode 100644 index 0000000000000000000000000000000000000000..826e575310cd8e5ebc747192f47ff2e88e14fb4d --- /dev/null +++ b/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine.css @@ -0,0 +1,81 @@ +body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } + +#HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } +#HTMLReporter a { text-decoration: none; } +#HTMLReporter a:hover { text-decoration: underline; } +#HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; } +#HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; } +#HTMLReporter #jasmine_content { position: fixed; right: 100%; } +#HTMLReporter .version { color: #aaaaaa; } +#HTMLReporter .banner { margin-top: 14px; } +#HTMLReporter .duration { color: #aaaaaa; float: right; } +#HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; } +#HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; } +#HTMLReporter .symbolSummary li.passed { font-size: 14px; } +#HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; } +#HTMLReporter .symbolSummary li.failed { line-height: 9px; } +#HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } +#HTMLReporter .symbolSummary li.skipped { font-size: 14px; } +#HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; } +#HTMLReporter .symbolSummary li.pending { line-height: 11px; } +#HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; } +#HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } +#HTMLReporter .runningAlert { background-color: #666666; } +#HTMLReporter .skippedAlert { background-color: #aaaaaa; } +#HTMLReporter .skippedAlert:first-child { background-color: #333333; } +#HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; } +#HTMLReporter .passingAlert { background-color: #a6b779; } +#HTMLReporter .passingAlert:first-child { background-color: #5e7d00; } +#HTMLReporter .failingAlert { background-color: #cf867e; } +#HTMLReporter .failingAlert:first-child { background-color: #b03911; } +#HTMLReporter .results { margin-top: 14px; } +#HTMLReporter #details { display: none; } +#HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; } +#HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } +#HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } +#HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } +#HTMLReporter.showDetails .summary { display: none; } +#HTMLReporter.showDetails #details { display: block; } +#HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } +#HTMLReporter .summary { margin-top: 14px; } +#HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; } +#HTMLReporter .summary .specSummary.passed a { color: #5e7d00; } +#HTMLReporter .summary .specSummary.failed a { color: #b03911; } +#HTMLReporter .description + .suite { margin-top: 0; } +#HTMLReporter .suite { margin-top: 14px; } +#HTMLReporter .suite a { color: #333333; } +#HTMLReporter #details .specDetail { margin-bottom: 28px; } +#HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; } +#HTMLReporter .resultMessage { padding-top: 14px; color: #333333; } +#HTMLReporter .resultMessage span.result { display: block; } +#HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } + +#TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ } +#TrivialReporter a:visited, #TrivialReporter a { color: #303; } +#TrivialReporter a:hover, #TrivialReporter a:active { color: blue; } +#TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; } +#TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; } +#TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; } +#TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; } +#TrivialReporter .runner.running { background-color: yellow; } +#TrivialReporter .options { text-align: right; font-size: .8em; } +#TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; } +#TrivialReporter .suite .suite { margin: 5px; } +#TrivialReporter .suite.passed { background-color: #dfd; } +#TrivialReporter .suite.failed { background-color: #fdd; } +#TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; } +#TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; } +#TrivialReporter .spec.failed { background-color: #fbb; border-color: red; } +#TrivialReporter .spec.passed { background-color: #bfb; border-color: green; } +#TrivialReporter .spec.skipped { background-color: #bbb; } +#TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; } +#TrivialReporter .passed { background-color: #cfc; display: none; } +#TrivialReporter .failed { background-color: #fbb; } +#TrivialReporter .skipped { color: #777; background-color: #eee; display: none; } +#TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; } +#TrivialReporter .resultMessage .mismatch { color: black; } +#TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; } +#TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; } +#TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; } +#TrivialReporter #jasmine_content { position: fixed; right: 100%; } +#TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; } diff --git a/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine.js b/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine.js new file mode 100644 index 0000000000000000000000000000000000000000..03bf89a0c4107414605c0aa24929ced18854bcf7 --- /dev/null +++ b/lib/rotjs-library/tests/lib/jasmine-1.2.0/jasmine.js @@ -0,0 +1,2529 @@ +var isCommonJS = typeof window == "undefined"; + +/** + * Top level namespace for Jasmine, a lightweight JavaScript BDD/spec/testing framework. + * + * @namespace + */ +var jasmine = {}; +if (isCommonJS) exports.jasmine = jasmine; +/** + * @private + */ +jasmine.unimplementedMethod_ = function() { + throw new Error("unimplemented method"); +}; + +/** + * Use jasmine.undefined instead of undefined, since undefined is just + * a plain old variable and may be redefined by somebody else. + * + * @private + */ +jasmine.undefined = jasmine.___undefined___; + +/** + * Show diagnostic messages in the console if set to true + * + */ +jasmine.VERBOSE = false; + +/** + * Default interval in milliseconds for event loop yields (e.g. to allow network activity or to refresh the screen with the HTML-based runner). Small values here may result in slow test running. Zero means no updates until all tests have completed. + * + */ +jasmine.DEFAULT_UPDATE_INTERVAL = 250; + +/** + * Default timeout interval in milliseconds for waitsFor() blocks. + */ +jasmine.DEFAULT_TIMEOUT_INTERVAL = 5000; + +jasmine.getGlobal = function() { + function getGlobal() { + return this; + } + + return getGlobal(); +}; + +/** + * Allows for bound functions to be compared. Internal use only. + * + * @ignore + * @private + * @param base {Object} bound 'this' for the function + * @param name {Function} function to find + */ +jasmine.bindOriginal_ = function(base, name) { + var original = base[name]; + if (original.apply) { + return function() { + return original.apply(base, arguments); + }; + } else { + // IE support + return jasmine.getGlobal()[name]; + } +}; + +jasmine.setTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'setTimeout'); +jasmine.clearTimeout = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearTimeout'); +jasmine.setInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'setInterval'); +jasmine.clearInterval = jasmine.bindOriginal_(jasmine.getGlobal(), 'clearInterval'); + +jasmine.MessageResult = function(values) { + this.type = 'log'; + this.values = values; + this.trace = new Error(); // todo: test better +}; + +jasmine.MessageResult.prototype.toString = function() { + var text = ""; + for (var i = 0; i < this.values.length; i++) { + if (i > 0) text += " "; + if (jasmine.isString_(this.values[i])) { + text += this.values[i]; + } else { + text += jasmine.pp(this.values[i]); + } + } + return text; +}; + +jasmine.ExpectationResult = function(params) { + this.type = 'expect'; + this.matcherName = params.matcherName; + this.passed_ = params.passed; + this.expected = params.expected; + this.actual = params.actual; + this.message = this.passed_ ? 'Passed.' : params.message; + + var trace = (params.trace || new Error(this.message)); + this.trace = this.passed_ ? '' : trace; +}; + +jasmine.ExpectationResult.prototype.toString = function () { + return this.message; +}; + +jasmine.ExpectationResult.prototype.passed = function () { + return this.passed_; +}; + +/** + * Getter for the Jasmine environment. Ensures one gets created + */ +jasmine.getEnv = function() { + var env = jasmine.currentEnv_ = jasmine.currentEnv_ || new jasmine.Env(); + return env; +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isArray_ = function(value) { + return jasmine.isA_("Array", value); +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isString_ = function(value) { + return jasmine.isA_("String", value); +}; + +/** + * @ignore + * @private + * @param value + * @returns {Boolean} + */ +jasmine.isNumber_ = function(value) { + return jasmine.isA_("Number", value); +}; + +/** + * @ignore + * @private + * @param {String} typeName + * @param value + * @returns {Boolean} + */ +jasmine.isA_ = function(typeName, value) { + return Object.prototype.toString.apply(value) === '[object ' + typeName + ']'; +}; + +/** + * Pretty printer for expecations. Takes any object and turns it into a human-readable string. + * + * @param value {Object} an object to be outputted + * @returns {String} + */ +jasmine.pp = function(value) { + var stringPrettyPrinter = new jasmine.StringPrettyPrinter(); + stringPrettyPrinter.format(value); + return stringPrettyPrinter.string; +}; + +/** + * Returns true if the object is a DOM Node. + * + * @param {Object} obj object to check + * @returns {Boolean} + */ +jasmine.isDomNode = function(obj) { + return obj.nodeType > 0; +}; + +/** + * Returns a matchable 'generic' object of the class type. For use in expecations of type when values don't matter. + * + * @example + * // don't care about which function is passed in, as long as it's a function + * expect(mySpy).toHaveBeenCalledWith(jasmine.any(Function)); + * + * @param {Class} clazz + * @returns matchable object of the type clazz + */ +jasmine.any = function(clazz) { + return new jasmine.Matchers.Any(clazz); +}; + +/** + * Returns a matchable subset of a JSON object. For use in expectations when you don't care about all of the + * attributes on the object. + * + * @example + * // don't care about any other attributes than foo. + * expect(mySpy).toHaveBeenCalledWith(jasmine.objectContaining({foo: "bar"}); + * + * @param sample {Object} sample + * @returns matchable object for the sample + */ +jasmine.objectContaining = function (sample) { + return new jasmine.Matchers.ObjectContaining(sample); +}; + +/** + * Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks. + * + * Spies should be created in test setup, before expectations. They can then be checked, using the standard Jasmine + * expectation syntax. Spies can be checked if they were called or not and what the calling params were. + * + * A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). + * + * Spies are torn down at the end of every spec. + * + * Note: Do not call new jasmine.Spy() directly - a spy must be created using spyOn, jasmine.createSpy or jasmine.createSpyObj. + * + * @example + * // a stub + * var myStub = jasmine.createSpy('myStub'); // can be used anywhere + * + * // spy example + * var foo = { + * not: function(bool) { return !bool; } + * } + * + * // actual foo.not will not be called, execution stops + * spyOn(foo, 'not'); + + // foo.not spied upon, execution will continue to implementation + * spyOn(foo, 'not').andCallThrough(); + * + * // fake example + * var foo = { + * not: function(bool) { return !bool; } + * } + * + * // foo.not(val) will return val + * spyOn(foo, 'not').andCallFake(function(value) {return value;}); + * + * // mock example + * foo.not(7 == 7); + * expect(foo.not).toHaveBeenCalled(); + * expect(foo.not).toHaveBeenCalledWith(true); + * + * @constructor + * @see spyOn, jasmine.createSpy, jasmine.createSpyObj + * @param {String} name + */ +jasmine.Spy = function(name) { + /** + * The name of the spy, if provided. + */ + this.identity = name || 'unknown'; + /** + * Is this Object a spy? + */ + this.isSpy = true; + /** + * The actual function this spy stubs. + */ + this.plan = function() { + }; + /** + * Tracking of the most recent call to the spy. + * @example + * var mySpy = jasmine.createSpy('foo'); + * mySpy(1, 2); + * mySpy.mostRecentCall.args = [1, 2]; + */ + this.mostRecentCall = {}; + + /** + * Holds arguments for each call to the spy, indexed by call count + * @example + * var mySpy = jasmine.createSpy('foo'); + * mySpy(1, 2); + * mySpy(7, 8); + * mySpy.mostRecentCall.args = [7, 8]; + * mySpy.argsForCall[0] = [1, 2]; + * mySpy.argsForCall[1] = [7, 8]; + */ + this.argsForCall = []; + this.calls = []; +}; + +/** + * Tells a spy to call through to the actual implemenatation. + * + * @example + * var foo = { + * bar: function() { // do some stuff } + * } + * + * // defining a spy on an existing property: foo.bar + * spyOn(foo, 'bar').andCallThrough(); + */ +jasmine.Spy.prototype.andCallThrough = function() { + this.plan = this.originalValue; + return this; +}; + +/** + * For setting the return value of a spy. + * + * @example + * // defining a spy from scratch: foo() returns 'baz' + * var foo = jasmine.createSpy('spy on foo').andReturn('baz'); + * + * // defining a spy on an existing property: foo.bar() returns 'baz' + * spyOn(foo, 'bar').andReturn('baz'); + * + * @param {Object} value + */ +jasmine.Spy.prototype.andReturn = function(value) { + this.plan = function() { + return value; + }; + return this; +}; + +/** + * For throwing an exception when a spy is called. + * + * @example + * // defining a spy from scratch: foo() throws an exception w/ message 'ouch' + * var foo = jasmine.createSpy('spy on foo').andThrow('baz'); + * + * // defining a spy on an existing property: foo.bar() throws an exception w/ message 'ouch' + * spyOn(foo, 'bar').andThrow('baz'); + * + * @param {String} exceptionMsg + */ +jasmine.Spy.prototype.andThrow = function(exceptionMsg) { + this.plan = function() { + throw exceptionMsg; + }; + return this; +}; + +/** + * Calls an alternate implementation when a spy is called. + * + * @example + * var baz = function() { + * // do some stuff, return something + * } + * // defining a spy from scratch: foo() calls the function baz + * var foo = jasmine.createSpy('spy on foo').andCall(baz); + * + * // defining a spy on an existing property: foo.bar() calls an anonymnous function + * spyOn(foo, 'bar').andCall(function() { return 'baz';} ); + * + * @param {Function} fakeFunc + */ +jasmine.Spy.prototype.andCallFake = function(fakeFunc) { + this.plan = fakeFunc; + return this; +}; + +/** + * Resets all of a spy's the tracking variables so that it can be used again. + * + * @example + * spyOn(foo, 'bar'); + * + * foo.bar(); + * + * expect(foo.bar.callCount).toEqual(1); + * + * foo.bar.reset(); + * + * expect(foo.bar.callCount).toEqual(0); + */ +jasmine.Spy.prototype.reset = function() { + this.wasCalled = false; + this.callCount = 0; + this.argsForCall = []; + this.calls = []; + this.mostRecentCall = {}; +}; + +jasmine.createSpy = function(name) { + + var spyObj = function() { + spyObj.wasCalled = true; + spyObj.callCount++; + var args = jasmine.util.argsToArray(arguments); + spyObj.mostRecentCall.object = this; + spyObj.mostRecentCall.args = args; + spyObj.argsForCall.push(args); + spyObj.calls.push({object: this, args: args}); + return spyObj.plan.apply(this, arguments); + }; + + var spy = new jasmine.Spy(name); + + for (var prop in spy) { + spyObj[prop] = spy[prop]; + } + + spyObj.reset(); + + return spyObj; +}; + +/** + * Determines whether an object is a spy. + * + * @param {jasmine.Spy|Object} putativeSpy + * @returns {Boolean} + */ +jasmine.isSpy = function(putativeSpy) { + return putativeSpy && putativeSpy.isSpy; +}; + +/** + * Creates a more complicated spy: an Object that has every property a function that is a spy. Used for stubbing something + * large in one call. + * + * @param {String} baseName name of spy class + * @param {Array} methodNames array of names of methods to make spies + */ +jasmine.createSpyObj = function(baseName, methodNames) { + if (!jasmine.isArray_(methodNames) || methodNames.length === 0) { + throw new Error('createSpyObj requires a non-empty array of method names to create spies for'); + } + var obj = {}; + for (var i = 0; i < methodNames.length; i++) { + obj[methodNames[i]] = jasmine.createSpy(baseName + '.' + methodNames[i]); + } + return obj; +}; + +/** + * All parameters are pretty-printed and concatenated together, then written to the current spec's output. + * + * Be careful not to leave calls to jasmine.log in production code. + */ +jasmine.log = function() { + var spec = jasmine.getEnv().currentSpec; + spec.log.apply(spec, arguments); +}; + +/** + * Function that installs a spy on an existing object's method name. Used within a Spec to create a spy. + * + * @example + * // spy example + * var foo = { + * not: function(bool) { return !bool; } + * } + * spyOn(foo, 'not'); // actual foo.not will not be called, execution stops + * + * @see jasmine.createSpy + * @param obj + * @param methodName + * @returns a Jasmine spy that can be chained with all spy methods + */ +var spyOn = function(obj, methodName) { + return jasmine.getEnv().currentSpec.spyOn(obj, methodName); +}; +if (isCommonJS) exports.spyOn = spyOn; + +/** + * Creates a Jasmine spec that will be added to the current suite. + * + * // TODO: pending tests + * + * @example + * it('should be true', function() { + * expect(true).toEqual(true); + * }); + * + * @param {String} desc description of this specification + * @param {Function} func defines the preconditions and expectations of the spec + */ +var it = function(desc, func) { + return jasmine.getEnv().it(desc, func); +}; +if (isCommonJS) exports.it = it; + +/** + * Creates a disabled Jasmine spec. + * + * A convenience method that allows existing specs to be disabled temporarily during development. + * + * @param {String} desc description of this specification + * @param {Function} func defines the preconditions and expectations of the spec + */ +var xit = function(desc, func) { + return jasmine.getEnv().xit(desc, func); +}; +if (isCommonJS) exports.xit = xit; + +/** + * Starts a chain for a Jasmine expectation. + * + * It is passed an Object that is the actual value and should chain to one of the many + * jasmine.Matchers functions. + * + * @param {Object} actual Actual value to test against and expected value + */ +var expect = function(actual) { + return jasmine.getEnv().currentSpec.expect(actual); +}; +if (isCommonJS) exports.expect = expect; + +/** + * Defines part of a jasmine spec. Used in cominbination with waits or waitsFor in asynchrnous specs. + * + * @param {Function} func Function that defines part of a jasmine spec. + */ +var runs = function(func) { + jasmine.getEnv().currentSpec.runs(func); +}; +if (isCommonJS) exports.runs = runs; + +/** + * Waits a fixed time period before moving to the next block. + * + * @deprecated Use waitsFor() instead + * @param {Number} timeout milliseconds to wait + */ +var waits = function(timeout) { + jasmine.getEnv().currentSpec.waits(timeout); +}; +if (isCommonJS) exports.waits = waits; + +/** + * Waits for the latchFunction to return true before proceeding to the next block. + * + * @param {Function} latchFunction + * @param {String} optional_timeoutMessage + * @param {Number} optional_timeout + */ +var waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { + jasmine.getEnv().currentSpec.waitsFor.apply(jasmine.getEnv().currentSpec, arguments); +}; +if (isCommonJS) exports.waitsFor = waitsFor; + +/** + * A function that is called before each spec in a suite. + * + * Used for spec setup, including validating assumptions. + * + * @param {Function} beforeEachFunction + */ +var beforeEach = function(beforeEachFunction) { + jasmine.getEnv().beforeEach(beforeEachFunction); +}; +if (isCommonJS) exports.beforeEach = beforeEach; + +/** + * A function that is called after each spec in a suite. + * + * Used for restoring any state that is hijacked during spec execution. + * + * @param {Function} afterEachFunction + */ +var afterEach = function(afterEachFunction) { + jasmine.getEnv().afterEach(afterEachFunction); +}; +if (isCommonJS) exports.afterEach = afterEach; + +/** + * Defines a suite of specifications. + * + * Stores the description and all defined specs in the Jasmine environment as one suite of specs. Variables declared + * are accessible by calls to beforeEach, it, and afterEach. Describe blocks can be nested, allowing for specialization + * of setup in some tests. + * + * @example + * // TODO: a simple suite + * + * // TODO: a simple suite with a nested describe block + * + * @param {String} description A string, usually the class under test. + * @param {Function} specDefinitions function that defines several specs. + */ +var describe = function(description, specDefinitions) { + return jasmine.getEnv().describe(description, specDefinitions); +}; +if (isCommonJS) exports.describe = describe; + +/** + * Disables a suite of specifications. Used to disable some suites in a file, or files, temporarily during development. + * + * @param {String} description A string, usually the class under test. + * @param {Function} specDefinitions function that defines several specs. + */ +var xdescribe = function(description, specDefinitions) { + return jasmine.getEnv().xdescribe(description, specDefinitions); +}; +if (isCommonJS) exports.xdescribe = xdescribe; + + +// Provide the XMLHttpRequest class for IE 5.x-6.x: +jasmine.XmlHttpRequest = (typeof XMLHttpRequest == "undefined") ? function() { + function tryIt(f) { + try { + return f(); + } catch(e) { + } + return null; + } + + var xhr = tryIt(function() { + return new ActiveXObject("Msxml2.XMLHTTP.6.0"); + }) || + tryIt(function() { + return new ActiveXObject("Msxml2.XMLHTTP.3.0"); + }) || + tryIt(function() { + return new ActiveXObject("Msxml2.XMLHTTP"); + }) || + tryIt(function() { + return new ActiveXObject("Microsoft.XMLHTTP"); + }); + + if (!xhr) throw new Error("This browser does not support XMLHttpRequest."); + + return xhr; +} : XMLHttpRequest; +/** + * @namespace + */ +jasmine.util = {}; + +/** + * Declare that a child class inherit it's prototype from the parent class. + * + * @private + * @param {Function} childClass + * @param {Function} parentClass + */ +jasmine.util.inherit = function(childClass, parentClass) { + /** + * @private + */ + var subclass = function() { + }; + subclass.prototype = parentClass.prototype; + childClass.prototype = new subclass(); +}; + +jasmine.util.formatException = function(e) { + var lineNumber; + if (e.line) { + lineNumber = e.line; + } + else if (e.lineNumber) { + lineNumber = e.lineNumber; + } + + var file; + + if (e.sourceURL) { + file = e.sourceURL; + } + else if (e.fileName) { + file = e.fileName; + } + + var message = (e.name && e.message) ? (e.name + ': ' + e.message) : e.toString(); + + if (file && lineNumber) { + message += ' in ' + file + ' (line ' + lineNumber + ')'; + } + + return message; +}; + +jasmine.util.htmlEscape = function(str) { + if (!str) return str; + return str.replace(/&/g, '&') + .replace(//g, '>'); +}; + +jasmine.util.argsToArray = function(args) { + var arrayOfArgs = []; + for (var i = 0; i < args.length; i++) arrayOfArgs.push(args[i]); + return arrayOfArgs; +}; + +jasmine.util.extend = function(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; +}; + +/** + * Environment for Jasmine + * + * @constructor + */ +jasmine.Env = function() { + this.currentSpec = null; + this.currentSuite = null; + this.currentRunner_ = new jasmine.Runner(this); + + this.reporter = new jasmine.MultiReporter(); + + this.updateInterval = jasmine.DEFAULT_UPDATE_INTERVAL; + this.defaultTimeoutInterval = jasmine.DEFAULT_TIMEOUT_INTERVAL; + this.lastUpdate = 0; + this.specFilter = function() { + return true; + }; + + this.nextSpecId_ = 0; + this.nextSuiteId_ = 0; + this.equalityTesters_ = []; + + // wrap matchers + this.matchersClass = function() { + jasmine.Matchers.apply(this, arguments); + }; + jasmine.util.inherit(this.matchersClass, jasmine.Matchers); + + jasmine.Matchers.wrapInto_(jasmine.Matchers.prototype, this.matchersClass); +}; + + +jasmine.Env.prototype.setTimeout = jasmine.setTimeout; +jasmine.Env.prototype.clearTimeout = jasmine.clearTimeout; +jasmine.Env.prototype.setInterval = jasmine.setInterval; +jasmine.Env.prototype.clearInterval = jasmine.clearInterval; + +/** + * @returns an object containing jasmine version build info, if set. + */ +jasmine.Env.prototype.version = function () { + if (jasmine.version_) { + return jasmine.version_; + } else { + throw new Error('Version not set'); + } +}; + +/** + * @returns string containing jasmine version build info, if set. + */ +jasmine.Env.prototype.versionString = function() { + if (!jasmine.version_) { + return "version unknown"; + } + + var version = this.version(); + var versionString = version.major + "." + version.minor + "." + version.build; + if (version.release_candidate) { + versionString += ".rc" + version.release_candidate; + } + versionString += " revision " + version.revision; + return versionString; +}; + +/** + * @returns a sequential integer starting at 0 + */ +jasmine.Env.prototype.nextSpecId = function () { + return this.nextSpecId_++; +}; + +/** + * @returns a sequential integer starting at 0 + */ +jasmine.Env.prototype.nextSuiteId = function () { + return this.nextSuiteId_++; +}; + +/** + * Register a reporter to receive status updates from Jasmine. + * @param {jasmine.Reporter} reporter An object which will receive status updates. + */ +jasmine.Env.prototype.addReporter = function(reporter) { + this.reporter.addReporter(reporter); +}; + +jasmine.Env.prototype.execute = function() { + this.currentRunner_.execute(); +}; + +jasmine.Env.prototype.describe = function(description, specDefinitions) { + var suite = new jasmine.Suite(this, description, specDefinitions, this.currentSuite); + + var parentSuite = this.currentSuite; + if (parentSuite) { + parentSuite.add(suite); + } else { + this.currentRunner_.add(suite); + } + + this.currentSuite = suite; + + var declarationError = null; + try { + specDefinitions.call(suite); + } catch(e) { + declarationError = e; + } + + if (declarationError) { + this.it("encountered a declaration exception", function() { + throw declarationError; + }); + } + + this.currentSuite = parentSuite; + + return suite; +}; + +jasmine.Env.prototype.beforeEach = function(beforeEachFunction) { + if (this.currentSuite) { + this.currentSuite.beforeEach(beforeEachFunction); + } else { + this.currentRunner_.beforeEach(beforeEachFunction); + } +}; + +jasmine.Env.prototype.currentRunner = function () { + return this.currentRunner_; +}; + +jasmine.Env.prototype.afterEach = function(afterEachFunction) { + if (this.currentSuite) { + this.currentSuite.afterEach(afterEachFunction); + } else { + this.currentRunner_.afterEach(afterEachFunction); + } + +}; + +jasmine.Env.prototype.xdescribe = function(desc, specDefinitions) { + return { + execute: function() { + } + }; +}; + +jasmine.Env.prototype.it = function(description, func) { + var spec = new jasmine.Spec(this, this.currentSuite, description); + this.currentSuite.add(spec); + this.currentSpec = spec; + + if (func) { + spec.runs(func); + } + + return spec; +}; + +jasmine.Env.prototype.xit = function(desc, func) { + return { + id: this.nextSpecId(), + runs: function() { + } + }; +}; + +jasmine.Env.prototype.compareObjects_ = function(a, b, mismatchKeys, mismatchValues) { + if (a.__Jasmine_been_here_before__ === b && b.__Jasmine_been_here_before__ === a) { + return true; + } + + a.__Jasmine_been_here_before__ = b; + b.__Jasmine_been_here_before__ = a; + + var hasKey = function(obj, keyName) { + return obj !== null && obj[keyName] !== jasmine.undefined; + }; + + for (var property in b) { + if (!hasKey(a, property) && hasKey(b, property)) { + mismatchKeys.push("expected has key '" + property + "', but missing from actual."); + } + } + for (property in a) { + if (!hasKey(b, property) && hasKey(a, property)) { + mismatchKeys.push("expected missing key '" + property + "', but present in actual."); + } + } + for (property in b) { + if (property == '__Jasmine_been_here_before__') continue; + if (!this.equals_(a[property], b[property], mismatchKeys, mismatchValues)) { + mismatchValues.push("'" + property + "' was '" + (b[property] ? jasmine.util.htmlEscape(b[property].toString()) : b[property]) + "' in expected, but was '" + (a[property] ? jasmine.util.htmlEscape(a[property].toString()) : a[property]) + "' in actual."); + } + } + + if (jasmine.isArray_(a) && jasmine.isArray_(b) && a.length != b.length) { + mismatchValues.push("arrays were not the same length"); + } + + delete a.__Jasmine_been_here_before__; + delete b.__Jasmine_been_here_before__; + return (mismatchKeys.length === 0 && mismatchValues.length === 0); +}; + +jasmine.Env.prototype.equals_ = function(a, b, mismatchKeys, mismatchValues) { + mismatchKeys = mismatchKeys || []; + mismatchValues = mismatchValues || []; + + for (var i = 0; i < this.equalityTesters_.length; i++) { + var equalityTester = this.equalityTesters_[i]; + var result = equalityTester(a, b, this, mismatchKeys, mismatchValues); + if (result !== jasmine.undefined) return result; + } + + if (a === b) return true; + + if (a === jasmine.undefined || a === null || b === jasmine.undefined || b === null) { + return (a == jasmine.undefined && b == jasmine.undefined); + } + + if (jasmine.isDomNode(a) && jasmine.isDomNode(b)) { + return a === b; + } + + if (a instanceof Date && b instanceof Date) { + return a.getTime() == b.getTime(); + } + + if (a.jasmineMatches) { + return a.jasmineMatches(b); + } + + if (b.jasmineMatches) { + return b.jasmineMatches(a); + } + + if (a instanceof jasmine.Matchers.ObjectContaining) { + return a.matches(b); + } + + if (b instanceof jasmine.Matchers.ObjectContaining) { + return b.matches(a); + } + + if (jasmine.isString_(a) && jasmine.isString_(b)) { + return (a == b); + } + + if (jasmine.isNumber_(a) && jasmine.isNumber_(b)) { + return (a == b); + } + + if (typeof a === "object" && typeof b === "object") { + return this.compareObjects_(a, b, mismatchKeys, mismatchValues); + } + + //Straight check + return (a === b); +}; + +jasmine.Env.prototype.contains_ = function(haystack, needle) { + if (jasmine.isArray_(haystack)) { + for (var i = 0; i < haystack.length; i++) { + if (this.equals_(haystack[i], needle)) return true; + } + return false; + } + return haystack.indexOf(needle) >= 0; +}; + +jasmine.Env.prototype.addEqualityTester = function(equalityTester) { + this.equalityTesters_.push(equalityTester); +}; +/** No-op base class for Jasmine reporters. + * + * @constructor + */ +jasmine.Reporter = function() { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerStarting = function(runner) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportRunnerResults = function(runner) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSuiteResults = function(suite) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecStarting = function(spec) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.reportSpecResults = function(spec) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.Reporter.prototype.log = function(str) { +}; + +/** + * Blocks are functions with executable code that make up a spec. + * + * @constructor + * @param {jasmine.Env} env + * @param {Function} func + * @param {jasmine.Spec} spec + */ +jasmine.Block = function(env, func, spec) { + this.env = env; + this.func = func; + this.spec = spec; +}; + +jasmine.Block.prototype.execute = function(onComplete) { + try { + this.func.apply(this.spec); + } catch (e) { + this.spec.fail(e); + } + onComplete(); +}; +/** JavaScript API reporter. + * + * @constructor + */ +jasmine.JsApiReporter = function() { + this.started = false; + this.finished = false; + this.suites_ = []; + this.results_ = {}; +}; + +jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) { + this.started = true; + var suites = runner.topLevelSuites(); + for (var i = 0; i < suites.length; i++) { + var suite = suites[i]; + this.suites_.push(this.summarize_(suite)); + } +}; + +jasmine.JsApiReporter.prototype.suites = function() { + return this.suites_; +}; + +jasmine.JsApiReporter.prototype.summarize_ = function(suiteOrSpec) { + var isSuite = suiteOrSpec instanceof jasmine.Suite; + var summary = { + id: suiteOrSpec.id, + name: suiteOrSpec.description, + type: isSuite ? 'suite' : 'spec', + children: [] + }; + + if (isSuite) { + var children = suiteOrSpec.children(); + for (var i = 0; i < children.length; i++) { + summary.children.push(this.summarize_(children[i])); + } + } + return summary; +}; + +jasmine.JsApiReporter.prototype.results = function() { + return this.results_; +}; + +jasmine.JsApiReporter.prototype.resultsForSpec = function(specId) { + return this.results_[specId]; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) { + this.finished = true; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSuiteResults = function(suite) { +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.reportSpecResults = function(spec) { + this.results_[spec.id] = { + messages: spec.results().getItems(), + result: spec.results().failedCount > 0 ? "failed" : "passed" + }; +}; + +//noinspection JSUnusedLocalSymbols +jasmine.JsApiReporter.prototype.log = function(str) { +}; + +jasmine.JsApiReporter.prototype.resultsForSpecs = function(specIds){ + var results = {}; + for (var i = 0; i < specIds.length; i++) { + var specId = specIds[i]; + results[specId] = this.summarizeResult_(this.results_[specId]); + } + return results; +}; + +jasmine.JsApiReporter.prototype.summarizeResult_ = function(result){ + var summaryMessages = []; + var messagesLength = result.messages.length; + for (var messageIndex = 0; messageIndex < messagesLength; messageIndex++) { + var resultMessage = result.messages[messageIndex]; + summaryMessages.push({ + text: resultMessage.type == 'log' ? resultMessage.toString() : jasmine.undefined, + passed: resultMessage.passed ? resultMessage.passed() : true, + type: resultMessage.type, + message: resultMessage.message, + trace: { + stack: resultMessage.passed && !resultMessage.passed() ? resultMessage.trace.stack : jasmine.undefined + } + }); + } + + return { + result : result.result, + messages : summaryMessages + }; +}; + +/** + * @constructor + * @param {jasmine.Env} env + * @param actual + * @param {jasmine.Spec} spec + */ +jasmine.Matchers = function(env, actual, spec, opt_isNot) { + this.env = env; + this.actual = actual; + this.spec = spec; + this.isNot = opt_isNot || false; + this.reportWasCalled_ = false; +}; + +// todo: @deprecated as of Jasmine 0.11, remove soon [xw] +jasmine.Matchers.pp = function(str) { + throw new Error("jasmine.Matchers.pp() is no longer supported, please use jasmine.pp() instead!"); +}; + +// todo: @deprecated Deprecated as of Jasmine 0.10. Rewrite your custom matchers to return true or false. [xw] +jasmine.Matchers.prototype.report = function(result, failing_message, details) { + throw new Error("As of jasmine 0.11, custom matchers must be implemented differently -- please see jasmine docs"); +}; + +jasmine.Matchers.wrapInto_ = function(prototype, matchersClass) { + for (var methodName in prototype) { + if (methodName == 'report') continue; + var orig = prototype[methodName]; + matchersClass.prototype[methodName] = jasmine.Matchers.matcherFn_(methodName, orig); + } +}; + +jasmine.Matchers.matcherFn_ = function(matcherName, matcherFunction) { + return function() { + var matcherArgs = jasmine.util.argsToArray(arguments); + var result = matcherFunction.apply(this, arguments); + + if (this.isNot) { + result = !result; + } + + if (this.reportWasCalled_) return result; + + var message; + if (!result) { + if (this.message) { + message = this.message.apply(this, arguments); + if (jasmine.isArray_(message)) { + message = message[this.isNot ? 1 : 0]; + } + } else { + var englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { return ' ' + s.toLowerCase(); }); + message = "Expected " + jasmine.pp(this.actual) + (this.isNot ? " not " : " ") + englishyPredicate; + if (matcherArgs.length > 0) { + for (var i = 0; i < matcherArgs.length; i++) { + if (i > 0) message += ","; + message += " " + jasmine.pp(matcherArgs[i]); + } + } + message += "."; + } + } + var expectationResult = new jasmine.ExpectationResult({ + matcherName: matcherName, + passed: result, + expected: matcherArgs.length > 1 ? matcherArgs : matcherArgs[0], + actual: this.actual, + message: message + }); + this.spec.addMatcherResult(expectationResult); + return jasmine.undefined; + }; +}; + + + + +/** + * toBe: compares the actual to the expected using === + * @param expected + */ +jasmine.Matchers.prototype.toBe = function(expected) { + return this.actual === expected; +}; + +/** + * toNotBe: compares the actual to the expected using !== + * @param expected + * @deprecated as of 1.0. Use not.toBe() instead. + */ +jasmine.Matchers.prototype.toNotBe = function(expected) { + return this.actual !== expected; +}; + +/** + * toEqual: compares the actual to the expected using common sense equality. Handles Objects, Arrays, etc. + * + * @param expected + */ +jasmine.Matchers.prototype.toEqual = function(expected) { + return this.env.equals_(this.actual, expected); +}; + +/** + * toNotEqual: compares the actual to the expected using the ! of jasmine.Matchers.toEqual + * @param expected + * @deprecated as of 1.0. Use not.toEqual() instead. + */ +jasmine.Matchers.prototype.toNotEqual = function(expected) { + return !this.env.equals_(this.actual, expected); +}; + +/** + * Matcher that compares the actual to the expected using a regular expression. Constructs a RegExp, so takes + * a pattern or a String. + * + * @param expected + */ +jasmine.Matchers.prototype.toMatch = function(expected) { + return new RegExp(expected).test(this.actual); +}; + +/** + * Matcher that compares the actual to the expected using the boolean inverse of jasmine.Matchers.toMatch + * @param expected + * @deprecated as of 1.0. Use not.toMatch() instead. + */ +jasmine.Matchers.prototype.toNotMatch = function(expected) { + return !(new RegExp(expected).test(this.actual)); +}; + +/** + * Matcher that compares the actual to jasmine.undefined. + */ +jasmine.Matchers.prototype.toBeDefined = function() { + return (this.actual !== jasmine.undefined); +}; + +/** + * Matcher that compares the actual to jasmine.undefined. + */ +jasmine.Matchers.prototype.toBeUndefined = function() { + return (this.actual === jasmine.undefined); +}; + +/** + * Matcher that compares the actual to null. + */ +jasmine.Matchers.prototype.toBeNull = function() { + return (this.actual === null); +}; + +/** + * Matcher that boolean not-nots the actual. + */ +jasmine.Matchers.prototype.toBeTruthy = function() { + return !!this.actual; +}; + + +/** + * Matcher that boolean nots the actual. + */ +jasmine.Matchers.prototype.toBeFalsy = function() { + return !this.actual; +}; + + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was called. + */ +jasmine.Matchers.prototype.toHaveBeenCalled = function() { + if (arguments.length > 0) { + throw new Error('toHaveBeenCalled does not take arguments, use toHaveBeenCalledWith'); + } + + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy " + this.actual.identity + " to have been called.", + "Expected spy " + this.actual.identity + " not to have been called." + ]; + }; + + return this.actual.wasCalled; +}; + +/** @deprecated Use expect(xxx).toHaveBeenCalled() instead */ +jasmine.Matchers.prototype.wasCalled = jasmine.Matchers.prototype.toHaveBeenCalled; + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was not called. + * + * @deprecated Use expect(xxx).not.toHaveBeenCalled() instead + */ +jasmine.Matchers.prototype.wasNotCalled = function() { + if (arguments.length > 0) { + throw new Error('wasNotCalled does not take arguments'); + } + + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy " + this.actual.identity + " to not have been called.", + "Expected spy " + this.actual.identity + " to have been called." + ]; + }; + + return !this.actual.wasCalled; +}; + +/** + * Matcher that checks to see if the actual, a Jasmine spy, was called with a set of parameters. + * + * @example + * + */ +jasmine.Matchers.prototype.toHaveBeenCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + this.message = function() { + if (this.actual.callCount === 0) { + // todo: what should the failure message for .not.toHaveBeenCalledWith() be? is this right? test better. [xw] + return [ + "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but it was never called.", + "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but it was." + ]; + } else { + return [ + "Expected spy " + this.actual.identity + " to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall), + "Expected spy " + this.actual.identity + " not to have been called with " + jasmine.pp(expectedArgs) + " but was called with " + jasmine.pp(this.actual.argsForCall) + ]; + } + }; + + return this.env.contains_(this.actual.argsForCall, expectedArgs); +}; + +/** @deprecated Use expect(xxx).toHaveBeenCalledWith() instead */ +jasmine.Matchers.prototype.wasCalledWith = jasmine.Matchers.prototype.toHaveBeenCalledWith; + +/** @deprecated Use expect(xxx).not.toHaveBeenCalledWith() instead */ +jasmine.Matchers.prototype.wasNotCalledWith = function() { + var expectedArgs = jasmine.util.argsToArray(arguments); + if (!jasmine.isSpy(this.actual)) { + throw new Error('Expected a spy, but got ' + jasmine.pp(this.actual) + '.'); + } + + this.message = function() { + return [ + "Expected spy not to have been called with " + jasmine.pp(expectedArgs) + " but it was", + "Expected spy to have been called with " + jasmine.pp(expectedArgs) + " but it was" + ]; + }; + + return !this.env.contains_(this.actual.argsForCall, expectedArgs); +}; + +/** + * Matcher that checks that the expected item is an element in the actual Array. + * + * @param {Object} expected + */ +jasmine.Matchers.prototype.toContain = function(expected) { + return this.env.contains_(this.actual, expected); +}; + +/** + * Matcher that checks that the expected item is NOT an element in the actual Array. + * + * @param {Object} expected + * @deprecated as of 1.0. Use not.toContain() instead. + */ +jasmine.Matchers.prototype.toNotContain = function(expected) { + return !this.env.contains_(this.actual, expected); +}; + +jasmine.Matchers.prototype.toBeLessThan = function(expected) { + return this.actual < expected; +}; + +jasmine.Matchers.prototype.toBeGreaterThan = function(expected) { + return this.actual > expected; +}; + +/** + * Matcher that checks that the expected item is equal to the actual item + * up to a given level of decimal precision (default 2). + * + * @param {Number} expected + * @param {Number} precision + */ +jasmine.Matchers.prototype.toBeCloseTo = function(expected, precision) { + if (!(precision === 0)) { + precision = precision || 2; + } + var multiplier = Math.pow(10, precision); + var actual = Math.round(this.actual * multiplier); + expected = Math.round(expected * multiplier); + return expected == actual; +}; + +/** + * Matcher that checks that the expected exception was thrown by the actual. + * + * @param {String} expected + */ +jasmine.Matchers.prototype.toThrow = function(expected) { + var result = false; + var exception; + if (typeof this.actual != 'function') { + throw new Error('Actual is not a function'); + } + try { + this.actual(); + } catch (e) { + exception = e; + } + if (exception) { + result = (expected === jasmine.undefined || this.env.equals_(exception.message || exception, expected.message || expected)); + } + + var not = this.isNot ? "not " : ""; + + this.message = function() { + if (exception && (expected === jasmine.undefined || !this.env.equals_(exception.message || exception, expected.message || expected))) { + return ["Expected function " + not + "to throw", expected ? expected.message || expected : "an exception", ", but it threw", exception.message || exception].join(' '); + } else { + return "Expected function to throw an exception."; + } + }; + + return result; +}; + +jasmine.Matchers.Any = function(expectedClass) { + this.expectedClass = expectedClass; +}; + +jasmine.Matchers.Any.prototype.jasmineMatches = function(other) { + if (this.expectedClass == String) { + return typeof other == 'string' || other instanceof String; + } + + if (this.expectedClass == Number) { + return typeof other == 'number' || other instanceof Number; + } + + if (this.expectedClass == Function) { + return typeof other == 'function' || other instanceof Function; + } + + if (this.expectedClass == Object) { + return typeof other == 'object'; + } + + return other instanceof this.expectedClass; +}; + +jasmine.Matchers.Any.prototype.jasmineToString = function() { + return ''; +}; + +jasmine.Matchers.ObjectContaining = function (sample) { + this.sample = sample; +}; + +jasmine.Matchers.ObjectContaining.prototype.jasmineMatches = function(other, mismatchKeys, mismatchValues) { + mismatchKeys = mismatchKeys || []; + mismatchValues = mismatchValues || []; + + var env = jasmine.getEnv(); + + var hasKey = function(obj, keyName) { + return obj != null && obj[keyName] !== jasmine.undefined; + }; + + for (var property in this.sample) { + if (!hasKey(other, property) && hasKey(this.sample, property)) { + mismatchKeys.push("expected has key '" + property + "', but missing from actual."); + } + else if (!env.equals_(this.sample[property], other[property], mismatchKeys, mismatchValues)) { + mismatchValues.push("'" + property + "' was '" + (other[property] ? jasmine.util.htmlEscape(other[property].toString()) : other[property]) + "' in expected, but was '" + (this.sample[property] ? jasmine.util.htmlEscape(this.sample[property].toString()) : this.sample[property]) + "' in actual."); + } + } + + return (mismatchKeys.length === 0 && mismatchValues.length === 0); +}; + +jasmine.Matchers.ObjectContaining.prototype.jasmineToString = function () { + return ""; +}; +// Mock setTimeout, clearTimeout +// Contributed by Pivotal Computer Systems, www.pivotalsf.com + +jasmine.FakeTimer = function() { + this.reset(); + + var self = this; + self.setTimeout = function(funcToCall, millis) { + self.timeoutsMade++; + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, false); + return self.timeoutsMade; + }; + + self.setInterval = function(funcToCall, millis) { + self.timeoutsMade++; + self.scheduleFunction(self.timeoutsMade, funcToCall, millis, true); + return self.timeoutsMade; + }; + + self.clearTimeout = function(timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined; + }; + + self.clearInterval = function(timeoutKey) { + self.scheduledFunctions[timeoutKey] = jasmine.undefined; + }; + +}; + +jasmine.FakeTimer.prototype.reset = function() { + this.timeoutsMade = 0; + this.scheduledFunctions = {}; + this.nowMillis = 0; +}; + +jasmine.FakeTimer.prototype.tick = function(millis) { + var oldMillis = this.nowMillis; + var newMillis = oldMillis + millis; + this.runFunctionsWithinRange(oldMillis, newMillis); + this.nowMillis = newMillis; +}; + +jasmine.FakeTimer.prototype.runFunctionsWithinRange = function(oldMillis, nowMillis) { + var scheduledFunc; + var funcsToRun = []; + for (var timeoutKey in this.scheduledFunctions) { + scheduledFunc = this.scheduledFunctions[timeoutKey]; + if (scheduledFunc != jasmine.undefined && + scheduledFunc.runAtMillis >= oldMillis && + scheduledFunc.runAtMillis <= nowMillis) { + funcsToRun.push(scheduledFunc); + this.scheduledFunctions[timeoutKey] = jasmine.undefined; + } + } + + if (funcsToRun.length > 0) { + funcsToRun.sort(function(a, b) { + return a.runAtMillis - b.runAtMillis; + }); + for (var i = 0; i < funcsToRun.length; ++i) { + try { + var funcToRun = funcsToRun[i]; + this.nowMillis = funcToRun.runAtMillis; + funcToRun.funcToCall(); + if (funcToRun.recurring) { + this.scheduleFunction(funcToRun.timeoutKey, + funcToRun.funcToCall, + funcToRun.millis, + true); + } + } catch(e) { + } + } + this.runFunctionsWithinRange(oldMillis, nowMillis); + } +}; + +jasmine.FakeTimer.prototype.scheduleFunction = function(timeoutKey, funcToCall, millis, recurring) { + this.scheduledFunctions[timeoutKey] = { + runAtMillis: this.nowMillis + millis, + funcToCall: funcToCall, + recurring: recurring, + timeoutKey: timeoutKey, + millis: millis + }; +}; + +/** + * @namespace + */ +jasmine.Clock = { + defaultFakeTimer: new jasmine.FakeTimer(), + + reset: function() { + jasmine.Clock.assertInstalled(); + jasmine.Clock.defaultFakeTimer.reset(); + }, + + tick: function(millis) { + jasmine.Clock.assertInstalled(); + jasmine.Clock.defaultFakeTimer.tick(millis); + }, + + runFunctionsWithinRange: function(oldMillis, nowMillis) { + jasmine.Clock.defaultFakeTimer.runFunctionsWithinRange(oldMillis, nowMillis); + }, + + scheduleFunction: function(timeoutKey, funcToCall, millis, recurring) { + jasmine.Clock.defaultFakeTimer.scheduleFunction(timeoutKey, funcToCall, millis, recurring); + }, + + useMock: function() { + if (!jasmine.Clock.isInstalled()) { + var spec = jasmine.getEnv().currentSpec; + spec.after(jasmine.Clock.uninstallMock); + + jasmine.Clock.installMock(); + } + }, + + installMock: function() { + jasmine.Clock.installed = jasmine.Clock.defaultFakeTimer; + }, + + uninstallMock: function() { + jasmine.Clock.assertInstalled(); + jasmine.Clock.installed = jasmine.Clock.real; + }, + + real: { + setTimeout: jasmine.getGlobal().setTimeout, + clearTimeout: jasmine.getGlobal().clearTimeout, + setInterval: jasmine.getGlobal().setInterval, + clearInterval: jasmine.getGlobal().clearInterval + }, + + assertInstalled: function() { + if (!jasmine.Clock.isInstalled()) { + throw new Error("Mock clock is not installed, use jasmine.Clock.useMock()"); + } + }, + + isInstalled: function() { + return jasmine.Clock.installed == jasmine.Clock.defaultFakeTimer; + }, + + installed: null +}; +jasmine.Clock.installed = jasmine.Clock.real; + +//else for IE support +jasmine.getGlobal().setTimeout = function(funcToCall, millis) { + if (jasmine.Clock.installed.setTimeout.apply) { + return jasmine.Clock.installed.setTimeout.apply(this, arguments); + } else { + return jasmine.Clock.installed.setTimeout(funcToCall, millis); + } +}; + +jasmine.getGlobal().setInterval = function(funcToCall, millis) { + if (jasmine.Clock.installed.setInterval.apply) { + return jasmine.Clock.installed.setInterval.apply(this, arguments); + } else { + return jasmine.Clock.installed.setInterval(funcToCall, millis); + } +}; + +jasmine.getGlobal().clearTimeout = function(timeoutKey) { + if (jasmine.Clock.installed.clearTimeout.apply) { + return jasmine.Clock.installed.clearTimeout.apply(this, arguments); + } else { + return jasmine.Clock.installed.clearTimeout(timeoutKey); + } +}; + +jasmine.getGlobal().clearInterval = function(timeoutKey) { + if (jasmine.Clock.installed.clearTimeout.apply) { + return jasmine.Clock.installed.clearInterval.apply(this, arguments); + } else { + return jasmine.Clock.installed.clearInterval(timeoutKey); + } +}; + +/** + * @constructor + */ +jasmine.MultiReporter = function() { + this.subReporters_ = []; +}; +jasmine.util.inherit(jasmine.MultiReporter, jasmine.Reporter); + +jasmine.MultiReporter.prototype.addReporter = function(reporter) { + this.subReporters_.push(reporter); +}; + +(function() { + var functionNames = [ + "reportRunnerStarting", + "reportRunnerResults", + "reportSuiteResults", + "reportSpecStarting", + "reportSpecResults", + "log" + ]; + for (var i = 0; i < functionNames.length; i++) { + var functionName = functionNames[i]; + jasmine.MultiReporter.prototype[functionName] = (function(functionName) { + return function() { + for (var j = 0; j < this.subReporters_.length; j++) { + var subReporter = this.subReporters_[j]; + if (subReporter[functionName]) { + subReporter[functionName].apply(subReporter, arguments); + } + } + }; + })(functionName); + } +})(); +/** + * Holds results for a set of Jasmine spec. Allows for the results array to hold another jasmine.NestedResults + * + * @constructor + */ +jasmine.NestedResults = function() { + /** + * The total count of results + */ + this.totalCount = 0; + /** + * Number of passed results + */ + this.passedCount = 0; + /** + * Number of failed results + */ + this.failedCount = 0; + /** + * Was this suite/spec skipped? + */ + this.skipped = false; + /** + * @ignore + */ + this.items_ = []; +}; + +/** + * Roll up the result counts. + * + * @param result + */ +jasmine.NestedResults.prototype.rollupCounts = function(result) { + this.totalCount += result.totalCount; + this.passedCount += result.passedCount; + this.failedCount += result.failedCount; +}; + +/** + * Adds a log message. + * @param values Array of message parts which will be concatenated later. + */ +jasmine.NestedResults.prototype.log = function(values) { + this.items_.push(new jasmine.MessageResult(values)); +}; + +/** + * Getter for the results: message & results. + */ +jasmine.NestedResults.prototype.getItems = function() { + return this.items_; +}; + +/** + * Adds a result, tracking counts (total, passed, & failed) + * @param {jasmine.ExpectationResult|jasmine.NestedResults} result + */ +jasmine.NestedResults.prototype.addResult = function(result) { + if (result.type != 'log') { + if (result.items_) { + this.rollupCounts(result); + } else { + this.totalCount++; + if (result.passed()) { + this.passedCount++; + } else { + this.failedCount++; + } + } + } + this.items_.push(result); +}; + +/** + * @returns {Boolean} True if everything below passed + */ +jasmine.NestedResults.prototype.passed = function() { + return this.passedCount === this.totalCount; +}; +/** + * Base class for pretty printing for expectation results. + */ +jasmine.PrettyPrinter = function() { + this.ppNestLevel_ = 0; +}; + +/** + * Formats a value in a nice, human-readable string. + * + * @param value + */ +jasmine.PrettyPrinter.prototype.format = function(value) { + if (this.ppNestLevel_ > 40) { + throw new Error('jasmine.PrettyPrinter: format() nested too deeply!'); + } + + this.ppNestLevel_++; + try { + if (value === jasmine.undefined) { + this.emitScalar('undefined'); + } else if (value === null) { + this.emitScalar('null'); + } else if (value === jasmine.getGlobal()) { + this.emitScalar(''); + } else if (value.jasmineToString) { + this.emitScalar(value.jasmineToString()); + } else if (typeof value === 'string') { + this.emitString(value); + } else if (jasmine.isSpy(value)) { + this.emitScalar("spy on " + value.identity); + } else if (value instanceof RegExp) { + this.emitScalar(value.toString()); + } else if (typeof value === 'function') { + this.emitScalar('Function'); + } else if (typeof value.nodeType === 'number') { + this.emitScalar('HTMLNode'); + } else if (value instanceof Date) { + this.emitScalar('Date(' + value + ')'); + } else if (value.__Jasmine_been_here_before__) { + this.emitScalar(''); + } else if (jasmine.isArray_(value) || typeof value == 'object') { + value.__Jasmine_been_here_before__ = true; + if (jasmine.isArray_(value)) { + this.emitArray(value); + } else { + this.emitObject(value); + } + delete value.__Jasmine_been_here_before__; + } else { + this.emitScalar(value.toString()); + } + } finally { + this.ppNestLevel_--; + } +}; + +jasmine.PrettyPrinter.prototype.iterateObject = function(obj, fn) { + for (var property in obj) { + if (property == '__Jasmine_been_here_before__') continue; + fn(property, obj.__lookupGetter__ ? (obj.__lookupGetter__(property) !== jasmine.undefined && + obj.__lookupGetter__(property) !== null) : false); + } +}; + +jasmine.PrettyPrinter.prototype.emitArray = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitObject = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitScalar = jasmine.unimplementedMethod_; +jasmine.PrettyPrinter.prototype.emitString = jasmine.unimplementedMethod_; + +jasmine.StringPrettyPrinter = function() { + jasmine.PrettyPrinter.call(this); + + this.string = ''; +}; +jasmine.util.inherit(jasmine.StringPrettyPrinter, jasmine.PrettyPrinter); + +jasmine.StringPrettyPrinter.prototype.emitScalar = function(value) { + this.append(value); +}; + +jasmine.StringPrettyPrinter.prototype.emitString = function(value) { + this.append("'" + value + "'"); +}; + +jasmine.StringPrettyPrinter.prototype.emitArray = function(array) { + this.append('[ '); + for (var i = 0; i < array.length; i++) { + if (i > 0) { + this.append(', '); + } + this.format(array[i]); + } + this.append(' ]'); +}; + +jasmine.StringPrettyPrinter.prototype.emitObject = function(obj) { + var self = this; + this.append('{ '); + var first = true; + + this.iterateObject(obj, function(property, isGetter) { + if (first) { + first = false; + } else { + self.append(', '); + } + + self.append(property); + self.append(' : '); + if (isGetter) { + self.append(''); + } else { + self.format(obj[property]); + } + }); + + this.append(' }'); +}; + +jasmine.StringPrettyPrinter.prototype.append = function(value) { + this.string += value; +}; +jasmine.Queue = function(env) { + this.env = env; + this.blocks = []; + this.running = false; + this.index = 0; + this.offset = 0; + this.abort = false; +}; + +jasmine.Queue.prototype.addBefore = function(block) { + this.blocks.unshift(block); +}; + +jasmine.Queue.prototype.add = function(block) { + this.blocks.push(block); +}; + +jasmine.Queue.prototype.insertNext = function(block) { + this.blocks.splice((this.index + this.offset + 1), 0, block); + this.offset++; +}; + +jasmine.Queue.prototype.start = function(onComplete) { + this.running = true; + this.onComplete = onComplete; + this.next_(); +}; + +jasmine.Queue.prototype.isRunning = function() { + return this.running; +}; + +jasmine.Queue.LOOP_DONT_RECURSE = true; + +jasmine.Queue.prototype.next_ = function() { + var self = this; + var goAgain = true; + + while (goAgain) { + goAgain = false; + + if (self.index < self.blocks.length && !this.abort) { + var calledSynchronously = true; + var completedSynchronously = false; + + var onComplete = function () { + if (jasmine.Queue.LOOP_DONT_RECURSE && calledSynchronously) { + completedSynchronously = true; + return; + } + + if (self.blocks[self.index].abort) { + self.abort = true; + } + + self.offset = 0; + self.index++; + + var now = new Date().getTime(); + if (self.env.updateInterval && now - self.env.lastUpdate > self.env.updateInterval) { + self.env.lastUpdate = now; + self.env.setTimeout(function() { + self.next_(); + }, 0); + } else { + if (jasmine.Queue.LOOP_DONT_RECURSE && completedSynchronously) { + goAgain = true; + } else { + self.next_(); + } + } + }; + self.blocks[self.index].execute(onComplete); + + calledSynchronously = false; + if (completedSynchronously) { + onComplete(); + } + + } else { + self.running = false; + if (self.onComplete) { + self.onComplete(); + } + } + } +}; + +jasmine.Queue.prototype.results = function() { + var results = new jasmine.NestedResults(); + for (var i = 0; i < this.blocks.length; i++) { + if (this.blocks[i].results) { + results.addResult(this.blocks[i].results()); + } + } + return results; +}; + + +/** + * Runner + * + * @constructor + * @param {jasmine.Env} env + */ +jasmine.Runner = function(env) { + var self = this; + self.env = env; + self.queue = new jasmine.Queue(env); + self.before_ = []; + self.after_ = []; + self.suites_ = []; +}; + +jasmine.Runner.prototype.execute = function() { + var self = this; + if (self.env.reporter.reportRunnerStarting) { + self.env.reporter.reportRunnerStarting(this); + } + self.queue.start(function () { + self.finishCallback(); + }); +}; + +jasmine.Runner.prototype.beforeEach = function(beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach'; + this.before_.splice(0,0,beforeEachFunction); +}; + +jasmine.Runner.prototype.afterEach = function(afterEachFunction) { + afterEachFunction.typeName = 'afterEach'; + this.after_.splice(0,0,afterEachFunction); +}; + + +jasmine.Runner.prototype.finishCallback = function() { + this.env.reporter.reportRunnerResults(this); +}; + +jasmine.Runner.prototype.addSuite = function(suite) { + this.suites_.push(suite); +}; + +jasmine.Runner.prototype.add = function(block) { + if (block instanceof jasmine.Suite) { + this.addSuite(block); + } + this.queue.add(block); +}; + +jasmine.Runner.prototype.specs = function () { + var suites = this.suites(); + var specs = []; + for (var i = 0; i < suites.length; i++) { + specs = specs.concat(suites[i].specs()); + } + return specs; +}; + +jasmine.Runner.prototype.suites = function() { + return this.suites_; +}; + +jasmine.Runner.prototype.topLevelSuites = function() { + var topLevelSuites = []; + for (var i = 0; i < this.suites_.length; i++) { + if (!this.suites_[i].parentSuite) { + topLevelSuites.push(this.suites_[i]); + } + } + return topLevelSuites; +}; + +jasmine.Runner.prototype.results = function() { + return this.queue.results(); +}; +/** + * Internal representation of a Jasmine specification, or test. + * + * @constructor + * @param {jasmine.Env} env + * @param {jasmine.Suite} suite + * @param {String} description + */ +jasmine.Spec = function(env, suite, description) { + if (!env) { + throw new Error('jasmine.Env() required'); + } + if (!suite) { + throw new Error('jasmine.Suite() required'); + } + var spec = this; + spec.id = env.nextSpecId ? env.nextSpecId() : null; + spec.env = env; + spec.suite = suite; + spec.description = description; + spec.queue = new jasmine.Queue(env); + + spec.afterCallbacks = []; + spec.spies_ = []; + + spec.results_ = new jasmine.NestedResults(); + spec.results_.description = description; + spec.matchersClass = null; +}; + +jasmine.Spec.prototype.getFullName = function() { + return this.suite.getFullName() + ' ' + this.description + '.'; +}; + + +jasmine.Spec.prototype.results = function() { + return this.results_; +}; + +/** + * All parameters are pretty-printed and concatenated together, then written to the spec's output. + * + * Be careful not to leave calls to jasmine.log in production code. + */ +jasmine.Spec.prototype.log = function() { + return this.results_.log(arguments); +}; + +jasmine.Spec.prototype.runs = function (func) { + var block = new jasmine.Block(this.env, func, this); + this.addToQueue(block); + return this; +}; + +jasmine.Spec.prototype.addToQueue = function (block) { + if (this.queue.isRunning()) { + this.queue.insertNext(block); + } else { + this.queue.add(block); + } +}; + +/** + * @param {jasmine.ExpectationResult} result + */ +jasmine.Spec.prototype.addMatcherResult = function(result) { + this.results_.addResult(result); +}; + +jasmine.Spec.prototype.expect = function(actual) { + var positive = new (this.getMatchersClass_())(this.env, actual, this); + positive.not = new (this.getMatchersClass_())(this.env, actual, this, true); + return positive; +}; + +/** + * Waits a fixed time period before moving to the next block. + * + * @deprecated Use waitsFor() instead + * @param {Number} timeout milliseconds to wait + */ +jasmine.Spec.prototype.waits = function(timeout) { + var waitsFunc = new jasmine.WaitsBlock(this.env, timeout, this); + this.addToQueue(waitsFunc); + return this; +}; + +/** + * Waits for the latchFunction to return true before proceeding to the next block. + * + * @param {Function} latchFunction + * @param {String} optional_timeoutMessage + * @param {Number} optional_timeout + */ +jasmine.Spec.prototype.waitsFor = function(latchFunction, optional_timeoutMessage, optional_timeout) { + var latchFunction_ = null; + var optional_timeoutMessage_ = null; + var optional_timeout_ = null; + + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i]; + switch (typeof arg) { + case 'function': + latchFunction_ = arg; + break; + case 'string': + optional_timeoutMessage_ = arg; + break; + case 'number': + optional_timeout_ = arg; + break; + } + } + + var waitsForFunc = new jasmine.WaitsForBlock(this.env, optional_timeout_, latchFunction_, optional_timeoutMessage_, this); + this.addToQueue(waitsForFunc); + return this; +}; + +jasmine.Spec.prototype.fail = function (e) { + var expectationResult = new jasmine.ExpectationResult({ + passed: false, + message: e ? jasmine.util.formatException(e) : 'Exception', + trace: { stack: e.stack } + }); + this.results_.addResult(expectationResult); +}; + +jasmine.Spec.prototype.getMatchersClass_ = function() { + return this.matchersClass || this.env.matchersClass; +}; + +jasmine.Spec.prototype.addMatchers = function(matchersPrototype) { + var parent = this.getMatchersClass_(); + var newMatchersClass = function() { + parent.apply(this, arguments); + }; + jasmine.util.inherit(newMatchersClass, parent); + jasmine.Matchers.wrapInto_(matchersPrototype, newMatchersClass); + this.matchersClass = newMatchersClass; +}; + +jasmine.Spec.prototype.finishCallback = function() { + this.env.reporter.reportSpecResults(this); +}; + +jasmine.Spec.prototype.finish = function(onComplete) { + this.removeAllSpies(); + this.finishCallback(); + if (onComplete) { + onComplete(); + } +}; + +jasmine.Spec.prototype.after = function(doAfter) { + if (this.queue.isRunning()) { + this.queue.add(new jasmine.Block(this.env, doAfter, this)); + } else { + this.afterCallbacks.unshift(doAfter); + } +}; + +jasmine.Spec.prototype.execute = function(onComplete) { + var spec = this; + if (!spec.env.specFilter(spec)) { + spec.results_.skipped = true; + spec.finish(onComplete); + return; + } + + this.env.reporter.reportSpecStarting(this); + + spec.env.currentSpec = spec; + + spec.addBeforesAndAftersToQueue(); + + spec.queue.start(function () { + spec.finish(onComplete); + }); +}; + +jasmine.Spec.prototype.addBeforesAndAftersToQueue = function() { + var runner = this.env.currentRunner(); + var i; + + for (var suite = this.suite; suite; suite = suite.parentSuite) { + for (i = 0; i < suite.before_.length; i++) { + this.queue.addBefore(new jasmine.Block(this.env, suite.before_[i], this)); + } + } + for (i = 0; i < runner.before_.length; i++) { + this.queue.addBefore(new jasmine.Block(this.env, runner.before_[i], this)); + } + for (i = 0; i < this.afterCallbacks.length; i++) { + this.queue.add(new jasmine.Block(this.env, this.afterCallbacks[i], this)); + } + for (suite = this.suite; suite; suite = suite.parentSuite) { + for (i = 0; i < suite.after_.length; i++) { + this.queue.add(new jasmine.Block(this.env, suite.after_[i], this)); + } + } + for (i = 0; i < runner.after_.length; i++) { + this.queue.add(new jasmine.Block(this.env, runner.after_[i], this)); + } +}; + +jasmine.Spec.prototype.explodes = function() { + throw 'explodes function should not have been called'; +}; + +jasmine.Spec.prototype.spyOn = function(obj, methodName, ignoreMethodDoesntExist) { + if (obj == jasmine.undefined) { + throw "spyOn could not find an object to spy upon for " + methodName + "()"; + } + + if (!ignoreMethodDoesntExist && obj[methodName] === jasmine.undefined) { + throw methodName + '() method does not exist'; + } + + if (!ignoreMethodDoesntExist && obj[methodName] && obj[methodName].isSpy) { + throw new Error(methodName + ' has already been spied upon'); + } + + var spyObj = jasmine.createSpy(methodName); + + this.spies_.push(spyObj); + spyObj.baseObj = obj; + spyObj.methodName = methodName; + spyObj.originalValue = obj[methodName]; + + obj[methodName] = spyObj; + + return spyObj; +}; + +jasmine.Spec.prototype.removeAllSpies = function() { + for (var i = 0; i < this.spies_.length; i++) { + var spy = this.spies_[i]; + spy.baseObj[spy.methodName] = spy.originalValue; + } + this.spies_ = []; +}; + +/** + * Internal representation of a Jasmine suite. + * + * @constructor + * @param {jasmine.Env} env + * @param {String} description + * @param {Function} specDefinitions + * @param {jasmine.Suite} parentSuite + */ +jasmine.Suite = function(env, description, specDefinitions, parentSuite) { + var self = this; + self.id = env.nextSuiteId ? env.nextSuiteId() : null; + self.description = description; + self.queue = new jasmine.Queue(env); + self.parentSuite = parentSuite; + self.env = env; + self.before_ = []; + self.after_ = []; + self.children_ = []; + self.suites_ = []; + self.specs_ = []; +}; + +jasmine.Suite.prototype.getFullName = function() { + var fullName = this.description; + for (var parentSuite = this.parentSuite; parentSuite; parentSuite = parentSuite.parentSuite) { + fullName = parentSuite.description + ' ' + fullName; + } + return fullName; +}; + +jasmine.Suite.prototype.finish = function(onComplete) { + this.env.reporter.reportSuiteResults(this); + this.finished = true; + if (typeof(onComplete) == 'function') { + onComplete(); + } +}; + +jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) { + beforeEachFunction.typeName = 'beforeEach'; + this.before_.unshift(beforeEachFunction); +}; + +jasmine.Suite.prototype.afterEach = function(afterEachFunction) { + afterEachFunction.typeName = 'afterEach'; + this.after_.unshift(afterEachFunction); +}; + +jasmine.Suite.prototype.results = function() { + return this.queue.results(); +}; + +jasmine.Suite.prototype.add = function(suiteOrSpec) { + this.children_.push(suiteOrSpec); + if (suiteOrSpec instanceof jasmine.Suite) { + this.suites_.push(suiteOrSpec); + this.env.currentRunner().addSuite(suiteOrSpec); + } else { + this.specs_.push(suiteOrSpec); + } + this.queue.add(suiteOrSpec); +}; + +jasmine.Suite.prototype.specs = function() { + return this.specs_; +}; + +jasmine.Suite.prototype.suites = function() { + return this.suites_; +}; + +jasmine.Suite.prototype.children = function() { + return this.children_; +}; + +jasmine.Suite.prototype.execute = function(onComplete) { + var self = this; + this.queue.start(function () { + self.finish(onComplete); + }); +}; +jasmine.WaitsBlock = function(env, timeout, spec) { + this.timeout = timeout; + jasmine.Block.call(this, env, null, spec); +}; + +jasmine.util.inherit(jasmine.WaitsBlock, jasmine.Block); + +jasmine.WaitsBlock.prototype.execute = function (onComplete) { + if (jasmine.VERBOSE) { + this.env.reporter.log('>> Jasmine waiting for ' + this.timeout + ' ms...'); + } + this.env.setTimeout(function () { + onComplete(); + }, this.timeout); +}; +/** + * A block which waits for some condition to become true, with timeout. + * + * @constructor + * @extends jasmine.Block + * @param {jasmine.Env} env The Jasmine environment. + * @param {Number} timeout The maximum time in milliseconds to wait for the condition to become true. + * @param {Function} latchFunction A function which returns true when the desired condition has been met. + * @param {String} message The message to display if the desired condition hasn't been met within the given time period. + * @param {jasmine.Spec} spec The Jasmine spec. + */ +jasmine.WaitsForBlock = function(env, timeout, latchFunction, message, spec) { + this.timeout = timeout || env.defaultTimeoutInterval; + this.latchFunction = latchFunction; + this.message = message; + this.totalTimeSpentWaitingForLatch = 0; + jasmine.Block.call(this, env, null, spec); +}; +jasmine.util.inherit(jasmine.WaitsForBlock, jasmine.Block); + +jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 10; + +jasmine.WaitsForBlock.prototype.execute = function(onComplete) { + if (jasmine.VERBOSE) { + this.env.reporter.log('>> Jasmine waiting for ' + (this.message || 'something to happen')); + } + var latchFunctionResult; + try { + latchFunctionResult = this.latchFunction.apply(this.spec); + } catch (e) { + this.spec.fail(e); + onComplete(); + return; + } + + if (latchFunctionResult) { + onComplete(); + } else if (this.totalTimeSpentWaitingForLatch >= this.timeout) { + var message = 'timed out after ' + this.timeout + ' msec waiting for ' + (this.message || 'something to happen'); + this.spec.fail({ + name: 'timeout', + message: message + }); + + this.abort = true; + onComplete(); + } else { + this.totalTimeSpentWaitingForLatch += jasmine.WaitsForBlock.TIMEOUT_INCREMENT; + var self = this; + this.env.setTimeout(function() { + self.execute(onComplete); + }, jasmine.WaitsForBlock.TIMEOUT_INCREMENT); + } +}; + +jasmine.version_= { + "major": 1, + "minor": 2, + "build": 0, + "revision": 1337005947 +}; diff --git a/lib/rotjs-library/tests/reporters/jasmine.console_reporter.js b/lib/rotjs-library/tests/reporters/jasmine.console_reporter.js new file mode 100644 index 0000000000000000000000000000000000000000..7995bd09cd01791c2f83b034ab06bbba72c8ffcf --- /dev/null +++ b/lib/rotjs-library/tests/reporters/jasmine.console_reporter.js @@ -0,0 +1,142 @@ +(function() { + if (! jasmine) { + throw new Exception("jasmine library does not exist in global namespace!"); + } + + /** + * Basic reporter that outputs spec results to the browser console. + * Useful if you need to test an html page and don't want the TrivialReporter + * markup mucking things up. + * + * Usage: + * + * jasmine.getEnv().addReporter(new jasmine.ConsoleReporter()); + * jasmine.getEnv().execute(); + */ + var ConsoleReporter = function() { + this.started = false; + this.finished = false; + }; + + ConsoleReporter.prototype = { + reportRunnerResults: function(runner) { + if (this.hasGroupedConsole()) { + var suites = runner.suites(); + startGroup(runner.results(), 'tests'); + for (var i=0; i1", function() { + var size = d2.computeSize(1/0, 220); + expect(size[1]).toBe(10); + }); + + it("should compute fractional size for spacing >1", function() { + var size = d2.computeSize(1/0, 210); + expect(size[1]).toBe(9); + }); + }); + + describe("hex layout", function() { + var d1 = new ROT.Display({fontSize:18, spacing:1, layout:"hex"}); + var d2 = new ROT.Display({fontSize:18, spacing:1.2, layout:"hex"}); + + it("should compute size for spacing 1", function() { + var size = d1.computeSize(1/0, 96); + expect(size[1]).toBe(5); + }); + + it("should compute size for spacing >1", function() { + var size = d2.computeSize(1/0, 96); + expect(size[1]).toBe(4); + }); + }); + }); + + describe("computeFontSize", function() { + describe("rectangular layout", function() { + var d1 = new ROT.Display({width:100, height:20, spacing:1}); + var d2 = new ROT.Display({width:100, height:20, spacing:1.2}); + + it("should compute integer size for spacing 1", function() { + var size = d1.computeFontSize(1/0, 180); + expect(size).toBe(9); + }); + + it("should compute fractional size for spacing 1", function() { + var size = d1.computeFontSize(1/0, 170); + expect(size).toBe(8); + }); + + it("should compute integer size for spacing >1", function() { + var size = d2.computeFontSize(1/0, 180); + expect(size).toBe(7); + }); + + it("should compute fractional size for spacing >1", function() { + var size = d2.computeFontSize(1/0, 170); + expect(size).toBe(6); + }); + }); + + describe("hex layout", function() { + var d1 = new ROT.Display({width:100, height:5, spacing:1, layout:"hex"}); + var d2 = new ROT.Display({width:100, height:5, spacing:1.3, layout:"hex"}); + + xit("should compute size for spacing 1", function() { + var size = d1.computeFontSize(1/0, 96); + expect(size).toBe(18); + }); + + it("should compute size for spacing >1", function() { + var size = d2.computeFontSize(1/0, 96); + expect(size).toBe(14); + }); + }); + }); +}); diff --git a/lib/rotjs-library/tests/spec/dungeon.js b/lib/rotjs-library/tests/spec/dungeon.js new file mode 100644 index 0000000000000000000000000000000000000000..f24830b43ba7c6e3bf2a40aeaea784683fd4e622 --- /dev/null +++ b/lib/rotjs-library/tests/spec/dungeon.js @@ -0,0 +1,72 @@ +describe("Map.Dungeon", function() { + var names = ["Digger", "Uniform"]; + + var buildDungeonTests = function(name) { + var ctor = ROT.Map[name]; + ROT.RNG.setSeed(1234); + var map = new ctor(); + map.create(); + var rooms = map.getRooms(); + var corridors = map.getCorridors(); + + describe(name, function() { + it("should generate >0 rooms", function() { + expect(rooms.length).toBeGreaterThan(0); + }); + + it("all rooms should have at least one door", function() { + for (var i=0;i0 corridors", function() { + expect(corridors.length).toBeGreaterThan(0); + }); + + it("all corridors should have at least one empty cell", function() { + for (var i=0;i=MAP48.length || y>=MAP48[0].length) { return false; } + return (MAP48[x][y] == 0); + } + + var A = [0, 1]; + var B = [2, 2]; + var Z = [4, 4]; + var X = [6, 2]; + var PATH = []; + var PATH_CALLBACK = function(x, y) { PATH.push(x, y); } + + /* + * . . A # . B + * . # # . . + * . . # . . . + * # . . # . + * X # # # Z . + */ + var MAP6 = [ /* transposed */ + [0, null, 0, null, 0], + [null, 0, null, 1, null], + [0, null, 0, null, 1], + [null, 1, null, 0, null], + [0, null, 1, null, 1], + [null, 1, null, 0, null], + [1, null, 0, null, 1], + [null, 0, null, 1, null], + [0, null, 0, null, 0], + [null, 0, null, 0, null], + [0, null, 0, null, 0] + ]; + + var A6 = [4, 0]; + var B6 = [10, 0]; + var Z6 = [8, 4]; + var X6 = [0, 4]; + + var PASSABLE_CALLBACK_6 = function(x, y) { + if (x<0 || y<0 || x>=MAP6.length || y>=MAP6[0].length) { return false; } + return (MAP6[x][y] == 0); + } + + beforeEach(function() { + PATH = []; + }); + + + describe("Dijkstra", function() { + describe("8-topology", function() { + var PATH_A = [0, 1, 0, 2, 0, 3, 1, 4, 2, 4, 3, 4, 4, 4]; + var PATH_B = [2, 2, 1, 2, 0, 3, 1, 4, 2, 4, 3, 4, 4, 4]; + var dijkstra = new ROT.Path.Dijkstra(Z[0], Z[1], PASSABLE_CALLBACK_48, {topology:8}); + + it("should compute correct path A", function() { + path = []; + dijkstra.compute(A[0], A[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_A.toString()); + }); + + it("should compute correct path B", function() { + dijkstra.compute(B[0], B[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_B.toString()); + }); + + it("should survive non-existant path X", function() { + dijkstra.compute(X[0], X[1], PATH_CALLBACK); + expect(PATH.length).toEqual(0); + }); + }); /* 8-topology */ + + describe("4-topology", function() { + var PATH_A = [0, 1, 0, 2, 0, 3, 0, 4, 1, 4, 2, 4, 3, 4, 4, 4]; + var PATH_B = [2, 2, 1, 2, 0, 2, 0, 3, 0, 4, 1, 4, 2, 4, 3, 4, 4, 4]; + var dijkstra = new ROT.Path.Dijkstra(Z[0], Z[1], PASSABLE_CALLBACK_48, {topology:4}); + + it("should compute correct path A", function() { + dijkstra.compute(A[0], A[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_A.toString()); + }); + + it("should compute correct path B", function() { + dijkstra.compute(B[0], B[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_B.toString()); + }); + + it("should survive non-existant path X", function() { + dijkstra.compute(X[0], X[1], PATH_CALLBACK); + expect(PATH.length).toEqual(0); + }); + }); /* 4-topology */ + + describe("6-topology", function() { + var PATH_A = [4, 0, 2, 0, 1, 1, 2, 2, 3, 3, 5, 3, 6, 2, 8, 2, 9, 3, 8, 4]; + var PATH_B = [10, 0, 9, 1, 8, 2, 9, 3, 8, 4]; + var dijkstra = new ROT.Path.Dijkstra(Z6[0], Z6[1], PASSABLE_CALLBACK_6, {topology:6}); + + it("should compute correct path A", function() { + dijkstra.compute(A6[0], A6[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_A.toString()); + }); + + it("should compute correct path B", function() { + dijkstra.compute(B6[0], B6[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_B.toString()); + }); + + it("should survive non-existant path X", function() { + dijkstra.compute(X6[0], X6[1], PATH_CALLBACK); + expect(PATH.length).toEqual(0); + }); + }); /* 6-topology */ + + }); /* dijkstra */ + + describe("A*", function() { + describe("8-topology", function() { + var PATH_A = [0, 1, 0, 2, 0, 3, 1, 4, 2, 4, 3, 4, 4, 4]; + var PATH_B = [2, 2, 1, 2, 0, 3, 1, 4, 2, 4, 3, 4, 4, 4]; + var astar = new ROT.Path.AStar(Z[0], Z[1], PASSABLE_CALLBACK_48, {topology:8}); + + it("should compute correct path A", function() { + path = []; + astar.compute(A[0], A[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_A.toString()); + }); + + it("should compute correct path B", function() { + astar.compute(B[0], B[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_B.toString()); + }); + + it("should survive non-existant path X", function() { + astar.compute(X[0], X[1], PATH_CALLBACK); + expect(PATH.length).toEqual(0); + }); + }); /* 8-topology */ + + describe("4-topology", function() { + var PATH_A = [0, 1, 0, 2, 0, 3, 0, 4, 1, 4, 2, 4, 3, 4, 4, 4]; + var PATH_B = [2, 2, 1, 2, 0, 2, 0, 3, 0, 4, 1, 4, 2, 4, 3, 4, 4, 4]; + var astar = new ROT.Path.AStar(Z[0], Z[1], PASSABLE_CALLBACK_48, {topology:4}); + + it("should compute correct path A", function() { + astar.compute(A[0], A[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_A.toString()); + }); + + it("should compute correct path B", function() { + astar.compute(B[0], B[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_B.toString()); + }); + + it("should survive non-existant path X", function() { + astar.compute(X[0], X[1], PATH_CALLBACK); + expect(PATH.length).toEqual(0); + }); + }); /* 4-topology */ + + describe("6-topology", function() { + var PATH_A = [4, 0, 2, 0, 1, 1, 2, 2, 3, 3, 5, 3, 6, 2, 8, 2, 9, 3, 8, 4]; + var PATH_B = [10, 0, 9, 1, 8, 2, 9, 3, 8, 4]; + var astar = new ROT.Path.AStar(Z6[0], Z6[1], PASSABLE_CALLBACK_6, {topology:6}); + + it("should compute correct path A", function() { + astar.compute(A6[0], A6[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_A.toString()); + }); + + it("should compute correct path B", function() { + astar.compute(B6[0], B6[1], PATH_CALLBACK); + expect(PATH.toString()).toEqual(PATH_B.toString()); + }); + + it("should survive non-existant path X", function() { + astar.compute(X6[0], X6[1], PATH_CALLBACK); + expect(PATH.length).toEqual(0); + }); + }); /* 6-topology */ + + }); /* A* */ + +}); /* path */ diff --git a/lib/rotjs-library/tests/spec/rng.js b/lib/rotjs-library/tests/spec/rng.js new file mode 100644 index 0000000000000000000000000000000000000000..afe1c57ddec74a182b2a279e9dfc0fa925792cea --- /dev/null +++ b/lib/rotjs-library/tests/spec/rng.js @@ -0,0 +1,47 @@ +describe("RNG", function() { + describe("getUniform", function() { + var value = ROT.RNG.getUniform(); + it("should return a number", function() { + expect(typeof(value)).toEqual("number"); + }); + it("should return a number 0..1", function() { + expect(value).toBeGreaterThan(0); + expect(value).toBeLessThan(1); + }); + }); + + describe("seeding", function() { + it("should return a seed number", function() { + expect(typeof(ROT.RNG.getSeed())).toEqual("number"); + }); + + it("should return the same value for a given seed", function() { + var seed = Math.round(Math.random()*1000000); + ROT.RNG.setSeed(seed); + var val1 = ROT.RNG.getUniform(); + ROT.RNG.setSeed(seed); + var val2 = ROT.RNG.getUniform(); + expect(val1).toEqual(val2); + }); + + it("should return a precomputed value for a given seed", function() { + ROT.RNG.setSeed(12345); + var val = ROT.RNG.getUniform(); + expect(val).toEqual(0.01198604702949524); + }); + }); + + describe("state manipulation", function() { + it("should return identical values after setting identical states", function() { + ROT.RNG.getUniform(); + + var state = ROT.RNG.getState(); + var val1 = ROT.RNG.getUniform(); + ROT.RNG.setState(state); + var val2 = ROT.RNG.getUniform(); + + expect(val1).toEqual(val2); + }); + }); + +}); diff --git a/lib/rotjs-library/tests/spec/scheduler.js b/lib/rotjs-library/tests/spec/scheduler.js new file mode 100644 index 0000000000000000000000000000000000000000..ee8ea19a6ef6f8407afbbcffd812153946070f55 --- /dev/null +++ b/lib/rotjs-library/tests/spec/scheduler.js @@ -0,0 +1,39 @@ +describe("Scheduler", function() { + var A50 = {getSpeed: function() { return 50; }}; + var A100a = {getSpeed: function() { return 100; }}; + var A100b = {getSpeed: function() { return 100; }}; + var A200 = {getSpeed: function() { return 200; }}; + var s = new ROT.Scheduler(); + + beforeEach(function() { + s.clear(); + this.addMatchers({ + toSchedule: function(expected) { + for (var i=0;i", + "/":"?", + "\\":"|" + } + //Special Keys - and their codes + var special_keys = { + 'esc':27, + 'escape':27, + 'tab':9, + 'space':32, + 'return':13, + 'enter':13, + 'backspace':8, + + 'scrolllock':145, + 'scroll_lock':145, + 'scroll':145, + 'capslock':20, + 'caps_lock':20, + 'caps':20, + 'numlock':144, + 'num_lock':144, + 'num':144, + + 'pause':19, + 'break':19, + + 'insert':45, + 'home':36, + 'delete':46, + 'end':35, + + 'pageup':33, + 'page_up':33, + 'pu':33, + + 'pagedown':34, + 'page_down':34, + 'pd':34, + + 'left':37, + 'up':38, + 'right':39, + 'down':40, + + 'f1':112, + 'f2':113, + 'f3':114, + 'f4':115, + 'f5':116, + 'f6':117, + 'f7':118, + 'f8':119, + 'f9':120, + 'f10':121, + 'f11':122, + 'f12':123 + } + + var modifiers = { + shift: { wanted:false, pressed:false}, + ctrl : { wanted:false, pressed:false}, + alt : { wanted:false, pressed:false}, + meta : { wanted:false, pressed:false} //Meta is Mac specific + }; + + if(e.ctrlKey) modifiers.ctrl.pressed = true; + if(e.shiftKey) modifiers.shift.pressed = true; + if(e.altKey) modifiers.alt.pressed = true; + if(e.metaKey) modifiers.meta.pressed = true; + + for(var i=0; k=keys[i],i 1) { //If it is a special key + if(special_keys[k] == code) kp++; + + } else if(opt['keycode']) { + if(opt['keycode'] == code) kp++; + + } else { //The special keys did not match + if(character == k) kp++; + else { + if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase + character = shift_nums[character]; + if(character == k) kp++; + } + } + } + } + + if(kp == keys.length && + modifiers.ctrl.pressed == modifiers.ctrl.wanted && + modifiers.shift.pressed == modifiers.shift.wanted && + modifiers.alt.pressed == modifiers.alt.wanted && + modifiers.meta.pressed == modifiers.meta.wanted) { + callback(e); + + if(!opt['propagate']) { //Stop the event + //e.cancelBubble is supported by IE - this will kill the bubbling process. + e.cancelBubble = true; + e.returnValue = false; + + //e.stopPropagation works in Firefox. + if (e.stopPropagation) { + e.stopPropagation(); + e.preventDefault(); + } + return false; + } + } + } + this.all_shortcuts[shortcut_combination] = { + 'callback':func, + 'target':ele, + 'event': opt['type'] + }; + //Attach the function with the event + if(ele.addEventListener) ele.addEventListener(opt['type'], func, false); + else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func); + else ele['on'+opt['type']] = func; + }, + + //Remove the shortcut - just specify the shortcut and I will remove the binding + 'remove':function(shortcut_combination) { + shortcut_combination = shortcut_combination.toLowerCase(); + var binding = this.all_shortcuts[shortcut_combination]; + delete(this.all_shortcuts[shortcut_combination]) + if(!binding) return; + var type = binding['event']; + var ele = binding['target']; + var callback = binding['callback']; + + if(ele.detachEvent) ele.detachEvent('on'+type, callback); + else if(ele.removeEventListener) ele.removeEventListener(type, callback, false); + else ele['on'+type] = false; + } +} diff --git a/mods/default b/mods/default new file mode 100644 index 0000000000000000000000000000000000000000..13e1d9a3dc2a0912a7123452a6d0c00d4ef39d76 --- /dev/null +++ b/mods/default @@ -0,0 +1 @@ +../levels/ \ No newline at end of file diff --git a/mods/example_mod/01_theGreatWall.jsx b/mods/example_mod/01_theGreatWall.jsx new file mode 100644 index 0000000000000000000000000000000000000000..0377819b3b1c55ed107bafed8c6d47a23863ee7b --- /dev/null +++ b/mods/example_mod/01_theGreatWall.jsx @@ -0,0 +1,59 @@ +#BEGIN_PROPERTIES# +{ + "version": "1.0", + "commandsIntroduced": + ["global.startLevel", "global.onExit", "map.placePlayer", + "map.placeObject", "map.getHeight", "map.getWidth", + "map.displayChapter", "map.getPlayer", "player.hasItem"], + "music": "The Green" +} +#END_PROPERTIES# +/***************** + * theGreatWall.js * + ***************** + * + * The great wall defensed enemies in ancient. + * Meanwhile, it blocked citizens travel and trade to outside. + * + * Today, the great wall which replaced with electronic stones is still standing there. + * + * BREAK OUT! MAN! + * + * Freedom is not free! + */ + +function startLevel(map) { +#START_OF_START_LEVEL# + map.displayChapter('Chapter 1\nFreedom is not free'); + + map.placePlayer(25, map.getHeight() - 5); + + for (x = 0; x < map.getWidth(); x++) { + if ((x % 10) < 5 ) { + map.placeObject(x, 5, 'block'); + } else { + map.placeObject(x, 7, 'block'); + for (y = 0; y < 3; y ++) { + map.placeObject(x, 7 - y, 'block'); + } + } + map.placeObject(x, 10, 'block'); + } + +#BEGIN_EDITABLE# + +#END_EDITABLE# + + map.placeObject(15, 12, 'computer'); + map.placeObject(25, 0, 'exit'); +#END_OF_START_LEVEL# +} + +function onExit(map) { + if (!map.getPlayer().hasItem('computer')) { + map.writeStatus("Don't forget to pick up the computer!"); + return false; + } else { + return true; + } +} diff --git a/mods/example_mod/02_mod.jsx b/mods/example_mod/02_mod.jsx new file mode 100644 index 0000000000000000000000000000000000000000..511f1d7333d333f3caaa92d81c5c3643eba04ad5 --- /dev/null +++ b/mods/example_mod/02_mod.jsx @@ -0,0 +1,51 @@ +#BEGIN_PROPERTIES# +{ + "version": "1.0", + "music": "Brazil" +} +#END_PROPERTIES# +/************** + * mod.js * + ************* + * + * Congratulations! You'v completed the example of mod. + * + * Create your own mod by putting the source code into + * the directory [mods/$your_mod_name]. When you ready for it, + * just run [make mod=$your_mod_name] to build it. And you can + * add this paramater to any [make] command to specify which + * mod you want to handle. + * + * What are you waiting for? Come on! + * + * Create you own mod and enjoy it. + * + */ + +function startLevel(map) { +#START_OF_START_LEVEL# + var credits = [ + [14, 5, "E X A M P L E of M O D"], + [10, 7, "%c{#0f0}$%c{#cccccc} make mod=example_mod"], + [10, 9, "%c{#0f0}$%c{#cccccc} make mod=example_mod release"], + [10, 11, "%c{#0f0}$%c{#cccccc} make mod=example_mod runlocal"], + ] + + function drawCredits(i) { + if (i >= credits.length) { + return; + } + + // redraw lines bottom to top to avoid cutting off letters + for (var j = i; j >= 0; j--) { + var line = credits[j]; + map._display.drawText(line[0], line[1], line[2]); + } + + map.timeout(function () {drawCredits(i+1);}, 2000) + } + + map.timeout(function () {drawCredits(0);}, 4000); + +#END_OF_START_LEVEL# +} diff --git a/mods/example_mod/intro.js b/mods/example_mod/intro.js new file mode 100644 index 0000000000000000000000000000000000000000..1082a730f0f9bacabe953375a2313f8d134beb24 --- /dev/null +++ b/mods/example_mod/intro.js @@ -0,0 +1,17 @@ +function playIntro(display, map, i) { + if (i < 0) { + display._intro = true; + } else { + if (typeof i === 'undefined') { i = map.getHeight(); } + display.clear(); + display.drawText(0, i - 2, "%c{#0f0}> initialize"); + display.drawText(13, i + 3, "R I S E O F T H E M O D S"); + display.drawText(22, i + 5, "- or - "); + display.drawText(16, i + 7, "THE EXAMPLE OF MODS"); + display.drawText(5, i + 12, "a demo that shows how to develop a mod"); + display.drawText(10, i + 22, "Press any key to begin ..."); + setTimeout(function () { + display.playIntro(map, i - 1); + }, 100); + } +} diff --git a/music/(((stereofect)))_Winter_Solstice_2012.mp3 b/music/(((stereofect)))_Winter_Solstice_2012.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..ee443d46e24ba80beaaf80918c8a250cc89f379c --- /dev/null +++ b/music/(((stereofect)))_Winter_Solstice_2012.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:461764f69ec7858e6bcdbac4485edd8384111f4138da8d554cd3e3bc7670d4b9 +size 5473048 diff --git a/music/Adversity.mp3 b/music/Adversity.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..e9fe9369fd4ec1844ae535ff5d27784f983689b0 --- /dev/null +++ b/music/Adversity.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d9e34a9ac9ecf8fbcd50595025411e57a09efd2d9137d8e63e9974e5fa015299 +size 3135734 diff --git a/music/Adversity.wav b/music/Adversity.wav new file mode 100644 index 0000000000000000000000000000000000000000..71e8e26082150fce12355b02cb8f1a5a6e63dc3c --- /dev/null +++ b/music/Adversity.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f619d9f56df7095f246b6598a318325bec455be41fa12193c80ae9688b76f569 +size 17274244 diff --git a/music/Ant_Neely_-_07_-_Not_Fit_For_Human_Consumption.mp3 b/music/Ant_Neely_-_07_-_Not_Fit_For_Human_Consumption.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..d049c4f940118c28931845c5356b39c13adc53e3 --- /dev/null +++ b/music/Ant_Neely_-_07_-_Not_Fit_For_Human_Consumption.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c90e10b60ff1cf6ef1726222ad342bd878f6b98bc08e30ed20b750e5fd7a19d +size 5949218 diff --git a/music/BLEO_-_02_-_Tart_Pts_1__2_feat_KeFF.mp3 b/music/BLEO_-_02_-_Tart_Pts_1__2_feat_KeFF.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..d1721c978ce0afbd23c1b3dfd0f04acebd86be91 --- /dev/null +++ b/music/BLEO_-_02_-_Tart_Pts_1__2_feat_KeFF.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6d39880c4f2f8f56956b937d5cd0b665543f67f3134d1c17cc12269b72cb7135 +size 15177232 diff --git a/music/BLEO_-_04_-_Death_Destroyer_Radio_Edit_feat_Rhinostrich.mp3 b/music/BLEO_-_04_-_Death_Destroyer_Radio_Edit_feat_Rhinostrich.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..a6711d48f1cd6e53832980933ceb58f59072d171 --- /dev/null +++ b/music/BLEO_-_04_-_Death_Destroyer_Radio_Edit_feat_Rhinostrich.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec467c3d7473e951c84dce78906d8ff1a448b0f8fd68ba25b9941d2a859b0481 +size 9889035 diff --git a/music/Boss Loop 1.mp3 b/music/Boss Loop 1.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..83ed41cee3641053b89992521122b6cdf27d554c --- /dev/null +++ b/music/Boss Loop 1.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b698cb85728f6170f240e70984c68232478562f8e563d197d881807ae60a59b +size 2347463 diff --git a/music/Boss Loop 1.wav b/music/Boss Loop 1.wav new file mode 100644 index 0000000000000000000000000000000000000000..b89f40b389e95d699eefed62f18dd979368e5628 --- /dev/null +++ b/music/Boss Loop 1.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e22cf57b64280a9e7a634172cf92225ea0d58d1233d2195acedb975796416dbd +size 12928408 diff --git a/music/Broke_For_Free_-_01_-_Night_Owl.mp3 b/music/Broke_For_Free_-_01_-_Night_Owl.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..3be5e9699af5468196fc2fec870b57f0154882f4 --- /dev/null +++ b/music/Broke_For_Free_-_01_-_Night_Owl.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec565f7edf537b7a70c60b26555022ed08741cc1affb47ca9a6ca6e87cbb9a1e +size 8054664 diff --git a/music/DmitryMazin-GameScratch.mp3 b/music/DmitryMazin-GameScratch.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..436417b4bc3260cbdf71aaa12927a372151e7c51 Binary files /dev/null and b/music/DmitryMazin-GameScratch.mp3 differ diff --git a/music/Eric_Skiff_-_06_-_Searching.mp3 b/music/Eric_Skiff_-_06_-_Searching.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..6996fcff8171a1cc7641b94733bf8f8bfbc72c03 --- /dev/null +++ b/music/Eric_Skiff_-_06_-_Searching.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3edc1633d003822448394a1eeecba0320b2fc66cae1a14cb7cbf26866382e3fb +size 4648267 diff --git a/music/Eric_Skiff_-_09_-_Come_and_Find_Me_-_B_mix.mp3 b/music/Eric_Skiff_-_09_-_Come_and_Find_Me_-_B_mix.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b0816b643a6a3acad040b19c2892fa6cf73b4545 --- /dev/null +++ b/music/Eric_Skiff_-_09_-_Come_and_Find_Me_-_B_mix.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2dc353c773333c5465c233a8eddd2ca5c4d87ac18d985ac0c91447f39ff95cce +size 6421746 diff --git a/music/Fex_coming_soon.mp3 b/music/Fex_coming_soon.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..21ec59d4e171005b610a563f2bac2ef8abc4a69f --- /dev/null +++ b/music/Fex_coming_soon.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:de691c6517c36e08a07cddc69d1269dfd21c4007bae948ec0a972a8e60d5af2b +size 1204454 diff --git a/music/Jackson_D_Zero_One.mp3 b/music/Jackson_D_Zero_One.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..7e6de85168dff16f2ef3b57b9851d8855911b9a7 --- /dev/null +++ b/music/Jackson_D_Zero_One.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:308f8150bf301631a44a122ad39a4351179f7e8ef52fcfddfa30bdf8b2572e84 +size 4652136 diff --git a/music/Obsibilo_-_02_-_Comme_Des_Orages.mp3 b/music/Obsibilo_-_02_-_Comme_Des_Orages.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..d72a42834c27805758ee5302bcf76ed1b2302219 --- /dev/null +++ b/music/Obsibilo_-_02_-_Comme_Des_Orages.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:586c932c83138131aa2062065f4b6e8ac2ea3d704369896833cbe4cb4556bf01 +size 9257166 diff --git a/music/Obsibilo_-_Soixante-8.mp3 b/music/Obsibilo_-_Soixante-8.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..6ffe44ac02386dd0936e23af77da634a7a1dc057 --- /dev/null +++ b/music/Obsibilo_-_Soixante-8.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7176fb3a5afd1b12b0a3871c912296de990b3c95b1ea2fccab7be6b6ed932039 +size 8552654 diff --git a/music/Revolution_Void_-_08_-_Obscure_Terrain.mp3 b/music/Revolution_Void_-_08_-_Obscure_Terrain.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..6e203a8d762ad9f7eff466654e853dfadd58907c --- /dev/null +++ b/music/Revolution_Void_-_08_-_Obscure_Terrain.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba2992e3aa4415fe1ea54279b48b31c28452f5d0843bfd6404bc182719c9341e +size 8908719 diff --git a/music/RoccoW_-_Messeah.mp3 b/music/RoccoW_-_Messeah.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..fb002b483df0994c87cda157608ff8791e5dec94 --- /dev/null +++ b/music/RoccoW_-_Messeah.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b3d45ebb583bd2e6d4b362146b5631e8c5445d42a39dd454af71530950b625b +size 6713664 diff --git a/music/Rolemusic_-_07_-_Beach_Wedding_Dance.mp3 b/music/Rolemusic_-_07_-_Beach_Wedding_Dance.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..9f0820c4c45966888c52af74e8a010939a2ac48c --- /dev/null +++ b/music/Rolemusic_-_07_-_Beach_Wedding_Dance.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74d580b531f1bffa7c1fca14751c43d153a09256aa0e69c091a16e40e61c4ebc +size 10606684 diff --git a/music/Roots of Supremacy.mp3 b/music/Roots of Supremacy.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..464c98a2ca00a74e167ca06fd7a88a30b2fd8daf --- /dev/null +++ b/music/Roots of Supremacy.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8046eb4df27435058c072c89a29bfdaa592dea2aac3d99bd693624201071ead3 +size 4070291 diff --git a/music/Roots of Supremacy.wav b/music/Roots of Supremacy.wav new file mode 100644 index 0000000000000000000000000000000000000000..f51f6afdf8758edd40531c7202c64111d1d5d713 --- /dev/null +++ b/music/Roots of Supremacy.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d31980c351312f86769f28247bb6c4a4eb550cf1111c72c2cd79fba959d18b8b +size 22427208 diff --git a/music/Skizofonik_System.mp3 b/music/Skizofonik_System.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..7ddb6d604d32d55ff2d889b911b13f14ae53fbd2 --- /dev/null +++ b/music/Skizofonik_System.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf3832b53e5a6e9a7ba386f3a218d820fba615101b3655bc07682eefb5eadc15 +size 6522214 diff --git a/music/Spectrofuzz_Sunset_84.mp3 b/music/Spectrofuzz_Sunset_84.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..42ee0ebaf7c73da01c661f51fcfc3e33ce862fdc --- /dev/null +++ b/music/Spectrofuzz_Sunset_84.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3ad8130a50dfbf1e09c4597c16b503788f558ccfc9285b02154b66b0fa5efaf +size 1611678 diff --git a/music/Sycamore_Drive_-_03_-_The_Waves_Call_Her_Name.mp3 b/music/Sycamore_Drive_-_03_-_The_Waves_Call_Her_Name.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..8209df94f0d7f5fd0420215158b8a8663cb91c7c --- /dev/null +++ b/music/Sycamore_Drive_-_03_-_The_Waves_Call_Her_Name.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b96fbdb97bef9733c1ad9dd058148ce2f5ce969ed96403941929c450f3acedf +size 4177278 diff --git a/music/ThatAndyGuy-Chip-loop.mp3 b/music/ThatAndyGuy-Chip-loop.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..fa16dbb9db51d9576d6cbc29c685f5e64cf5f6db --- /dev/null +++ b/music/ThatAndyGuy-Chip-loop.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:264a076e79cd926729cdf331d72c935e9bed12ffda32004d10dec46d65322b14 +size 3841492 diff --git a/music/ThatAndyGuy-Chip.mp3 b/music/ThatAndyGuy-Chip.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..fe619798036037d20501157d5e9edaa116d5d6dc --- /dev/null +++ b/music/ThatAndyGuy-Chip.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5575df5a973094ee3143a9263ee9fbf15a3ff36bad139db8f80265d9f1e7cca +size 3292732 diff --git a/music/Tortue_Super_Sonic_-_11_-_Y.mp3 b/music/Tortue_Super_Sonic_-_11_-_Y.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..5f3a32b2c4886267ae6c3ba4bf4c9bd112aecc68 --- /dev/null +++ b/music/Tortue_Super_Sonic_-_11_-_Y.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbe6093beab45324c7c735fcb6fd24b95c5116867789ce3e22fa6fedd98ca627 +size 1596380 diff --git a/music/Various_Artists_-_15_-_Slimeball_vomit.mp3 b/music/Various_Artists_-_15_-_Slimeball_vomit.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b2fbd5ed2d945a6976ca984e121df4e722c7acec --- /dev/null +++ b/music/Various_Artists_-_15_-_Slimeball_vomit.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bce95f4bc2142567e836303f2132218b3c97381567e5e9a533a1869d35970577 +size 9826243 diff --git a/music/Vernon_Lenoir_-_Brazilicon_alley.mp3 b/music/Vernon_Lenoir_-_Brazilicon_alley.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..b4368a799cc0dedaa39bed1853024c9fd79fefd5 --- /dev/null +++ b/music/Vernon_Lenoir_-_Brazilicon_alley.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c82ff6f9c3b2aac02ecc18e474b5c7191dce9433664ec04d18b885a93b7f99dd +size 4139107 diff --git a/music/Yonnie_The_Green.mp3 b/music/Yonnie_The_Green.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..6461e9fd6265bb8b8ebfd93d682210fad9fdadc9 --- /dev/null +++ b/music/Yonnie_The_Green.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:164b8fa2b95b54280f509d9ace03f283a3b185e4ea0c4444edb77ed240280472 +size 2941415 diff --git a/music/all_ages_bitcrusher.mp3 b/music/all_ages_bitcrusher.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..891f9ce765e3dd822eccbe439771c6f3edc7a0db --- /dev/null +++ b/music/all_ages_bitcrusher.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd892330af9172d9532cb98603783e50525774764adc61f8d07830aceec0bd00 +size 2665657 diff --git a/music/conspiracy_bitcrusher_final.mp3 b/music/conspiracy_bitcrusher_final.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..0a037a26a5a80b70b09886f55580bc6b6c46da1f --- /dev/null +++ b/music/conspiracy_bitcrusher_final.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:993e9b37d2fcf4f31ae762a516770e9aab64882dfaa0b643fb89f6acf81015bf +size 3078914 diff --git a/music/gurh.mp3 b/music/gurh.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..32c8280a28939a73a588f08538c4124f7a1937c2 --- /dev/null +++ b/music/gurh.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:93c8acb150b92e8688ad9819fb89bfe838f0e31fc1e1aa931f8a115d1002c32a +size 3170041 diff --git a/music/intricate_cloudy_sin.mp3 b/music/intricate_cloudy_sin.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..dce9b720d1b750b29ff35006fb0ff0e3a5c7bcca --- /dev/null +++ b/music/intricate_cloudy_sin.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f873f7c26e52aca4f55761b30b7090d2ca2f813ab4b04d7cc2e382ad0ba861b +size 7700006 diff --git a/music/tracks.txt b/music/tracks.txt new file mode 100644 index 0000000000000000000000000000000000000000..a125c8e7871d162858b991bdef278c4e7b38a3ef --- /dev/null +++ b/music/tracks.txt @@ -0,0 +1,53 @@ +=== Tracks by Level === + + 01. Yonnie_The_Green + 02. gurh + 03. Obscure Terrain + 04. coming soon + 05. intricate_cloudy_sin + 06. DmitryMazin-GameScratch + 07. Tortue_Super_Sonic_-_11_-_Y + 08. Night Owl + 09. Sycamore_Drive_-_03_-_The_Waves_Call_Her_Name + 10. Eric_Skiff_-_09_-_Come_and_Find_Me_-_B_mix + 11. Conspiracy + 12. Messeah + 13. Eric_Skiff_-_06_-_Searching + 14. ThatAndyGuy-Chip-loop +@15. Sycamore_Drive_-_03_-_The_Waves_Call_Her_Name + 16. Obsibilo_-_Soixante-8 + 17. Various_Artists_-_15_-_Slimeball_vomit + 18. Rolemusic_-_07_-_Beach_Wedding_Dance + 19. Boss Loop 1 + 20. Adversity + 21. Comme Des Orages + XX. Vernon_Lenoir_-_Brazilicon_alley + +=== Credits & Licenses === + +"The Green" - Jonathan Holliday (used with permission) : 01 +"Dmitry's Thing #2" - Dmitry Mazin (written for Untrusted) : 02 +"Obscure Terrain" - Revolution Void (CC-BY-NC-SA) : 03 +"coming soon" - Fex (public domain) : 04 +"cloudy sin" - intricate (used with permission) : 05 +"Dynamic Punctuality" - Dmitry Mazin (written for Untrusted) : 06 +"Y" - Tortue Super Sonic (CC-BY-NC-SA) : 07 +"Night Owl" - Broke for Free (CC-BY): 08 +"The Waves Call Her Name" - Sycamore Drive (CC-BY-NC-SA) : 09, 15 +"Come and Find Me - B mix" - Eric Skiff (CC-BY) : 10 +"Conspiracy" - Mike and Alan (used with permission) : 11 +"Messeah" - RoccoW (CC-BY) : 12 +"Searching" - Eric Skiff (CC-BY) : 13 +"Da Funk Do You Know 'bout Chip?" - That Andy Guy (used with permission) : 14 +"Soixante-8" - Obsibilo (CC-BY-NC-SA) : 16 +"Tart (Pts 1 and 2)" - BLEO (CC-BY-NC-SA) : 17 +"Beach Wedding Dance" - Rolemusic (CC-BY-NC-SA) : 18 +"Boss Loop 1" - Essa (free to use) : 19 +"Adversity" - Seropard (free to use): 20 +"Comme Des Orages" - Obsibilo (CC-BY-NC-SA): 21 +"Brazilicon Alley" - Vernon Lenoir (CC-BY-NC-SA) : XX + +=== Under Consideration === + +"Death Destroyer [Radio Edit]" - BLEO (CC-BY-NC-SA) +"Slimeball Vomit" - Radio Scotvoid (CC-BY-SA) diff --git a/music/what.mp3 b/music/what.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..18500afef14627e903be6fc8188b9bab7d8318c8 --- /dev/null +++ b/music/what.mp3 @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bbd3a6030857e740c666080bde6451af5046aaf2291038675144ebc0e55cd8c +size 1368782 diff --git a/parse_target.sh b/parse_target.sh new file mode 100644 index 0000000000000000000000000000000000000000..8edbebae0121807f69923696cd5589f3210d6e85 --- /dev/null +++ b/parse_target.sh @@ -0,0 +1,29 @@ +# collecting jsx filenames in a directory and write them to $target. +target=$1 +mod=$2 + +# MOD +[ "$mod" != "default" ] && m=$mod +sed -i -e "s#\/\/%MOD%#$m#" $target + +# LEVELS +levels='' +for lvl in mods/$mod/*.jsx +do + lvl=`basename $lvl` + levels=`printf "$levels'%s'," $lvl` +done +levels="${levels%?}" +sed -i -e "s#\/\/%LEVELS%#$levels#g" $target + +# BONUS +bonus='' +if [ -d mods/$mod/bonus ]; then + for lvl in mods/$mod/bonus/*.jsx + do + lvl=`basename $lvl` + bonus=`printf "$bonus'%s'," $lvl` + done +fi +bonus="${bonus%?}" +sed -i -e "s#\/\/%BONUS%#$bonus#" $target diff --git a/scripts/_head.js b/scripts/_head.js new file mode 100644 index 0000000000000000000000000000000000000000..5d11b9790454f7c94492abc03937ba1f952e31c1 --- /dev/null +++ b/scripts/_head.js @@ -0,0 +1 @@ +(function () { diff --git a/scripts/_launcher_debug.js b/scripts/_launcher_debug.js new file mode 100644 index 0000000000000000000000000000000000000000..f6bf2d7551b5bbfe094aa06931f55f066e0170b5 --- /dev/null +++ b/scripts/_launcher_debug.js @@ -0,0 +1,6 @@ +$(document).ready(function() { + var startLevel = getParameterByName('lvl') ? parseInt(getParameterByName('lvl')) : null; + window.game = new Game(true, startLevel); + window.game._initialize(); + window.eval = {}; +}); diff --git a/scripts/_launcher_release.js b/scripts/_launcher_release.js new file mode 100644 index 0000000000000000000000000000000000000000..0e5d172a7fa7d6b6ac1564028dd4b5df4a90d98a --- /dev/null +++ b/scripts/_launcher_release.js @@ -0,0 +1,14 @@ +$(document).ready(function() { + new Game()._initialize(); + window.eval = {}; +}); + +// prevent ctrl+R and F5 +$(document).bind('keydown keyup', function(e) { + if(e.which === 116) { + return false; + } + if(e.which === 82 && e.ctrlKey) { + return false; + } +}); diff --git a/scripts/_tail.js b/scripts/_tail.js new file mode 100644 index 0000000000000000000000000000000000000000..dfcd59e36b0698317a886785ce0e62776cf25ae7 --- /dev/null +++ b/scripts/_tail.js @@ -0,0 +1,5 @@ + +})(); + +console.log("%cIf you can read this, you are cheating! D:", "color: red; font-size: x-large"); +console.log("%cBut really, you don't need this console to play the game. Walk around using arrow keys (or Vim keys), and pick up the computer (" + String.fromCharCode(0x2318) + "). Then the fun begins!", "font-size: 15px"); diff --git a/scripts/build/.gitignore b/scripts/build/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/scripts/codeEditor.js b/scripts/codeEditor.js new file mode 100644 index 0000000000000000000000000000000000000000..d8739a9c59bcec1f4341976503ea227266340731 --- /dev/null +++ b/scripts/codeEditor.js @@ -0,0 +1,490 @@ +function CodeEditor(textAreaDomID, width, height, game) { + var symbols = { + 'begin_line':'#BEGIN_EDITABLE#', + 'end_line':'#END_EDITABLE#', + 'begin_char':"#{#", + 'end_char': "#}#", + 'begin_properties':'#BEGIN_PROPERTIES#', + 'end_properties':'#END_PROPERTIES#', + 'start_start_level':'#START_OF_START_LEVEL#', + 'end_start_level':'#END_OF_START_LEVEL#' + }; + + var charLimit = 80; + + var properties = {}; + var editableLines = []; + var editableSections = {}; + var lastChange = {}; + var startOfStartLevel = null; + var endOfStartLevel = null; + + this.setEndOfStartLevel = function (eosl) { + endOfStartLevel = eosl; + } + + this.setEditableLines = function (el) { + editableLines = el; + } + + this.setEditableSections = function (es) { + editableSections = es; + } + + // for debugging purposes + log = function (text) { + if (game._debugMode) { + console.log(text); + } + } + + // preprocesses code,determines the location + // of editable lines and sections, loads properties + function preprocess(codeString) { + editableLines = []; + editableSections = {}; + endOfStartLevel = null; + startOfStartLevel = null; + var propertiesString = ''; + + var lineArray = codeString.split("\n"); + var inEditableBlock = false; + var inPropertiesBlock = false; + + for (var i = 0; i < lineArray.length; i++) { + var currentLine = lineArray[i]; + + // process properties + if (currentLine.indexOf(symbols.begin_properties) === 0) { + lineArray.splice(i,1); // be aware that this *mutates* the list + i--; + inPropertiesBlock = true; + } else if (currentLine.indexOf(symbols.end_properties) === 0) { + lineArray.splice(i,1); + i--; + inPropertiesBlock = false; + } else if (inPropertiesBlock) { + lineArray.splice(i,1); + i--; + propertiesString += currentLine; + } + // process editable lines and sections + else if (currentLine.indexOf(symbols.begin_line) === 0) { + lineArray.splice(i,1); + i--; + inEditableBlock = true; + } else if (currentLine.indexOf(symbols.end_line) === 0) { + lineArray.splice(i,1); + i--; + inEditableBlock = false; + } + // process start of startLevel() + else if (currentLine.indexOf(symbols.start_start_level) === 0) { + lineArray.splice(i,1); + startOfStartLevel = i; + i--; + } + // process end of startLevel() + else if (currentLine.indexOf(symbols.end_start_level) === 0) { + lineArray.splice(i,1); + endOfStartLevel = i; + i--; + } + // everything else + else { + if (inEditableBlock) { + editableLines.push(i); + } else { + // check if there are any editable sections + var sections = []; + var startPoint = null; + for (var j = 0; j < currentLine.length - 2; j++) { + if (currentLine.slice(j,j+3) === symbols.begin_char) { + currentLine = currentLine.slice(0,j) + currentLine.slice(j+3, currentLine.length); + startPoint = j; + } else if (currentLine.slice(j,j+3) === symbols.end_char) { + currentLine = currentLine.slice(0,j) + currentLine.slice(j+3, currentLine.length); + sections.push([startPoint, j]); + } + } + if (sections.length > 0) { + lineArray[i] = currentLine; + editableSections[i] = sections; + } + } + } + } + + try { + properties = JSON.parse(propertiesString); + } catch (e) { + properties = {}; + } + + return lineArray.join("\n"); + } + + var findEndOfSegment = function(line) { + // Given an editable line number, returns the last line of the + // given line's editable segment. + + if (editableLines.indexOf(line + 1) === -1) { + return line; + } + + return findEndOfSegment(line + 1); + }; + + var shiftLinesBy = function(array, after, shiftAmount) { + // Shifts all line numbers strictly after the given line by + // the provided amount. + + return array.map(function(line) { + if (line > after) { + log('Shifting ' + line + ' to ' + (line + shiftAmount)); + return line + shiftAmount; + } + return line; + }); + }; + + // enforces editing restrictions when set as the handler + // for the 'beforeChange' event + var enforceRestrictions = function(instance, change) { + lastChange = change; + + var inEditableArea = function(c) { + var lineNum = c.to.line; + if (editableLines.indexOf(lineNum) !== -1 && editableLines.indexOf(c.from.line) !== -1) { + // editable lines? + return true; + } else if (editableSections[lineNum]) { + // this line has editable sections - are we in one of them? + var sections = editableSections[lineNum]; + for (var i = 0; i < sections.length; i++) { + var section = sections[i]; + if (c.from.ch > section[0] && c.to.ch > section[0] && + c.from.ch < section[1] && c.to.ch < section[1]) { + return true; + } + } + return false; + } + }; + + log( + '---Editor input (beforeChange) ---\n' + + 'Kind: ' + change.origin + '\n' + + 'Number of lines: ' + change.text.length + '\n' + + 'From line: ' + change.from.line + '\n' + + 'To line: ' + change.to.line + ); + + if (!inEditableArea(change)) { + change.cancel(); + } else if (change.to.line < change.from.line || + change.to.line - change.from.line + 1 > change.text.length) { // Deletion + updateEditableLinesOnDeletion(change); + } else { // Insert/paste + // First line already editable + var newLines = change.text.length - (change.to.line - change.from.line + 1); + + if (newLines > 0) { + if (editableLines.indexOf(change.to.line) < 0) { + change.cancel(); + return; + } + + // enforce 80-char limit by wrapping all lines > 80 chars + var wrappedText = []; + change.text.forEach(function (line) { + while (line.length > charLimit) { + // wrap lines at spaces if at all possible + var minCutoff = charLimit - 20; + var cutoff = minCutoff + line.slice(minCutoff).indexOf(" "); + if (cutoff > 80) { + // no suitable cutoff point found - let's get messy + cutoff = 80; + } + wrappedText.push(line.substr(0, cutoff)); + line = line.substr(cutoff); + } + wrappedText.push(line); + }); + change.text = wrappedText; + + // updating line count + newLines = change.text.length - (change.to.line - change.from.line + 1); + + updateEditableLinesOnInsert(change, newLines); + } else { + // enforce 80-char limit by trimming the line + var lineLength = instance.getLine(change.to.line).length; + if (lineLength + change.text[0].length > charLimit) { + var allowedLength = Math.max(charLimit - lineLength, 0); + change.text[0] = change.text[0].substr(0, allowedLength); + } + } + + // modify editable sections accordingly + // TODO Probably broken by multiline paste + var sections = editableSections[change.to.line]; + if (sections) { + var delta = change.text[0].length - (change.to.ch - change.from.ch); + for (var i = 0; i < sections.length; i++) { + // move any section start/end points that we are to the left of + if (change.to.ch < sections[i][1]) { + sections[i][1] += delta; + } + if (change.to.ch < sections[i][0]) { + sections[i][0] += delta; + } + } + } + } + + log(editableLines); + } + + var updateEditableLinesOnInsert = function(change, newLines) { + var lastLine = findEndOfSegment(change.to.line); + + // Shift editable line numbers after this segment + editableLines = shiftLinesBy(editableLines, lastLine, newLines); + + // TODO If editable sections appear together with editable lines + // in a level, multiline edit does not properly handle editable + // sections. + + log("Appending " + newLines + " lines"); + + // Append new lines + for (var i = lastLine + 1; i <= lastLine + newLines; i++) { + editableLines.push(i); + } + + // Update endOfStartLevel + if (endOfStartLevel) { + endOfStartLevel += newLines; + } + }; + + var updateEditableLinesOnDeletion = function(changeInput) { + // Figure out how many lines just got removed + var numRemoved = changeInput.to.line - changeInput.from.line - changeInput.text.length + 1; + // Find end of segment + var editableSegmentEnd = findEndOfSegment(changeInput.to.line); + // Remove that many lines from its end, one by one + for (var i = editableSegmentEnd; i > editableSegmentEnd - numRemoved; i--) { + log('Removing\t' + i); + editableLines.remove(i); + } + // Shift lines that came after + editableLines = shiftLinesBy(editableLines, editableSegmentEnd, -numRemoved); + // TODO Shift editableSections + + // Update endOfStartLevel + if (endOfStartLevel) { + endOfStartLevel -= numRemoved; + } + }; + + // beforeChange events don't pick up undo/redo + // so we track them on change event + var trackUndoRedo = function(instance, change) { + if (change.origin === 'undo' || change.origin === 'redo') { + enforceRestrictions(instance, change); + } + } + + this.initialize = function() { + this.internalEditor = CodeMirror.fromTextArea(document.getElementById(textAreaDomID), { + theme: 'vibrant-ink', + lineNumbers: true, + dragDrop: false, + smartIndent: false + }); + + this.internalEditor.setSize(width, height); + + // set up event handlers + + this.internalEditor.on("focus", function(instance) { + // implements yellow box when changing focus + $('.CodeMirror').addClass('focus'); + $('#screen canvas').removeClass('focus'); + + $('#helpPane').hide(); + $('#menuPane').hide(); + }); + + this.internalEditor.on('cursorActivity', function (instance) { + // fixes the cursor lag bug + instance.refresh(); + + // automatically smart-indent if the cursor is at position 0 + // and the line is empty (ignore if backspacing) + if (lastChange.origin !== '+delete') { + var loc = instance.getCursor(); + if (loc.ch === 0 && instance.getLine(loc.line).trim() === "") { + instance.indentLine(loc.line, "prev"); + } + } + }); + + this.internalEditor.on('change', markEditableSections); + this.internalEditor.on('change', trackUndoRedo); + } + + // loads code into editor + this.loadCode = function(codeString) { + /* + * logic: before setting the value of the editor to the code string, + * we run it through setEditableLines and setEditableSections, which + * strip our notation from the string and as a side effect build up + * a data structure of editable areas + */ + + this.internalEditor.off('beforeChange', enforceRestrictions); + codeString = preprocess(codeString); + this.internalEditor.setValue(codeString); + this.internalEditor.on('beforeChange', enforceRestrictions); + + this.markUneditableLines(); + this.internalEditor.refresh(); + this.internalEditor.clearHistory(); + }; + + // marks uneditable lines within editor + this.markUneditableLines = function() { + var instance = this.internalEditor; + for (var i = 0; i < instance.lineCount(); i++) { + if (editableLines.indexOf(i) === -1) { + instance.addLineClass(i, 'wrap', 'disabled'); + } + } + } + + // marks editable sections inside uneditable lines within editor + var markEditableSections = function(instance) { + $('.editableSection').removeClass('editableSection'); + for (var line in editableSections) { + if (editableSections.hasOwnProperty(line)) { + var sections = editableSections[line]; + for (var i = 0; i < sections.length; i++) { + var section = sections[i]; + var from = {'line': parseInt(line), 'ch': section[0]}; + var to = {'line': parseInt(line), 'ch': section[1]}; + instance.markText(from, to, {'className': 'editableSection'}); + } + } + } + } + + // returns all contents + this.getCode = function (forSaving) { + var lines = this.internalEditor.getValue().split('\n'); + + if (!forSaving && startOfStartLevel) { + // insert the end of startLevel() marker at the appropriate location + lines.splice(startOfStartLevel, 0, "map._startOfStartLevelReached()"); + } + + if (!forSaving && endOfStartLevel) { + // insert the end of startLevel() marker at the appropriate location + lines.splice(endOfStartLevel+1, 0, "map._endOfStartLevelReached()"); + } + + return lines.join('\n'); + } + + // returns only the code written in editable lines and sections + this.getPlayerCode = function () { + var code = ''; + for (var i = 0; i < this.internalEditor.lineCount(); i++) { + if (editableLines && editableLines.indexOf(i) > -1) { + code += this.internalEditor.getLine(i) + ' \n'; + } + } + for (var line in editableSections) { + if (editableSections.hasOwnProperty(line)) { + var sections = editableSections[line]; + for (var i = 0; i < sections.length; i++) { + var section = sections[i]; + code += this.internalEditor.getLine(line).slice(section[0], section[1]) + ' \n'; + } + } + } + return code; + }; + + this.getProperties = function () { + return properties; + } + + this.setCode = function(code) { + // make sure we're not saving the hidden START/END_OF_START_LEVEL lines + code = code.split('\n').filter(function (line) { + return line.indexOf('OfStartLevelReached') < 0; + }).join('\n'); + + this.internalEditor.off('beforeChange',enforceRestrictions); + this.internalEditor.setValue(code); + this.internalEditor.on('beforeChange', enforceRestrictions); + this.markUneditableLines(); + this.internalEditor.refresh(); + this.internalEditor.clearHistory(); + } + + this.saveGoodState = function () { + var lvlNum = game._currentFile ? game._currentFile : game._currentLevel; + localStorage.setItem(game._getLocalKey('level' + lvlNum + '.lastGoodState'), JSON.stringify({ + code: this.getCode(true), + playerCode: this.getPlayerCode(), + editableLines: editableLines, + editableSections: editableSections, + endOfStartLevel: endOfStartLevel, + version: this.getProperties().version + })); + } + + this.createGist = function () { + var lvlNum = game._currentLevel; + var filename = 'untrusted-lvl' + lvlNum + '-solution.js'; + var description = 'Solution to level ' + lvlNum + ' in Untrusted: http://alex.nisnevich.com/untrusted/'; + var data = { + 'files': {}, + 'description': description, + 'public': true + }; + data['files'][filename] = { + 'content': this.getCode(true).replace(/\t/g, ' ') + }; + + var t = ['372f2dad', '3edbb23c', '7c82f871', '36a67eb8', '623e8b32']; + $.ajax({ + 'url': 'https://api.github.com/gists', + 'type': 'POST', + 'data': JSON.stringify(data), + 'headers': { 'Authorization': 'token ' + t.join('') }, + 'success': function (data, status, xhr) { + $('#savedLevelMsg').html('Level ' + lvlNum + ' solution saved at ' + data['html_url'] + ''); + } + }); + } + + this.getGoodState = function (lvlNum) { + return JSON.parse(localStorage.getItem(game._getLocalKey('level' + lvlNum + '.lastGoodState'))); + } + + this.refresh = function () { + this.internalEditor.refresh(); + } + + this.focus = function () { + this.internalEditor.focus(); + } + + this.initialize(); // run initialization code +} diff --git a/scripts/display.js b/scripts/display.js new file mode 100644 index 0000000000000000000000000000000000000000..28184d6f9da02b13c1602abbc52765bacc6414a9 --- /dev/null +++ b/scripts/display.js @@ -0,0 +1,258 @@ +ROT.Display.create = function(game, opts) { + opts.fontFamily = '"droid sans mono", Courier, "Courier New", monospace'; + var display = new ROT.Display(opts); + display.game = game; + return display; +}; + +ROT.Display.prototype.errors = []; + +ROT.Display.prototype.setupEventHandlers = function() { + var display = this; + var game = this.game; + + // directions for moving entities + var keys = { + 37: 'left', // left arrow + 38: 'up', // up arrow + 39: 'right', // right arrow + 40: 'down', // down arrow + 65: 'left', // A + 68: 'right', // D + 72: 'left', // H + 74: 'down', // J + 75: 'up', // K + 76: 'right', // L + 81: 'funcPhone', // Q + 82: 'rest', // R + 83: 'down', // S + 87: 'up', // W + 98: 'down', // 2 + 100: 'left', // 4 + 101: 'rest', // 5 + 102: 'right', // 6 + 104: 'up' // 8 + }; + + // contentEditable is required for canvas elements to detect keyboard events + $(this.getContainer()).attr("contentEditable", "true"); + this.getContainer().addEventListener("keydown", function(e) { + if (display._intro == true) { + game._start(); + display._intro = false; + } else if (keys[e.keyCode] && game.map.getPlayer()) { + game.map.getPlayer().move(keys[e.keyCode], true); + } + e.preventDefault(); + }); + + this.getContainer().addEventListener("click", function(e) { + $(this).addClass('focus'); + $('.CodeMirror').removeClass('focus'); + + $('#helpPane').hide(); + $('#menuPane').hide(); + }); +}; + +// drawObject takes care of looking up an object's symbol and color +// according to name (NOT according to the actual object literal!) +ROT.Display.prototype.drawObject = function (map, x, y, object) { + var type = object.type; + var definition = map._getObjectDefinition(type) || this.savedDefinitions[type]; + + var symbol = definition.symbol; + var color = object.color || definition.color || "#fff"; + var bgColor = object.bgColor || "#000"; + + this.draw(x, y, symbol, color, bgColor); +}; + +ROT.Display.prototype.drawAll = function(map) { + if (!this.offset) {this.offset = 0;} + + var game = this.game; + + // _initialize grid + var grid = new Array(game._dimensions.width); + for (var x = 0; x < game._dimensions.width; x++) { + grid[x] = new Array(game._dimensions.height); + for (var y = 0; y < game._dimensions.height; y++) { + grid[x][y] = { + type: 'empty', + bgColor: 'black' + }; + } + } + + // place static objects + for (var x = 0; x < game._dimensions.width; x++) { + for (var y = 0; y < game._dimensions.height; y++) { + grid[x][y] = { + type: map._getGrid()[x][y].type, + bgColor: map._getGrid()[x][y].bgColor + }; + } + } + + // place dynamic objects + var dynamicObjects = map.getDynamicObjects(); + for (var i = 0; i < dynamicObjects.length; i++) { + var obj = dynamicObjects[i]; + grid[obj.getX()][obj.getY()] = { + type: obj.getType(), + bgColor: map._getGrid()[obj.getX()][obj.getY()].bgColor + }; + } + + // place player + if (map.getPlayer()) { + var player = map.getPlayer(); + grid[player.getX()][player.getY()] = { + type: 'player', + color: player.getColor(), + bgColor: map._getGrid()[player.getX()][player.getY()].bgColor + } + } + + // draw grid + for (var x = 0; x < game._dimensions.width; x++) { + for (var y = Math.max(0, this.offset - map.getHeight()); y < game._dimensions.height; y++) { + this.drawObject(map, x, y + this.offset, grid[x][y]); + } + } + + // write error messages, if any + if (this.errors && this.errors.length > 0) { + for (var i = 0; i < this.errors.length; i++) { + var y = this.game._dimensions.height - this.errors.length + i; + this.drawText(0, y, this.errors[i]); + } + } + + // store for potential later use + this.grid = grid; +}; + +ROT.Display.prototype.drawPreviousLevel = function(map, offset) { + if (!offset) {offset = 0;} + + var game = this.game; + var grid = this.savedGrid; + + if (grid) { + for (var x = 0; x < game._dimensions.width; x++) { + for (var y = 0; y < game._dimensions.height; y++) { + this.drawObject(map, x, y + offset, grid[x][y]); + } + } + } +}; + +ROT.Display.prototype.saveGrid = function (map) { + this.savedGrid = this.grid; + this.savedDefinitions = map._getObjectDefinitions(); +} + +ROT.Display.prototype.playIntro = function (map, i) { + display = this; + playIntro(display, map, i) +}; + +ROT.Display.prototype.fadeIn = function (map, speed, callback, i) { + var display = this; + var game = this.game; + if (game._currentLevel == "bonus") { + var levelName = game._currentBonusLevel; + } else { + var levelName = game._levelFileNames[game._currentLevel - 1]; + } + var command = "%c{#0f0}> run " + levelName; + + if (i < -3) { + if (callback) { callback(); } + } else { + if (typeof i === 'undefined') { i = map.getHeight(); } + this.clear(); + this.errors = []; + this.drawPreviousLevel(map, i - map.getHeight()); + + this.offset = i + 3; + this.drawAll(map); + + this.drawText(0, i + 1, command); + + setTimeout(function () { + display.fadeIn(map, speed, callback, i - 1); + }, speed); + } +}; + +ROT.Display.prototype.writeStatus = function(text) { + var map = this.game.map; + + var strings = [text]; + if (text.length > map.getWidth()) { + // split into two lines + var minCutoff = map.getWidth() - 10; + var cutoff = minCutoff + text.slice(minCutoff).indexOf(" "); + strings = [text.slice(0, cutoff), text.slice(cutoff + 1)]; + } + + for (var i = 0; i < strings.length; i++) { + var str = strings[i]; + var x = Math.floor((map.getWidth() - str.length) / 2); + var y = map.getHeight() + i - strings.length - 1; + this.drawText(x, y, str); + } +}; + +ROT.Display.prototype.appendError = function(errorText, command) { + var game = this.game; + if (game._currentLevel == "bonus") { + var levelName = game._currentBonusLevel; + } else { + var levelName = game._levelFileNames[game._currentLevel - 1]; + } + if (!command) { + command = "%c{#0f0}> run " + levelName; + } + + this.offset -= 3; + this.errors = this.errors.concat([command, errorText, ""]); + this.clear(); + this.drawAll(game.map); +}; + +ROT.Display.prototype.focus = function() { + $('#screen').show(); + $(this.getContainer()).attr('tabindex', '0').click().focus(); +}; + + +ROT.Display.prototype.renderDom = function(html, css) { + // using ideas from http://robert.ocallahan.org/2011/11/drawing-dom-content-to-canvas.html + /*var canvas = $('#drawingCanvas')[0]; + var ctx = canvas.getContext("2d"); + canvas.width = canvas.width; //resets background of canvas + var data = "data:image/svg+xml," + + "" + + "" + + "" + + "
    " + + html + + "
    " + + "
    " + + "
    "; + //console.log(data); + var img = new Image(); + img.src = data; + //console.log(img); + img.onload = function() { + ctx.drawImage(img, 0, 0); + }*/ + + // drawing DOM to canvas doesn't work in many browsers, so + // we fall back to basic DOM rendering + $(dummyDom).html(html); // DOM CSS now resides in game.css with everything else +} diff --git a/scripts/dynamicObject.js b/scripts/dynamicObject.js new file mode 100644 index 0000000000000000000000000000000000000000..348a344b23a8fce7120c95dcd6925529ebd83e89 --- /dev/null +++ b/scripts/dynamicObject.js @@ -0,0 +1,259 @@ +function DynamicObject(map, type, x, y, __game) { + /* private variables */ + + var __x = x; + var __y = y; + var __type = type; + var __definition = __game._callUnexposedMethod(function () { + return map._getObjectDefinition(type); + }); + var __inventory = []; + var __destroyed = false; + var __myTurn = true; + var __timer = null; + + this._map = map; + + /* wrapper */ + + function wrapExposedMethod(f, object) { + return function () { + var args = arguments; + return __game._callUnexposedMethod(function () { + return f.apply(object, args); + }); + }; + }; + + /* unexposed methods */ + + this._computeDestination = function (startX, startY, direction) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: object._computeDestination()';} + + switch (direction) { + case 'up': + return {'x': startX, 'y': startY - 1}; + case 'down': + return {'x': startX, 'y': startY + 1}; + case 'left': + return {'x': startX - 1, 'y': startY}; + case 'right': + return {'x': startX + 1, 'y': startY}; + default: + return {'x': startX, 'y': startY}; + } + }; + + this._onTurn = function () { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: object._onTurn()';} + + var me = this; + var player = map.getPlayer(); + + function executeTurn() { + if (map._callbackValidationFailed) { + clearInterval(__timer); + return; + } + __myTurn = true; + + try { + //we need to check for a collision with the player *after* + //the player has moved but *before* the object itself moves + //this prevents a bug where players and objects can 'pass through' + //each other + if (__x === player.getX() && __y === player.getY()) { + if (__definition.pushable) { + me.move(player.getLastMoveDirection()); + } + if (__definition.onCollision) { + map._validateCallback(function () { + __definition.onCollision(player, me); + }); + } + } + + if (__myTurn && __definition.behavior) { + map._validateCallback(function () { + __definition.behavior(me, player); + }); + } + } catch (e) { + // throw e; // for debugging + map.writeStatus(e.toString()); + } + } + + if (__definition.interval) { + // start timer if not already set + if (!__timer) { + __timer = setInterval(executeTurn, __definition.interval); + } + + // don't move on regular turn, but still check for player collision + if (map.getPlayer().atLocation(__x, __y) && + (__definition.onCollision || __definition.projectile)) { + // trigger collision + if (__definition.projectile) { + // projectiles automatically kill + map.getPlayer().killedBy('a ' + __type); + } else { + var thing = this; + map._validateCallback(function () { + __definition.onCollision(map.getPlayer(), thing); + }); + } + } + } else { + executeTurn(); + } + }; + + this._afterMove = function () { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: object._afterMove()';} + + // try to pick up items + var objectName = map._getGrid()[__x][__y].type; + var object = map._getObjectDefinition(objectName); + if (object.type === 'item' && !__definition.projectile) { + __inventory.push(objectName); + map._removeItemFromMap(__x, __y, objectName); + map._playSound('pickup'); + } else if (object.type === 'trap') { + // this part is used by janosgyerik's bonus levels + if (object.deactivatedBy && object.deactivatedBy.indexOf(__type) > -1) { + if (typeof(object.onDeactivate) === 'function') { + __game.validateCallback(function(){ + object.onDeactivate(); + }); + } + map._removeItemFromMap(__x, __y, objectName); + } + } + }; + + this._destroy = function (onMapReset) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: object._destroy()';} + + var me = this; + + __destroyed = true; + clearInterval(__timer); + + // remove this object from map's __dynamicObjects list + map._refreshDynamicObjects(); + + // unless the map is being reset, play an explosion + // and call this object's onDestroy method + if (__definition.onDestroy && !onMapReset) { + if (!__definition.projectile) { + map._playSound('explosion'); + } + + map._validateCallback(function () { + __definition.onDestroy(me); + }); + } + }; + + /* exposed methods */ + + this.getX = function () { return __x; }; + this.getY = function () { return __y; }; + this.getType = function () { return __type; }; + this.isDestroyed = function () { return __destroyed; }; + + this.giveItemTo = wrapExposedMethod(function (player, itemType) { + var pl_at = player.atLocation; + + if (!(pl_at(__x, __y) || pl_at(__x+1, __y) || pl_at(__x-1, __y) || + pl_at(__x, __y+1) || pl_at(__x, __y-1))) { + throw (type + ' says: Can\'t give an item unless I\'m touching the player!'); + } + if (__inventory.indexOf(itemType) < 0) { + throw (type + ' says: I don\'t have that item!'); + } + + player._pickUpItem(itemType, map._getObjectDefinition(itemType)); + }, this); + + this.move = wrapExposedMethod(function (direction) { + var dest = this._computeDestination(__x, __y, direction); + + if (!__myTurn) { + throw 'Can\'t move when it isn\'t your turn!'; + } + + var nearestObj = map._findNearestToPoint("anyDynamic", dest.x, dest.y); + + // check for collision with player + if (map.getPlayer().atLocation(dest.x, dest.y) && + (__definition.onCollision || __definition.projectile)) { + // trigger collision + if (__definition.projectile) { + // projectiles automatically kill + map.getPlayer().killedBy('a ' + __type); + } else { + var thing = this; + map._validateCallback(function() { + __definition.onCollision(map.getPlayer(), thing); + }); + } + } else if (map._canMoveTo(dest.x, dest.y, __type) && + !map._isPointOccupiedByDynamicObject(dest.x, dest.y)) { + // move the object + __x = dest.x; + __y = dest.y; + this._afterMove(__x, __y); + } else { + // cannot move + if (__definition.projectile) { + // projectiles disappear when they cannot move + this._destroy(); + + // projectiles also destroy any dynamic objects they touch + if (map._isPointOccupiedByDynamicObject(dest.x, dest.y)) { + map._findDynamicObjectAtPoint(dest.x, dest.y)._destroy(); + } + } + } + + __myTurn = false; + }, this); + + this.canMove = wrapExposedMethod(function (direction) { + var dest = this._computeDestination(__x, __y, direction); + + // check if the object can move there and will not collide with + // another dynamic object + return (map._canMoveTo(dest.x, dest.y, __type) && + !map._isPointOccupiedByDynamicObject(dest.x, dest.y)); + }, this); + + this.findNearest = wrapExposedMethod(function (type) { + return map._findNearestToPoint(type, __x, __y); + }, this); + + // only for teleporters + this.setTarget = wrapExposedMethod(function (target) { + if (__type != 'teleporter') { + throw 'setTarget() can only be called on a teleporter!'; + } + + if (target === this) { + throw 'Teleporters cannot target themselves!'; + } + + this.target = target; + }, this); + + // call secureObject to prevent user code from tampering with private attributes + __game.secureObject(this, type); + + // constructor + + if (!map._dummy && __definition.interval) { + this._onTurn(); + } + +} diff --git a/scripts/game.js b/scripts/game.js new file mode 100644 index 0000000000000000000000000000000000000000..742fe0c711ee25ceca2b52a0ea2073294ab6bd5b --- /dev/null +++ b/scripts/game.js @@ -0,0 +1,459 @@ +function Game(debugMode, startLevel) { + /* private properties */ + + var __currentCode = ''; + var __commands = []; + var __playerCodeRunning = false; + + /* unexposed properties */ + + this._dimensions = { + width: 50, + height: 25 + }; + + this._levelFileNames = [ +//%LEVELS% + ]; + + this._bonusLevels = [ +//%BONUS% + ].filter(function (lvl) { return (lvl.indexOf('_') != 0); }); // filter out bonus levels that start with '_' + + this._mod = '//%MOD%'; + + this._viewableScripts = [ + 'codeEditor.js', + 'display.js', + 'dynamicObject.js', + 'game.js', + 'inventory.js', + 'map.js', + 'objects.js', + 'player.js', + 'reference.js', + 'sound.js', + 'ui.js', + 'util.js', + 'validate.js' + ]; + + this._editableScripts = [ + 'map.js', + 'objects.js', + 'player.js' + ]; + + this._resetTimeout = null; + this._currentLevel = 0; + this._currentFile = null; + this._currentBonusLevel = null; + this._levelReached = 1; + this._displayedChapters = []; + + this._playerPrototype = Player; // to allow messing with map.js and player.js later + + this._nextBonusLevel = null; + + /* unexposed getters */ + + this._getHelpCommands = function () { return __commands; }; + this._isPlayerCodeRunning = function () { return __playerCodeRunning; }; + this._getLocalKey = function (key) { return (this._mod.length == 0 ? '' : this._mod + '.') + key; }; + + /* unexposed setters */ + + this._setPlayerCodeRunning = function (pcr) { __playerCodeRunning = pcr; }; + + /* unexposed methods */ + + this._initialize = function () { + // Get last level reached from localStorage (if any) + var levelKey = this._mod.length == 0 ? 'levelReached' : this._mod + '.levelReached'; + this._levelReached = parseInt(localStorage.getItem(levelKey)) || 1; + + // Fix potential corruption + // levelReached may be "81111" instead of "8" due to bug + if (this._levelReached > this._levelFileNames.length) { + for (var l = 1; l <= this._levelFileNames.length; l++) { + if (!localStorage[this._getLocalKey("level" + l + ".lastGoodState")]) { + this._levelReached = l - 1; + break; + } + } + } + + // Initialize sound + this.sound = new Sound('local'); + // this.sound = new Sound(debugMode ? 'local' : 'cloudfront'); + + // Initialize map display + this.display = ROT.Display.create(this, { + width: this._dimensions.width, + height: this._dimensions.height, + fontSize: 20 + }); + this.display.setupEventHandlers(); + var display = this.display; + $('#screen').append(this.display.getContainer()); + $('#drawingCanvas, #dummyDom, #dummyDom *').click(function () { + display.focus(); + }); + + // Initialize editor, map, and objects + this.editor = new CodeEditor("editor", 600, 500, this); + this.map = new Map(this.display, this); + this.objects = this.getListOfObjects(); + + // Enable controls + this.enableShortcutKeys(); + this.enableButtons(); + this.setUpNotepad(); + + // Load help commands from local storage (if possible) + if (localStorage.getItem(this._getLocalKey('helpCommands'))) { + __commands = localStorage.getItem(this._getLocalKey('helpCommands')).split(';'); + } + + // Enable debug features + if (debugMode) { + this._debugMode = true; + this._levelReached = 999; // make all levels accessible + __commands = Object.keys(this.reference); // display all help + this.sound.toggleSound(); // mute sound by default in debug mode + } + + // Lights, camera, action + if (startLevel) { + this._currentLevel = startLevel - 1; + this._getLevel(startLevel, debugMode); + } else if (!debugMode && this._levelReached != 1) { + // load last level reached (unless it's the credits) + this._getLevel(Math.min(this._levelReached, 21)); + } else { + this._intro(); + } + }; + + this._intro = function () { + this.display.focus(); + this.display.playIntro(this.map); + }; + + this._start = function (lvl) { + this._getLevel(lvl ? lvl : 1); + }; + + this._moveToNextLevel = function () { + // is the player permitted to exit? + if (typeof this.onExit === 'function') { + var game = this; + var canExit = this.validateCallback(function () { + return game.onExit(game.map); + }); + if (!canExit) { + this.sound.playSound('blip'); + return; + } + } + + this.sound.playSound('complete'); + + //we disable moving so the player can't move during the fadeout + this.map.getPlayer()._canMove = false; + + if (this._currentLevel == 'bonus') { + if (this._nextBonusLevel) { + this._getLevelByPath("levels/bonus/" + this._nextBonusLevel); + } else { + // open main menu + $('#helpPane, #notepadPane').hide(); + $('#menuPane').show(); + } + } else { + this._getLevel(this._currentLevel + 1, false, true); + } + }; + + this._jumpToNthLevel = function (levelNum) { + this._currentFile = null; + this._getLevel(levelNum, false, false); + this.display.focus(); + this.sound.playSound('blip'); + }; + + // makes an ajax request to get the level text file and + // then loads it into the game + this._getLevel = function (levelNum, isResetting, movingToNextLevel) { + var game = this; + var editor = this.editor; + + if (levelNum > this._levelFileNames.length) { + return; + } + + this._levelReached = Math.max(levelNum, this._levelReached); + if (!debugMode) { + localStorage.setItem(this._getLocalKey('levelReached'), this._levelReached); + } + + var fileName = this._levelFileNames[levelNum - 1]; + + lvlCode = this._levels['levels/' + fileName]; + if (movingToNextLevel) { + // save level state and create a gist + editor.saveGoodState(); + editor.createGist(); + } + + game._currentLevel = levelNum; + game._currentBonusLevel = null; + game._currentFile = null; + + // load level code in editor + editor.loadCode(lvlCode); + + // restored saved state for this level? + if (!isResetting && editor.getGoodState(levelNum)) { + // unless the current level is a newer version + var newVer = editor.getProperties().version; + var savedVer = editor.getGoodState(levelNum).version; + if (!(newVer && (!savedVer || isNewerVersion(newVer, savedVer)))) { + // restore saved line/section/endOfStartLevel state if possible + if (editor.getGoodState(levelNum).endOfStartLevel) { + editor.setEndOfStartLevel(editor.getGoodState(levelNum).endOfStartLevel); + } + if (editor.getGoodState(levelNum).editableLines) { + editor.setEditableLines(editor.getGoodState(levelNum).editableLines); + } + if (editor.getGoodState(levelNum).editableSections) { + editor.setEditableSections(editor.getGoodState(levelNum).editableSections); + } + + // restore saved code + editor.setCode(editor.getGoodState(levelNum).code); + } + } + + // start the level and fade in + game._evalLevelCode(null, null, true); + game.display.focus(); + + // store the commands introduced in this level (for api reference) + __commands = __commands.concat(editor.getProperties().commandsIntroduced).unique(); + localStorage.setItem(this._getLocalKey('helpCommands'), __commands.join(';')); + }; + + this._getLevelByPath = function (filePath) { + var game = this; + var editor = this.editor; + + $.get(filePath, function (lvlCode) { + game._currentLevel = 'bonus'; + game._currentBonusLevel = filePath.split("levels/")[1]; + game._currentFile = null; + + // load level code in editor + editor.loadCode(lvlCode); + + // save next bonus level + game._nextBonusLevel = editor.getProperties()["nextBonusLevel"]; + + // start the level and fade in + game._evalLevelCode(null, null, true); + game.display.focus(); + + // store the commands introduced in this level (for api reference) + __commands = __commands.concat(editor.getProperties().commandsIntroduced).unique(); + localStorage.setItem(this._getLocalKey('helpCommands'), __commands.join(';')); + }, 'text'); + + }; + + // how meta can we go? + this._editFile = function (filePath) { + var game = this; + + var fileName = filePath.split('/')[filePath.split('/').length - 1]; + game._currentFile = filePath; + + $.get(filePath, function (code) { + // load level code in editor + if (game._editableScripts.indexOf(fileName) > -1) { + game.editor.loadCode('#BEGIN_EDITABLE#\n' + code + '\n#END_EDITABLE#'); + } else { + game.editor.loadCode(code); + } + }, 'text'); + }; + + this._resetLevel = function( level ) { + var game = this; + var resetTimeout_msec = 2500; + var reset_game_msg = "To reset this level press ^4 again."; + + if ( this._resetTimeout != null ) { + $('body, #buttons').css('background-color', '#000'); + window.clearTimeout( this._resetTimeout ); + this._resetTimeout = null; + + if (game._currentBonusLevel) { + game._getLevelByPath('levels/' + game._currentBonusLevel); + } else { + this._getLevel(level, true); + } + if(game.map._status == reset_game_msg) { + game.map.writeStatus(""); + } + } else { + this.map.writeStatus(reset_game_msg); + $('body, #buttons').css('background-color', '#900'); + + this._resetTimeout = setTimeout(function () { + game._resetTimeout = null; + if(game.map._status == reset_game_msg) { + game.map.writeStatus(""); + } + + $('body, #buttons').css('background-color', '#000'); + }, resetTimeout_msec ); + } + }; + + // restart level with currently loaded code + this._restartLevel = function () { + this.editor.setCode(__currentCode); + this._evalLevelCode(); + }; + + this._evalLevelCode = function (allCode, playerCode, isNewLevel, restartingLevelFromScript) { + this.map._clearIntervals(); + var game = this; + + // by default, get code from the editor + var loadedFromEditor = false; + if (!allCode) { + allCode = this.editor.getCode(); + playerCode = this.editor.getPlayerCode(); + loadedFromEditor = true; + } + + // if we're editing a script file, do something completely different + if (this._currentFile !== null && !restartingLevelFromScript) { + __currentCode = allCode; + this.validateAndRunScript(allCode); + return; + } + + // save current display state (for scrolling up later) + this.display.saveGrid(this.map); + + // validate the code + // if it passes validation, returns the startLevel function if it pass + // if it fails validation, returns false + var validatedStartLevel = this.validate(allCode, playerCode, restartingLevelFromScript); + + if (validatedStartLevel) { // code is valid + // reset the map + this.map._reset(); // for cleanup + this.map = new Map(this.display, this); + this.map._reset(); + this.map._setProperties(this.editor.getProperties()['mapProperties']); + + // save editor state + if (!restartingLevelFromScript) { + __currentCode = allCode; + } + if (loadedFromEditor && !restartingLevelFromScript) { + this.editor.saveGoodState(); + } + + // clear drawing canvas and hide it until level loads + var screenCanvas = $('#screen canvas')[0]; + $('#drawingCanvas')[0].width = screenCanvas.width; + $('#drawingCanvas')[0].height = screenCanvas.height; + $('#drawingCanvas').hide(); + $('#dummyDom').hide(); + + // set correct inventory state + this.setInventoryStateByLevel(this._currentLevel); + + // start the level + validatedStartLevel(this.map); + + // Add the computer to bonus levels that lack it + if (this._currentLevel == "bonus" && this.map.countObjects("computer") == 0) { + this.addToInventory("computer") + $('#editorPane, #savedLevelMsg').show(); + this.editor.refresh(); + } + + // draw the map + this.display.fadeIn(this.map, isNewLevel ? 100 : 10, function () { + game.map.refresh(); // refresh inventory display + + // show map overlays if necessary + if (game.map._properties.showDrawingCanvas) { + $('#drawingCanvas').show(); + } else if (game.map._properties.showDummyDom) { + $('#dummyDom').show(); + } + + // workaround because we can't use writeStatus() in startLevel() + // (due to the text getting overwritten by the fade-in) + if (game.editor.getProperties().startingMessage) { + game.map.writeStatus(game.editor.getProperties().startingMessage); + } + }); + + this.map._ready(); + + // start bg music for this level + if (this.editor.getProperties().music) { + this.sound.playTrackByName(this.editor.getProperties().music); + } + + // activate super menu if 21_endOfTheLine has been reached + if (this._levelReached >= 21) { + this.activateSuperMenu(); + } + + // finally, allow player movement + if (this.map.getPlayer()) { + this.map.getPlayer()._canMove = true; + game.display.focus(); + } + } else { // code is invalid + // play error sound + this.sound.playSound('static'); + + // disable player movement + this.map.getPlayer()._canMove = false; + } + }; + + this._callUnexposedMethod = function(f) { + if (__playerCodeRunning) { + __playerCodeRunning = false; + try { + res = f(); + } finally { + __playerCodeRunning = true; + } + return res; + } else { + return f(); + } + }; + this._checkObjective = function() { + if (typeof(this.objective) === 'function') { + var game = this; + var objectiveIsMet = this.validateCallback(function() { + return game.objective(game.map); + }); + if (objectiveIsMet) { + this._moveToNextLevel(); + } + } + } +} diff --git a/scripts/inventory.js b/scripts/inventory.js new file mode 100644 index 0000000000000000000000000000000000000000..9f4fe97a6607f554a13b69d49e068d1195095349 --- /dev/null +++ b/scripts/inventory.js @@ -0,0 +1,125 @@ +Game.prototype.inventory = []; + +Game.prototype.getItemDefinition = function (itemName) { + var map = this.map; + return this._callUnexposedMethod(function () { + return map._getObjectDefinition(itemName); + }); +}; + +Game.prototype.addToInventory = function (itemName) { + if (this.inventory.indexOf(itemName) === -1) { + this.inventory.push(itemName); + this.drawInventory(); + } +}; + +Game.prototype.checkInventory = function (itemName) { + return this.inventory.indexOf(itemName) > -1; +}; + +Game.prototype.removeFromInventory = function (itemName) { + var object = this.getItemDefinition(itemName); + if (!object) { + throw 'No such object: ' + itemName; + } + if (object.type != 'item') { + throw 'Object is not an item: ' + itemName; + } + + this.inventory.remove(itemName); + this.drawInventory(); + + if (object.onDrop) { + this._setPlayerCodeRunning(true); + try { + object.onDrop(); + } catch (e) { + this.map.writeStatus(e.toString()) + } + this._setPlayerCodeRunning(false); + } +}; + +Game.prototype.setInventoryStateByLevel = function (levelNum) { + // first remove items that have onDrop effects on UI + if (levelNum == 1 || levelNum == "bonus") { + this.removeFromInventory('computer'); + } + if (levelNum <= 7 || levelNum == "bonus") { + this.removeFromInventory('phone'); + } + + // clear any remaining items from inventory + this.inventory = []; + + // repopulate inventory by level + if (levelNum > 1) { + this.addToInventory('computer'); + $('#editorPane, #savedLevelMsg').fadeIn(); + this.editor.refresh(); + } + if (levelNum > 7) { + this.addToInventory('phone'); + $('#phoneButton').show(); + } + if (levelNum > 11) { + this.addToInventory('redKey'); + } + if (levelNum > 12) { + this.addToInventory('greenKey'); + } + if (levelNum > 13) { + this.addToInventory('blueKey'); + } + if (levelNum > 14) { + this.addToInventory('theAlgorithm'); + this.removeFromInventory('redKey'); + this.removeFromInventory('greenKey'); + this.removeFromInventory('blueKey'); + } + if (levelNum > 15) { + this.removeFromInventory('theAlgorithm'); + } + if (levelNum > 20) { + this.addToInventory('theAlgorithm'); + } + + // clear any status messages generated by this + this.map.writeStatus(""); +}; + +Game.prototype.drawInventory = function () { + var game = this; + + if (this.inventory.length > 0) { + $('#inventory').text('INVENTORY: '); + + this.inventory.forEach(function (item) { + var object = game.map._getObjectDefinition(item); + + $('') + .attr('title', item) + .css('color', object.color ? object.color : '#fff') + .text(object.symbol) + .appendTo($('#inventory')); + }); + } else { + $('#inventory').html(''); + } +}; + +/* methods relating to specific inventory items go here */ + +Game.prototype.usePhone = function () { + var player = this.map.getPlayer(); + if (player && player._canMove && player.hasItem('phone')) { + if (player._phoneFunc) { + this.sound.playSound('select'); + this.validateCallback(player._phoneFunc); + } else { + this.sound.playSound('static'); + this.map.writeStatus("Your function phone isn't bound to any function!"); + } + } +}; diff --git a/scripts/map.js b/scripts/map.js new file mode 100644 index 0000000000000000000000000000000000000000..15e312e396ebd0203df635eca02ce4828207809f --- /dev/null +++ b/scripts/map.js @@ -0,0 +1,699 @@ +function Map(display, __game) { + /* private variables */ + + var __player; + var __grid; + var __dynamicObjects = []; + var __objectDefinitions; + + var __lines; + var __dom; + var __domCSS = ''; + + var __allowOverwrite; + var __keyDelay; + var __refreshRate; + + var __intervals = []; + var __chapterHideTimeout; + + /* unexposed variables */ + + this._properties = {}; + this._display = display; + this._dummy = false; // overridden by dummyMap in validate.js + this._status = ''; + + /* wrapper */ + + function wrapExposedMethod(f, map) { + return function () { + var args = arguments; + return __game._callUnexposedMethod(function () { + return f.apply(map, args); + }); + }; + }; + + /* unexposed getters */ + + this._getObjectDefinition = function(objName) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getObjectDefinition()';} + return __objectDefinitions[objName]; + }; + this._getObjectDefinitions = function() { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getObjectDefinitions()';} + return __objectDefinitions; + }; + this._getGrid = function () { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getGrid()';} + return __grid; + }; + this._getLines = function() { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._getLines()';} + return __lines; + }; + + /* exposed getters */ + + this.getDynamicObjects = function () { + // copy dynamic object list to fix issue#166 + var copy = []; + for (var i = 0; i < __dynamicObjects.length; i++) { + copy[i] = __dynamicObjects[i]; + } + return copy; + }; + this.getPlayer = function () { return __player; }; + this.getWidth = function () { return __game._dimensions.width; }; + this.getHeight = function () { return __game._dimensions.height; }; + + /* unexposed methods */ + + this._reset = function () { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._reset()';} + + __objectDefinitions = __game.getListOfObjects(); + + this._display.clear(); + + __grid = new Array(__game._dimensions.width); + for (var x = 0; x < __game._dimensions.width; x++) { + __grid[x] = new Array(__game._dimensions.height); + for (var y = 0; y < __game._dimensions.height; y++) { + __grid[x][y] = {type: 'empty'}; + } + } + + this.getDynamicObjects().forEach(function (obj) { + obj._destroy(true); + }); + __dynamicObjects = []; + __player = null; + this._clearIntervals(); + __lines = []; + __dom = ''; + this._overrideKeys = {}; + + // preload stylesheet for DOM level + $.get('styles/dom.css', function (css) { + __domCSS = css; + }); + + this.finalLevel = false; + this._callbackValidationFailed = false; + }; + this._clearIntervals = function() { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._clearIntervals()';} + for (var i = 0; i < __intervals.length; i++) { + clearInterval(__intervals[i]); + } + __intervals = []; + }; + + this._ready = function () { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._ready()';} + + // set refresh rate if one is specified + if (__refreshRate) { + // wrapExposedMethod is necessary here to prevent the `_moveToNextLevel` + // call from breaking + this.startTimer(wrapExposedMethod(function () { + // refresh the map + this.refresh(); + + // check for nonstandard victory condition + __game._checkObjective() + }, this), __refreshRate); + } + }; + + this._setProperties = function (mapProperties) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._setProperties()';} + + // set defaults + this._properties = {}; + __allowOverwrite = false; + __keyDelay = 0; + __refreshRate = null; + + // now set any properties that were passed in + if (mapProperties) { + this._properties = mapProperties; + + if (mapProperties.allowOverwrite === true) { + __allowOverwrite = true; + } + + if (mapProperties.keyDelay) { + __keyDelay = mapProperties.keyDelay; + } + + if (mapProperties.refreshRate) { + __refreshRate = mapProperties.refreshRate; + } + } + }; + + this._canMoveTo = function (x, y, myType) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._canMoveTo()';} + + var x = Math.floor(x); var y = Math.floor(y); + + if (x < 0 || x >= __game._dimensions.width || y < 0 || y >= __game._dimensions.height) { + return false; + } + + // look for static objects that can serve as obstacles + var objType = __grid[x][y].type; + var object = __objectDefinitions[objType]; + if (object.impassable) { + if (myType && object.passableFor && object.passableFor.indexOf(myType) > -1) { + // this object is of a type that can pass the obstacle + return true; + } else if (typeof object.impassable === 'function') { + // the obstacle is impassable only in certain circumstances + return this._validateCallback(function () { + return !object.impassable(__player, object); + }); + } else { + // the obstacle is always impassable + return false; + } + } else if (myType && object.impassableFor && object.impassableFor.indexOf(myType) > -1) { + // this object is of a type that cannot pass the obstacle + return false; + } else { + // no obstacle + return true; + } + }; + + // Returns the object of the given type closest to target coordinates + this._findNearestToPoint = function (type, targetX, targetY) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._findNearestToPoint()';} + + var foundObjects = []; + + // look for static objects + for (var x = 0; x < this.getWidth(); x++) { + for (var y = 0; y < this.getHeight(); y++) { + if (__grid[x][y].type === type) { + foundObjects.push({x: x, y: y}); + } + } + } + + // look for dynamic objects + for (var i = 0; i < __dynamicObjects.length; i++) { + var object = __dynamicObjects[i]; + if (object.getType() === type) { + foundObjects.push({x: object.getX(), y: object.getY()}); + } + } + + // look for player + if (type === 'player') { + foundObjects.push({x: __player.getX(), y: __player.getY()}); + } + + var dists = []; + for (var i = 0; i < foundObjects.length; i++) { + var obj = foundObjects[i]; + dists[i] = Math.sqrt(Math.pow(targetX - obj.x, 2) + Math.pow(targetY - obj.y, 2)); + + // We want to find objects distinct from ourselves + if (dists[i] === 0) { + dists[i] = 999; + } + } + + var minDist = Math.min.apply(Math, dists); + var closestTarget = foundObjects[dists.indexOf(minDist)]; + + return closestTarget; + }; + + this._isPointOccupiedByDynamicObject = function (x, y) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._isPointOccupiedByDynamicObject()';} + + var x = Math.floor(x); var y = Math.floor(y); + + for (var i = 0; i < __dynamicObjects.length; i++) { + var object = __dynamicObjects[i]; + if (object.getX() === x && object.getY() === y) { + return true; + } + } + return false; + }; + + this._findDynamicObjectAtPoint = function (x, y) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._findDynamicObjectAtPoint()';} + + var x = Math.floor(x); var y = Math.floor(y); + + for (var i = 0; i < __dynamicObjects.length; i++) { + var object = __dynamicObjects[i]; + if (object.getX() === x && object.getY() === y) { + return object; + } + } + return false; + }; + + this._moveAllDynamicObjects = function () { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._moveAllDynamicObjects()';} + + // the way things work right now, teleporters must take precedence + // over all other objects -- otherwise, pointers.jsx will not work + // correctly. + // TODO: make this not be the case + + // "move" teleporters + __dynamicObjects.filter(function (object) { + return (object.getType() === 'teleporter'); + }).forEach(function(object) { + object._onTurn(); + }); + + // move everything else + __dynamicObjects.filter(function (object) { + return (object.getType() !== 'teleporter'); + }).forEach(function(object) { + object._onTurn(); + }); + + // refresh only at the end + this.refresh(); + }; + + this._removeItemFromMap = function (x, y, klass) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._removeItemFromMap()';} + + var x = Math.floor(x); var y = Math.floor(y); + + if (__grid[x][y].type === klass) { + __grid[x][y].type = 'empty'; + } + }; + + this._reenableMovementForPlayer = function (player) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._reenableMovementForPlayer()';} + + if (!this._callbackValidationFailed) { + setTimeout(function () { + player._canMove = true; + }, __keyDelay); + } + }; + + this._hideChapter = function() { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._hideChapter()';} + + // start fading out chapter immediately + // unless it's a death message, in which case wait 2.5 sec + clearInterval(__chapterHideTimeout); + __chapterHideTimeout = setTimeout(function () { + $('#chapter').fadeOut(1000); + }, $('#chapter').hasClass('death') ? 2500 : 0); + }; + + this._refreshDynamicObjects = function() { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._refreshDynamicObjects()';} + + __dynamicObjects = __dynamicObjects.filter(function (obj) { return !obj.isDestroyed(); }); + }; + + this._countTimers = function() { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._countTimers()';} + + return __intervals.length; + } + + /* (unexposed) wrappers for game methods */ + + this._startOfStartLevelReached = function() { + __game._startOfStartLevelReached = true; + }; + + this._endOfStartLevelReached = function() { + __game._endOfStartLevelReached = true; + }; + + this._playSound = function (sound) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._playSound()';} + + __game.sound.playSound(sound); + }; + + this._validateCallback = function (callback) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: map._validateCallback()';} + + return __game.validateCallback(callback); + }; + + /* exposed methods */ + + this.refresh = wrapExposedMethod(function () { + if (__dom) { + this._display.clear(); + + var domHTML = __dom[0].outerHTML + .replace(/"/g, "'") + .replace(/]*)>/g, '
    ') + .replace(/]*)>/g, ''); + + this._display.renderDom(domHTML, __domCSS); + } else { + this._display.drawAll(this); + } + // rewrite any status messages + if (this._status) { + this._display.writeStatus(this._status); + } + __game.drawInventory(); + }, this); + + this.countObjects = wrapExposedMethod(function (type) { + var count = 0; + + // count static objects + for (var x = 0; x < this.getWidth(); x++) { + for (var y = 0; y < this.getHeight(); y++) { + if (__grid[x][y].type === type) { + count++; + } + } + } + + // count dynamic objects + __dynamicObjects.forEach(function (obj) { + if (obj.getType() === type) { + count++; + } + }) + + return count; + }, this); + + this.placeObject = wrapExposedMethod(function (x, y, type) { + var x = Math.floor(x); var y = Math.floor(y); + + if (!__objectDefinitions[type]) { + throw "There is no type of object named " + type + "!"; + } + var minLevel = __objectDefinitions[type].minimumLevel + if (minLevel && __game._currentLevel < minLevel) { + throw type.capitalize() + "s are not available until level " + minLevel; + } + + if (__player && x == __player.getX() && y == __player.getY()) { + throw "Can't place object on top of player!"; + } + + if (typeof(__grid[x]) === 'undefined' || typeof(__grid[x][y]) === 'undefined') { + return; + // throw "Not a valid location to place an object!"; + } + + if (__objectDefinitions[type].type === 'dynamic') { + // dynamic object + __dynamicObjects.push(new DynamicObject(this, type, x, y, __game)); + } else { + // static object + if (__grid[x][y].type === 'empty' || __grid[x][y].type === type || __allowOverwrite) { + __grid[x][y].type = type; + } else { + throw "There is already an object at (" + x + ", " + y + ")!"; + } + } + }, this); + + this.placePlayer = wrapExposedMethod(function (x, y) { + var x = Math.floor(x); var y = Math.floor(y); + + if (__player) { + throw "Can't place player twice!"; + } + + __player = new __game._playerPrototype(x, y, this, __game); + this._display.drawAll(this); + }, this); + + this.createFromGrid = wrapExposedMethod(function (grid, tiles, xOffset, yOffset) { + for (var y = 0; y < grid.length; y++) { + var line = grid[y]; + for (var x = 0; x < line.length; x++) { + var tile = line[x]; + var type = tiles[tile]; + if (type === 'player') { + this.placePlayer(x + xOffset, y + yOffset); + } else if (type) { + this.placeObject(x + xOffset, y + yOffset, type); + } + } + } + }, this); + + this.setSquareColor = wrapExposedMethod(function (x, y, bgColor) { + var x = Math.floor(x); var y = Math.floor(y); + + __grid[x][y].bgColor = bgColor; + }, this); + + this.defineObject = wrapExposedMethod(function (name, properties) { + if (__objectDefinitions[name]) { + throw "There is already a type of object named " + name + "!"; + } + + if (properties.interval && properties.interval < 100) { + throw "defineObject(): minimum interval is 100 milliseconds"; + } + + __objectDefinitions[name] = properties; + }, this); + + this.getObjectTypeAt = wrapExposedMethod(function (x, y) { + var x = Math.floor(x); var y = Math.floor(y); + + // Bazek: We should always check, if the coordinates are inside of map! + if (x >= 0 && x < this.getWidth() && y >= 0 && y < this.getHeight()) + return __grid[x][y].type; + else + return ''; + }, this); + + this.getAdjacentEmptyCells = wrapExposedMethod(function (x, y) { + var x = Math.floor(x); var y = Math.floor(y); + + var map = this; + var actions = ['right', 'down', 'left', 'up']; + var adjacentEmptyCells = []; + $.each(actions, function (i, action) { + switch (actions[i]) { + case 'right': + var child = [x+1, y]; + break; + case 'left': + var child = [x-1, y]; + break; + case 'down': + var child = [x, y+1]; + break; + case 'up': + var child = [x, y-1]; + break; + } + // Bazek: We need to check, if child is inside of map! + var childInsideMap = child[0] >= 0 && child[0] < map.getWidth() && child[1] >= 0 && child[1] < map.getHeight(); + if (childInsideMap && map.getObjectTypeAt(child[0], child[1]) === 'empty') { + adjacentEmptyCells.push([child, action]); + } + }); + return adjacentEmptyCells; + }, this); + + this.startTimer = wrapExposedMethod(function(timer, delay) { + if (!delay) { + throw "startTimer(): delay not specified" + } else if (delay < 25) { + throw "startTimer(): minimum delay is 25 milliseconds"; + } + var validate = this._validateCallback; + __intervals.push(setInterval(function(){validate(timer)}, delay)); + }, this); + + this.timeout = wrapExposedMethod(function(timer, delay) { + if (!delay) { + throw "timeout(): delay not specified" + } else if (delay < 25) { + throw "timeout(): minimum delay is 25 milliseconds"; + } + var validate = this._validateCallback; + __intervals.push(setTimeout(function(){validate(timer)}, delay)); + }, this); + + this.displayChapter = wrapExposedMethod(function(chapterName, cssClass) { + if (__game._displayedChapters.indexOf(chapterName) === -1) { + $('#chapter').html(chapterName.replace("\n","
    ")); + $('#chapter').removeClass().show(); + + if (cssClass) { + $('#chapter').addClass(cssClass); + } else { + __game._displayedChapters.push(chapterName); + } + + setTimeout(function () { + $('#chapter').fadeOut(); + }, 5 * 1000); + } + }, this); + + this.writeStatus = wrapExposedMethod(function(status) { + if (this._status) { + // refresh to hide the old status message + this._status = ""; + this.refresh(); + } + this._status = status; + this._display.writeStatus(status); + }, this); + + // used by validators + // returns true iff called at the start of the level (that is, on DummyMap) + // returns false iff called by validateCallback (that is, on the actual map) + this.isStartOfLevel = wrapExposedMethod(function () { + return this._dummy; + }, this); + + /* canvas-related stuff */ + + this.getCanvasContext = wrapExposedMethod(function() { + var ctx = $('#drawingCanvas')[0].getContext('2d'); + if(!this._dummy) { + var opts = this._display.getOptions(); + ctx.font = opts.fontSize+"px " +opts.fontFamily; + } + return ctx; + }, this); + + this.getCanvasCoords = wrapExposedMethod(function() { + var x, y; + if(arguments.length == 1) { + var obj = arguments[0]; + x = obj.getX(); + y = obj.getY(); + } else { + x = arguments[0]; + y = arguments[1]; + } + var canvas = $('#drawingCanvas')[0]; + return { + x: (x + 0.5) * canvas.width / __game._dimensions.width, + y: (y + 0.5) * canvas.height / __game._dimensions.height + }; + }, this); + + this.getRandomColor = wrapExposedMethod(function(start, end) { + var mean = [ + Math.floor((start[0] + end[0]) / 2), + Math.floor((start[1] + end[1]) / 2), + Math.floor((start[2] + end[2]) / 2) + ]; + var std = [ + Math.floor((end[0] - start[0]) / 2), + Math.floor((end[1] - start[1]) / 2), + Math.floor((end[2] - start[2]) / 2) + ]; + return ROT.Color.toHex(ROT.Color.randomize(mean, std)); + }, this); + + this.createLine = wrapExposedMethod(function(start, end, callback) { + __lines.push({'start': start, 'end': end, 'callback': callback}); + }, this); + + this.testLineCollisions = wrapExposedMethod(function(player) { + var threshold = 7; + var playerCoords = this.getCanvasCoords(player); + __lines.forEach(function (line) { + if (pDistance(playerCoords.x, playerCoords.y, + line.start[0], line.start[1], + line.end[0], line.end[1]) < threshold) { + __game.validateCallback(function() { + line.callback(__player); + }); + } + }) + }, this); + + /* for DOM manipulation level */ + + this.getDOM = wrapExposedMethod(function () { + return __dom; + }) + + this.createFromDOM = wrapExposedMethod(function(dom) { + __dom = dom; + }, this); + + this.updateDOM = wrapExposedMethod(function(dom) { + __dom = dom; + }, this); + + this.overrideKey = wrapExposedMethod(function(keyName, callback) { + this._overrideKeys[keyName] = callback; + }, this); + + /* validators */ + + this.validateAtLeastXObjects = wrapExposedMethod(function(num, type) { + var count = this.countObjects(type); + if (count < num) { + throw 'Not enough ' + type + 's on the map! Expected: ' + num + ', found: ' + count; + } + }, this); + + this.validateAtMostXObjects = wrapExposedMethod(function(num, type) { + var count = this.countObjects(type); + if (count > num) { + throw 'Too many ' + type + 's on the map! Expected: ' + num + ', found: ' + count; + } + }, this); + + this.validateExactlyXManyObjects = wrapExposedMethod(function(num, type) { + var count = this.countObjects(type); + if (count != num) { + throw 'Wrong number of ' + type + 's on the map! Expected: ' + num + ', found: ' + count; + } + }, this); + + this.validateAtMostXDynamicObjects = wrapExposedMethod(function(num) { + var count = this.getDynamicObjects().length; + if (count > num) { + throw 'Too many dynamic objects on the map! Expected: ' + num + ', found: ' + count; + } + }, this); + + this.validateNoTimers = wrapExposedMethod(function() { + var count = this._countTimers(); + if (count > 0) { + throw 'Too many timers set on the map! Expected: 0, found: ' + count; + } + }, this); + + this.validateAtLeastXLines = wrapExposedMethod(function(num) { + var count = this._getLines().length; + if (count < num) { + throw 'Not enough lines on the map! Expected: ' + num + ', found: ' + count; + } + }, this); + + /* initialization */ + + this._reset(); + + // call secureObject to prevent user code from tampering with private attributes + __game.secureObject(this, "map"); +} diff --git a/scripts/objects.js b/scripts/objects.js new file mode 100644 index 0000000000000000000000000000000000000000..1ccff8d32ea6d1bb5308474faf5d34ffef406019 --- /dev/null +++ b/scripts/objects.js @@ -0,0 +1,259 @@ +/* +Objects can have the following parameters: + color: '#fff' by default + impassable: true if it blocks the player from movement (false by default) + onCollision: function (player) called when player moves over the object + onPickUp: function (player) called when player picks up the item + symbol: Unicode character representing the object + type: 'item' or null +*/ + +// used by bonus levels 01 through 04 +function moveToward(obj, type) { + var target = obj.findNearest(type); + var leftDist = obj.getX() - target.x; + var upDist = obj.getY() - target.y; + + var direction; + if (upDist == 0 && leftDist == 0) { + return; + } + if (upDist > 0 && upDist >= leftDist) { + direction = 'up'; + } else if (upDist < 0 && upDist < leftDist) { + direction = 'down'; + } else if (leftDist > 0 && leftDist >= upDist) { + direction = 'left'; + } else { + direction = 'right'; + } + + if (obj.canMove(direction)) { + obj.move(direction); + } +} + +// used by bonus levels 01 through 04 +function followAndKeepDistance(obj, type) { + var target = obj.findNearest(type); + var leftDist = obj.getX() - target.x; + var upDist = obj.getY() - target.y; + + if (Math.abs(upDist) < 2 && Math.abs(leftDist) < 4 + || Math.abs(leftDist) < 2 && Math.abs(upDist) < 4) { + return; + } + var direction; + if (upDist > 0 && upDist >= leftDist) { + direction = 'up'; + } else if (upDist < 0 && upDist < leftDist) { + direction = 'down'; + } else if (leftDist > 0 && leftDist >= upDist) { + direction = 'left'; + } else { + direction = 'right'; + } + + if (obj.canMove(direction)) { + obj.move(direction); + } +} + +// used by bonus levels 01 through 04 +function killPlayerIfTooFar(obj, map) { + var target = obj.findNearest('player'); + var leftDist = obj.getX() - target.x; + var upDist = obj.getY() - target.y; + + if (Math.abs(upDist) > 8 || Math.abs(leftDist) > 8) { + map.getPlayer().killedBy('"suspicious circumstances"'); + } +} + +Game.prototype.getListOfObjects = function () { + var game = this; + return { + // special + + 'empty' : { + 'symbol': ' ', + 'impassableFor': ['raft'] + }, + + 'player' : { + 'symbol': '@', + 'color': '#0f0' + }, + + 'exit' : { + 'symbol' : String.fromCharCode(0x2395), // ⎕ + 'color': '#0ff', + 'onCollision': function (player) { + if (!game.map.finalLevel) { + game._callUnexposedMethod(function () { + game._moveToNextLevel(); + }); + } + } + }, + + // obstacles + + 'block': { + 'symbol': '#', + 'color': '#999', + 'impassable': true + }, + + 'tree': { + 'symbol': '♣', + 'color': '#080', + 'impassable': true + }, + + 'mine': { + 'symbol': ' ', + 'onCollision': function (player) { + player.killedBy('a hidden mine'); + } + }, + + 'trap': { + 'type': 'dynamic', + 'symbol': '*', + 'color': '#f00', + 'onCollision': function (player, me) { + player.killedBy('a trap'); + }, + 'behavior': null + }, + + 'teleporter': { + 'type': 'dynamic', + 'symbol' : String.fromCharCode(0x2395), // ⎕ + 'color': '#f0f', + 'onCollision': function (player, me) { + if (!player._hasTeleported) { + if (me.target) { + game._callUnexposedMethod(function () { + player._moveTo(me.target); + }); + } else { + throw 'TeleporterError: Missing target for teleporter' + } + } + player._hasTeleported = true; + }, + 'behavior': null + }, + + // items + + 'computer': { + 'type': 'item', + 'symbol': String.fromCharCode(0x2318), // ⌘ + 'color': '#ccc', + 'onPickUp': function (player) { + $('#editorPane, #savedLevelMsg').fadeIn(); + game.editor.refresh(); + game.map.writeStatus('You have picked up the computer!'); + }, + 'onDrop': function () { + $('#editorPane, #savedLevelMsg').hide(); + } + }, + + 'phone': { + 'type': 'item', + 'minimumLevel': 7, + 'symbol': String.fromCharCode(0x260E), // ☎ + 'onPickUp': function (player) { + game.map.writeStatus('You have picked up the function phone!'); + $('#phoneButton').show(); + }, + 'onDrop': function () { + $('#phoneButton').hide(); + } + }, + + 'redKey': { + 'type': 'item', + 'minimumLevel': 11, + 'symbol': 'k', + 'color': 'red', + 'onPickUp': function (player) { + game.map.writeStatus('You have picked up a red key!'); + } + }, + + 'greenKey': { + 'type': 'item', + 'minimumLevel': 12, + 'symbol': 'k', + 'color': '#0f0', + 'onPickUp': function (player) { + game.map.writeStatus('You have picked up a green key!'); + } + }, + + 'blueKey': { + 'type': 'item', + 'minimumLevel': 13, + 'symbol': 'k', + 'color': '#06f', + 'onPickUp': function (player) { + game.map.writeStatus('You have picked up a blue key!'); + } + }, + + 'yellowKey': { + 'type': 'item', + 'minimumLevel': 14, + 'symbol': 'k', + 'color': 'yellow', + 'onPickUp': function (player) { + game.map.writeStatus('You have picked up a yellow key!'); + } + }, + + 'theAlgorithm': { + 'minimumLevel': 14, + 'type': 'item', + 'symbol': 'A', + 'color': 'white', + 'onPickUp': function (player) { + game.map.writeStatus('You have picked up the Algorithm!'); + }, + 'onDrop': function () { + game.map.writeStatus('You have lost the Algorithm!'); + } + }, + + // used by bonus levels 01 through 04 + 'eye': { + 'type': 'dynamic', + 'symbol': 'E', + 'color': 'red', + 'behavior': function (me) { + followAndKeepDistance(me, 'player'); + killPlayerIfTooFar(me, game.map); + }, + 'onCollision': function (player) { + player.killedBy('"the eye"'); + }, + }, + + // used by bonus levels 01 through 04 + 'guard': { + 'type': 'dynamic', + 'symbol': 'd', + 'color': 'red', + 'behavior': function (me) { + moveToward(me, 'player'); + }, + 'onCollision': function (player) { + player.killedBy('a guard drone'); + }, + } + }; +}; diff --git a/scripts/player.js b/scripts/player.js new file mode 100644 index 0000000000000000000000000000000000000000..06f6ca7fb9e59e2e1556a948e0e631cb151ce1cf --- /dev/null +++ b/scripts/player.js @@ -0,0 +1,216 @@ +function Player(x, y, __map, __game) { + /* private variables */ + + var __x = x; + var __y = y; + var __color = "#0f0"; + var __lastMoveDirection = ''; + + var __display = __map._display; + + /* unexposed variables */ + + this._canMove = false; + + /* wrapper */ + + function wrapExposedMethod(f, player) { + return function () { + var args = arguments; + return __game._callUnexposedMethod(function () { + return f.apply(player, args); + }); + }; + }; + + /* exposed getters/setters */ + + this.getX = function () { return __x; }; + this.getY = function () { return __y; }; + this.getColor = function () { return __color; }; + this.getLastMoveDirection = function() { return __lastMoveDirection; }; + + this.setColor = wrapExposedMethod(function (c) { + __color = c; + __display.drawAll(__map); + }); + + /* unexposed methods */ + + // (used for teleporters) + this._moveTo = function (dynamicObject) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: player._moveTo()';} + + // no safety checks or anything + // this method is about as safe as a war zone + __x = dynamicObject.getX(); + __y = dynamicObject.getY(); + __display.drawAll(__map); + + // play teleporter sound + __game.sound.playSound('blip'); + }; + + this._afterMove = function (x, y) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: player._afterMove()';} + + var player = this; + + this._hasTeleported = false; // necessary to prevent bugs with teleportation + + __map._hideChapter(); + __map._moveAllDynamicObjects(); + + var onTransport = false; + + // check for collision with transport object + for (var i = 0; i < __map.getDynamicObjects().length; i++) { + var object = __map.getDynamicObjects()[i]; + if (object.getX() === x && object.getY() === y) { + var objectDef = __map._getObjectDefinition(object.getType()); + if (objectDef.transport) { + onTransport = true; + } + } + } + + // check for collision with static object UNLESS + // we are on a transport + if (!onTransport) { + var objectName = __map._getGrid()[x][y].type; + var objectDef = __map._getObjectDefinition(objectName); + if (objectDef.type === 'item') { + this._pickUpItem(objectName, objectDef); + } else if (objectDef.onCollision) { + __game.validateCallback(function () { + objectDef.onCollision(player); + }); + } + } + + // check for collision with any lines on the map + __map.testLineCollisions(this); + + // don't run checkObjective if validation has already failed to prevent duplicate `Validation failed` errors + if (!__map._callbackValidationFailed) { + // check for nonstandard victory condition (e.g. DOM level) + __game._checkObjective() + } + }; + + this._pickUpItem = function (itemName, object) { + if (__game._isPlayerCodeRunning()) { throw 'Forbidden method call: player._pickUpItem()';} + + var player = this; + + __game.addToInventory(itemName); + __map._removeItemFromMap(__x, __y, itemName); + __map.refresh(); + __game.sound.playSound('pickup'); + + if (object.onPickUp) { + __game.validateCallback(function () { + object.onPickUp(player); + }); + } + }; + + /* exposed methods */ + + this.atLocation = wrapExposedMethod(function (x, y) { + return (__x === x && __y === y); + }, this); + + this.move = wrapExposedMethod(function (direction, fromKeyboard) { + if (!this._canMove) { // mainly for key delay + return false; + } + + if (fromKeyboard) { + // clear any status text + __map._status = ""; + if (__map._overrideKeys[direction]) { + try { + __game.validateCallback(__map._overrideKeys[direction], true); + + __map.refresh(); + this._canMove = false; + __map._reenableMovementForPlayer(this); // (key delay can vary by map) + this._afterMove(__x, __y); + } catch (e) { + } + return; + } + } + + var new__x; + var new__y; + if (direction === 'up') { + new__x = __x; + new__y = __y - 1; + } + else if (direction === 'down') { + new__x = __x; + new__y = __y + 1; + } + else if (direction === 'left') { + new__x = __x - 1; + new__y = __y; + } + else if (direction === 'right') { + new__x = __x + 1; + new__y = __y; + } + else if (direction === 'rest') { + new__x = __x; + new__y = __y; + } + else if (direction === 'funcPhone') { + __game.usePhone(); + return; + } + + if (__map._canMoveTo(new__x, new__y)) { + __x = new__x; + __y = new__y; + + __map.refresh(); + + this._canMove = false; + + __lastMoveDirection = direction; + this._afterMove(__x, __y); + + __map._reenableMovementForPlayer(this); // (key delay can vary by map) + } else { + // play bump sound + __game.sound.playSound('select'); + } + }, this); + + this.killedBy = wrapExposedMethod(function (killer) { + __game.sound.playSound('hurt'); + __game._restartLevel(); + + __map.displayChapter('You have been killed by \n' + killer + '!', 'death'); + }, this); + + this.hasItem = wrapExposedMethod(function (itemName) { + return __game.checkInventory(itemName); + }, this); + + this.removeItem = wrapExposedMethod(function (itemName) { + var object = __game.objects[itemName]; + + __game.removeFromInventory(itemName); + __game.sound.playSound('blip'); + }, this); + + this.setPhoneCallback = wrapExposedMethod(function(func) { + this._phoneFunc = func; + }, this); + + // call secureObject to prevent user code from tampering with private attributes + __game.secureObject(this,"player"); + +} diff --git a/scripts/reference.js b/scripts/reference.js new file mode 100644 index 0000000000000000000000000000000000000000..64bdcf6bd31557ee82b8a8eb8e987692dd2c31fe --- /dev/null +++ b/scripts/reference.js @@ -0,0 +1,492 @@ +Game.prototype.reference = { + 'canvas.beginPath': { + 'name': 'canvasContext.beginPath()', + 'category': 'canvas', + 'type': 'method', + 'description': 'Begins drawing a new shape.' + }, + 'canvas.lineTo': { + 'name': 'canvasContext.lineTo(x, y)', + 'category': 'canvas', + 'type': 'method', + 'description': 'Sets the end coordinates of a line.' + }, + 'canvas.lineWidth': { + 'name': 'canvasContext.lineWidth', + 'category': 'canvas', + 'type': 'property', + 'description': 'Determines the width of the next lines drawn.' + }, + 'canvas.moveTo': { + 'name': 'canvasContext.moveTo(x, y)', + 'category': 'canvas', + 'type': 'method', + 'description': 'Sets the start coordinates of a line.' + }, + 'canvas.stroke': { + 'name': 'canvasContext.stroke()', + 'category': 'canvas', + 'type': 'method', + 'description': 'Draws a line whose coordinates have been defined by lineTo and moveTo.' + }, + 'canvas.strokeStyle': { + 'name': 'canvasContext.strokeStyle', + 'category': 'canvas', + 'type': 'property', + 'description': 'Determines the color (and, optionally, other properties) of the next lines drawn.' + }, + 'canvas.fillStyle': { + 'name': 'canvasContext.fillStyle', + 'category': 'canvas', + 'type': 'property', + 'description': 'Determines the color (and, optionally, other properties) of the text drawn with fillText.' + }, + 'canvas.fillText': { + 'name': 'canvasContext.fillText(text, x, y)', + 'category': 'canvas', + 'type': 'method', + 'description': 'Draws a given piece of text, starting at specified coordinates, to to the canvas', + }, + 'global.$': { + 'name': '$(html)', + 'category': 'global', + 'type': 'method', + 'description': 'When passed an HTML string, $ returns a corresponding jQuery instance.' + }, + 'global.objective': { + 'name': 'objective(map)', + 'category': 'global', + 'type': 'method', + 'description': 'The player exits the level as soon as this method returns true.' + }, + 'global.onExit': { + 'name': 'onExit(map)', + 'category': 'global', + 'type': 'method', + 'description': 'The player can exit the level only if this method returns true.' + }, + 'global.startLevel': { + 'name': 'startLevel(map)', + 'category': 'global', + 'type': 'method', + 'description': 'This method is called when the level loads.' + }, + 'global.validateLevel': { + 'name': 'validateLevel(map)', + 'category': 'global', + 'type': 'method', + 'description': 'The level can be loaded only if this method returns true.' + }, + 'ROT.Map.DividedMaze': { + 'name': 'ROT.Map.DividedMaze(width, height)', + 'category': 'global', + 'type': 'method', + 'description': 'Instantiates a Maze object of given width and height. The Maze object can create a maze by calling maze.create(callback), where the callback is a function that accepts (x, y, mapValue) and performs some action for each point in a grid, where mapValue is a boolean that is true if and only if the given point is part of the maze.' + }, + + 'jQuery.addClass': { + 'name': 'jQueryObject.addClass(class)', + 'category': 'jQuery', + 'type': 'method', + 'description': 'Adds the given CSS class to the DOM element(s) specified by the jQuery object.' + }, + 'jQuery.children': { + 'name': 'jQueryObject.children()', + 'category': 'jQuery', + 'type': 'method', + 'description': 'Returns the children of the DOM element specified by the jQuery object, as a jQuery array.' + }, + 'jQuery.find': { + 'name': 'jQueryObject.find(selector)', + 'category': 'jQuery', + 'type': 'method', + 'description': 'Returns all elements in the DOM tree specified by the jQuery object that match the given CSS selector, as a jQuery array.' + }, + 'jQuery.first': { + 'name': 'jQueryObject.first()', + 'category': 'jQuery', + 'type': 'method', + 'description': 'Returns the first element of a jQuery array.' + }, + 'jQuery.hasClass': { + 'name': 'jQueryObject.hasClass(class)', + 'category': 'jQuery', + 'type': 'method', + 'description': 'Returns true if and only if the DOM element specified by the jQuery object has the given CSS class.' + }, + 'jQuery.length': { + 'name': 'jQueryObject.length', + 'category': 'jQuery', + 'type': 'property', + 'description': 'Returns the number of elements in a jQuery array.' + }, + 'jQuery.next': { + 'name': 'jQueryObject.next()', + 'category': 'jQuery', + 'type': 'property', + 'description': 'Returns the next sibling of the DOM element specified by the jQuery object.' + }, + 'jQuery.parent': { + 'name': 'jQueryObject.parent()', + 'category': 'jQuery', + 'type': 'method', + 'description': 'Returns the parent of the DOM element specified by the jQuery object.' + }, + 'jQuery.prev': { + 'name': 'jQueryObject.prev()', + 'category': 'jQuery', + 'type': 'property', + 'description': 'Returns the previous sibling of the DOM element specified by the jQuery object.' + }, + 'jQuery.removeClass': { + 'name': 'jQueryObject.removeClass(class)', + 'category': 'jQuery', + 'type': 'method', + 'description': 'Removes the given CSS class from the DOM element(s) specified by the jQuery object.' + }, + + 'map.countObjects': { + 'name': 'map.countObjects(objectType)', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the number of objects of the given type on the map.' + }, + 'map.createFromDOM': { + 'name': 'map.createFromDOM($html)', + 'category': 'map', + 'type': 'method', + 'description': 'Creates the map from a jQuery instance, rendering the map as a DOM (document object model) rather than a grid.' + }, + 'map.createFromGrid': { + 'name': 'map.createFromGrid(grid, tiles, xOffset, yOffset)', + 'category': 'map', + 'type': 'method', + 'description': 'Places objects on the map corresponding to their position on the grid (an array of strings), with mappings as defined in tiles (a dictionary of character -> object type mappings), at the given offset from the top-left corner of the map.' + }, + 'map.createLine': { + 'name': 'map.createLine([x1, x2], [y1 y2], callback)', + 'category': 'map', + 'type': 'method', + 'description': 'Places a line on the map between the given points, that triggers the given callback when the player touches it. (Note that the line is invisible: createLine does not draw anything to the canvas.)' + }, + 'map.displayChapter': { + 'name': 'map.displayChapter(chapter)', + 'category': 'map', + 'type': 'method', + 'description': 'Displays the given chapter name.' + }, + 'map.defineObject': { + 'name': 'map.defineObject(type, properties)', + 'category': 'map', + 'type': 'method', + 'description': 'Defines a new type of object with the given properties. Note that type definitions created with map.defineObject only persist in the scope of the level.' + }, + 'map.getAdjacentEmptyCells': { + 'name': 'map.getAdjacentEmptyCells(x, y)', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the empty cells adjacent to the cell at the given coordinates (if any), as an array of items of the form [[x, y], direction], where (x, y) are the coordinates of each empty cell, and direction is the direction from the given cell to each empty cell ("left", "right", "up", or "down").' + }, + 'map.getCanvasContext': { + 'name': 'map.getCanvasContext()', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the 2D drawing context of the canvas overlaying the map.' + }, + 'map.getCanvasCoords': { + 'name': 'map.getCanvasCoords(obj) / map.getCanvasCoords(x, y)', + 'category': 'map', + 'type': 'method', + 'description': 'Returns {"x": x, "y": y}, where x and y are the respective coordinates of the given object or grid position on the canvas returned by map.getCanvasContext().' + }, + 'map.getDOM': { + 'name': 'map.getDOM()', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the jQuery instance representing the map.' + }, + 'map.getDynamicObjects': { + 'name': 'map.getDynamicObjects()', + 'category': 'map', + 'type': 'method', + 'description': 'Returns all dynamic objects currently on the map.' + }, + 'map.getHeight': { + 'name': 'map.getHeight()', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the height of the map, in cells.' + }, + 'map.getObjectTypeAt': { + 'name': 'map.getObjectTypeAt(x, y)', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the type of the object at the given coordinates (or "empty" if there is no object there).' + }, + 'map.getPlayer': { + 'name': 'map.getPlayer()', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the Player object.' + }, + 'map.getRandomColor': { + 'name': 'map.getRandomColor(start, end)', + 'category': 'map', + 'type': 'method', + 'description': 'Returns a hexadecimal string representing a random color in between the start and end colors. The start and end colors must be arrays of the form [R, G, B], where R, G, and B are decimal integers.' + }, + 'map.getWidth': { + 'name': 'map.getWidth()', + 'category': 'map', + 'type': 'method', + 'description': 'Returns the width of the map, in cells.' + }, + 'map.isStartOfLevel': { + 'name': 'map.isStartOfLevel()', + 'category': 'map', + 'type': 'method', + 'description': 'Returns true if called while a level is starting.' + }, + 'map.overrideKey': { + 'name': 'map.overrideKey(key, callback)', + 'category': 'map', + 'type': 'method', + 'description': 'Overrides the action performed by pressing the given key (left, right, up, or down).' + }, + 'map.placeObject': { + 'name': 'map.placeObject(x, y, objectType)', + 'category': 'map', + 'type': 'method', + 'description': 'Places an object of the given type at the given coordinates.' + }, + 'map.placePlayer': { + 'name': 'map.placePlayer(x, y)', + 'category': 'map', + 'type': 'method', + 'description': 'Places the player at the given coordinates.' + }, + 'map.setSquareColor': { + 'name': 'map.setSquareColor(x, y, color)', + 'category': 'map', + 'type': 'method', + 'description': 'Sets the background color of the given square.' + }, + 'map.timeout': { + 'name': 'map.timeout(callback, delay)', + 'category': 'map', + 'type': 'method', + 'description': 'Starts a timer (c.f. setTimeout) of the given delay, in milliseconds (minimum 25 ms). Unlike map.startTimer, the callback will only run once.' + }, + 'map.startTimer': { + 'name': 'map.startTimer(callback, delay)', + 'category': 'map', + 'type': 'method', + 'description': 'Starts a timer (c.f. setInterval) of the given delay, in milliseconds (minimum 25 ms).' + }, + 'map.updateDOM': { + 'name': 'map.updateDOM($html)', + 'category': 'map', + 'type': 'method', + 'description': 'Updates the jQuery instance representing the map.' + }, + 'map.validateAtLeastXLines': { + 'name': 'map.validateAtLeastXLines(num)', + 'category': 'map', + 'type': 'method', + 'description': 'Raises an exception if there are not at least num lines (created by map.createLine) on the map.' + }, + 'map.validateAtLeastXObjects': { + 'name': 'map.validateAtLeastXObjects(num, objectType)', + 'category': 'map', + 'type': 'method', + 'description': 'Raises an exception if there are not at least num objects of type objectType on the map.' + }, + 'map.validateAtMostXDynamicObjects': { + 'name': 'map.validateExactlyXManyObjects(num)', + 'category': 'map', + 'type': 'method', + 'description': 'Raises an exception if there are more than num dynamic objects on the map.' + }, + 'map.validateExactlyXManyObjects': { + 'name': 'map.validateExactlyXManyObjects(num, objectType)', + 'category': 'map', + 'type': 'method', + 'description': 'Raises an exception if there are not exactly num objects of type objectType on the map.' + }, + 'map.validateNoTimers': { + 'name': 'map.validateNoTimers()', + 'category': 'map', + 'type': 'method', + 'description': 'Raises an exception if there are any timers currently set with map.startTimer.' + }, + 'map.writeStatus': { + 'name': 'map.writeStatus(message)', + 'category': 'map', + 'type': 'method', + 'description': 'Displays a message at the bottom of the map.' + }, + + 'object.behavior': { + 'name': 'object.behavior = function (object)', + 'category': 'object', + 'type': 'property', + 'description': '(For dynamic objects only.) The function that is executed each time it is this object\'s turn.' + }, + 'object.canMove': { + 'name': 'object.canMove(direction)', + 'category': 'object', + 'type': 'method', + 'description': '(For dynamic objects only.) Returns true if (and only if) the object is able to move one square in the given direction, which can be "left", "right", "up", or "down".' + }, + 'object.color': { + 'name': 'object.color', + 'category': 'object', + 'type': 'property', + 'description': 'The color of the object\'s symbol on the map.' + }, + 'object.findNearest': { + 'name': 'object.findNearest(type)', + 'category': 'object', + 'type': 'method', + 'description': '(For dynamic objects only.) Returns the x and y coordinates of the nearest object of the given type to this object, as a hash.' + }, + 'object.getX': { + 'name': 'object.getX()', + 'category': 'object', + 'type': 'method', + 'description': '(For dynamic objects only.) Returns the x-coordinate of the object.' + }, + 'object.getY': { + 'name': 'object.getY()', + 'category': 'object', + 'type': 'method', + 'description': '(For dynamic objects only.) Returns the y-coordinate of the object.' + }, + 'object.giveItemTo': { + 'name': 'object.giveItemTo(target, item)', + 'category': 'object', + 'type': 'method', + 'description': '(For dynamic objects only.) Gives the given item to the target (generally, the player). Can only be done if the object and the player have just collided.' + }, + 'object.impassable': { + 'name': 'object.impassable = function (player, object)', + 'category': 'object', + 'type': 'property', + 'description': '(For non-dynamic objects only.) The function that determines whether or not the player can pass through this object.' + }, + 'object.move': { + 'name': 'object.move(direction)', + 'category': 'object', + 'type': 'method', + 'description': '(For dynamic objects only.) Moves the object one square in the given direction, which can be "left", "right", "up", or "down". An object can only move once per turn.' + }, + 'object.onCollision': { + 'name': 'object.onCollision = function (player)', + 'category': 'object', + 'type': 'property', + 'description': 'The function that is executed when this object touches the player.' + }, + 'object.onDestroy': { + 'name': 'object.onDestroy = function (object)', + 'category': 'object', + 'type': 'property', + 'description': '(For dynamic objects only.) The function that is executed when this object is destroyed.' + }, + 'object.projectile': { + 'name': 'object.projectile', + 'category': 'object', + 'type': 'property', + 'description': '(For dynamic objects only.) If true, this object destroys any dynamic object (or player) that it collides with, and is itself destroyed when it collides with anything.' + }, + 'object.pushable': { + 'name': 'object.pushable', + 'category': 'object', + 'type': 'property', + 'description': '(For dynamic objects only.) If true, this object can be pushed by the player.' + }, + 'object.symbol': { + 'name': 'object.symbol', + 'category': 'object', + 'type': 'property', + 'description': 'The object\'s symbol on the map.' + }, + 'object.setTarget': { + 'name': 'object.setTarget()', + 'category': 'object', + 'type': 'method', + 'description': '(For teleporters only.) Sets the destination of this teleporter.' + }, + 'object.type': { + 'name': 'object.type', + 'category': 'object', + 'type': 'property', + 'description': 'Can be "item", "dynamic", or none. If "dynamic", then this object can move on turns that run each time that the player moves. If "item", then this object can be picked up.' + }, + + 'player.atLocation': { + 'name': 'player.atLocation(x, y)', + 'category': 'player', + 'type': 'method', + 'description': 'Returns true if and only if the player is at the given location.' + }, + 'player.getColor': { + 'name': 'player.getColor()', + 'category': 'player', + 'type': 'method', + 'description': 'Returns the color of the player.' + }, + 'player.getLastMoveDirection': { + 'name': 'player.getLastMoveDirection()', + 'category': 'player', + 'type': 'method', + 'description': 'Returns the direction of last move by the player.' + }, + 'player.getX': { + 'name': 'player.getX()', + 'category': 'player', + 'type': 'method', + 'description': 'Returns the x-coordinate of the player.' + }, + 'player.getY': { + 'name': 'player.getY()', + 'category': 'player', + 'type': 'method', + 'description': 'Returns the y-coordinate of the player.' + }, + 'player.hasItem': { + 'name': 'player.hasItem(itemType)', + 'category': 'player', + 'type': 'method', + 'description': 'Returns true if and only if the player has the given item.' + }, + 'player.killedBy': { + 'name': 'player.killedBy(text)', + 'category': 'player', + 'type': 'method', + 'description': 'Kills the player and displays the given text as the cause of death.' + }, + 'player.move': { + 'name': 'player.move(direction)', + 'category': 'player', + 'type': 'method', + 'description': 'Moves the player one square in the given direction. The player can only move once in a given function.' + }, + 'player.removeItem': { + 'name': 'player.removeItem(itemType)', + 'category': 'player', + 'type': 'method', + 'description': 'Removes the given item from the player\'s inventory, if the player has the given item.' + }, + 'player.setColor': { + 'name': 'player.setColor(color)', + 'category': 'player', + 'type': 'method', + 'description': 'Sets the color of the player.' + }, + 'player.setPhoneCallback': { + 'name': 'player.setPhoneCallback(callback)', + 'category': 'player', + 'type': 'method', + 'description': 'Sets the function that is executed when the player uses the function phone.' + } +}; diff --git a/scripts/sound.js b/scripts/sound.js new file mode 100644 index 0000000000000000000000000000000000000000..ac92a47f57d8bb48e988bcbc67e2a9702fb4ed44 --- /dev/null +++ b/scripts/sound.js @@ -0,0 +1,238 @@ +function Sound(source) { + this.tracks = { + 'Adversity': { + path: "music/Adversity.mp3", + artist: "Seropard", + title: "Adversity", + url: "https://soundcloud.com/seropard" + }, + 'Beach Wedding Dance': { + path: "music/Rolemusic_-_07_-_Beach_Wedding_Dance.mp3", + artist: "Rolemusic", + title: "Beach Wedding Dance", + url: "https://soundcloud.com/rolemusic" + }, + 'BossLoop': { + path: "music/Boss Loop 1.mp3", + artist: "Essa", + title: "Boss Loop 1", + url: "http://www.youtube.com/user/Essasmusic" + }, + 'Brazil': { + path: "music/Vernon_Lenoir_-_Brazilicon_alley.mp3", + artist: "Vernon Lenoir", + title: "Brazilicon Alley", + url: "http://vernonlenoir.wordpress.com/" + }, + 'Chip': { + path: "music/ThatAndyGuy-Chip-loop.mp3", + artist: "That Andy Guy", + title: "Da Funk Do You Know 'bout Chip?", + url: "https://soundcloud.com/that-andy-guy" + }, + 'cloudy_sin': { + path: "music/intricate_cloudy_sin.mp3", + artist: "iNTRICATE", + title: "cloudy sin", + url: "https://soundcloud.com/stk13" + }, + 'Come and Find Me': { + path: "music/Eric_Skiff_-_09_-_Come_and_Find_Me_-_B_mix.mp3", + artist: "Eric Skiff", + title: "Come and Find Me", + url: "http://ericskiff.com/" + }, + 'coming soon': { + path: "music/Fex_coming_soon.mp3", + artist: "Fex", + title: "coming soon", + url: "http://artistserver.com/Fex" + }, + 'Comme Des Orages': { + path: "music/Obsibilo_-_02_-_Comme_Des_Orages.mp3", + artist: "Obsibilo", + title: "Comme Des Orages", + url: "http://freemusicarchive.org/music/Obsibilo/" + }, + 'conspiracy': { + path: "music/conspiracy_bitcrusher_final.mp3", + artist: "Mike and Alan", + title: "Conspiracy", + url: "https://www.facebook.com/MicAndAlan" + }, + 'Death Destroyer': { + path: "music/BLEO_-_02_-_Death_Destroyer_Radio_Edit_feat_Rhinostrich.mp3", + artist: "BLEO feat Rhinostrich", + title: "Death Destroyer (Radio Edit)", + url: "http://bleo.dummydrome.com/" + }, + 'GameScratch': { + path: "music/DmitryMazin-GameScratch.mp3", + artist: "Dmitry Mazin", + title: "Dynamic Punctuality", + url: "https://soundcloud.com/dmitry-mazin" + }, + 'gurh': { + path: "music/gurh.mp3", + artist: "Dmitry Mazin", + title: "Dmitry's Thing #2", + url: "https://soundcloud.com/dmitry-mazin" + }, + 'Messeah': { + path: "music/RoccoW_-_Messeah.mp3", + artist: "RoccoW", + title: "Messeah", + url: "https://soundcloud.com/roccow" + }, + 'Night Owl': { + path: "music/Broke_For_Free_-_01_-_Night_Owl.mp3", + artist: "Broke for Free", + title: "Night Owl", + url: "http://brokeforfree.com/" + }, + 'Obscure Terrain': { + path: "music/Revolution_Void_-_08_-_Obscure_Terrain.mp3", + artist: "Revolution Void", + title: "Obscure Terrain", + url: "http://revolutionvoid.com/" + }, + 'Searching': { + path: "music/Eric_Skiff_-_06_-_Searching.mp3", + artist: "Eric Skiff", + title: "Searching", + url: "http://ericskiff.com/" + }, + 'Slimeball Vomit': { + path: "music/Various_Artists_-_15_-_Slimeball_vomit.mp3", + artist: "Radio Scotvoid", + title: "Slimeball Vomit", + url: "https://soundcloud.com/radio-scotvoid" + }, + 'Soixante-8': { + path: "music/Obsibilo_-_Soixante-8.mp3", + artist: "Obsibilo", + title: "Soixante-8", + url: "http://freemusicarchive.org/music/Obsibilo/" + }, + 'Tart': { + path: "music/BLEO_-_02_-_Tart_Pts_1__2_feat_KeFF.mp3", + artist: "BLEO feat KeFF", + title: "Tart (Pts 1-2)", + url: "http://bleo.dummydrome.com/" + }, + 'The Green': { + path: "music/Yonnie_The_Green.mp3", + artist: "Jonathan Holliday", + title: "The Green", + url: "http://www.soundclick.com/bands/default.cfm?bandID=836578" + }, + 'The_Waves_Call_Her_Name': { + path: "music/Sycamore_Drive_-_03_-_The_Waves_Call_Her_Name.mp3", + artist: "Sycamore Drive", + title: "The Waves Call Her Name", + url: "http://sycamoredrive.bandcamp.com/" + }, + 'Y': { + path: "music/Tortue_Super_Sonic_-_11_-_Y.mp3", + artist: "Tortue Super Sonic", + title: "Y", + url: "https://soundcloud.com/tss-tortue-super-sonic" + } + }; + + this.defaultTracks = [ // (not currently used, as all levels now have explicit tracks) + 'GameScratch', + 'Y', + 'Searching', + 'Soixante-8', + 'Come and Find Me' + ]; + + this.sources = { + 'local': '', + 'cloudfront': 'http://dk93t8qfl63bu.cloudfront.net/' + }; + + this.bgPlayerElt = $("#jquery_bgPlayer"); + this.soundPlayerElt = $("#jquery_soundPlayer"); + this.muted = false; + this.currentLevelNum = -1; + + this.init = function() { + var sound = this; + + this.source = this.sources[source]; + + this.bgPlayerElt.jPlayer({ + wmode: "window", + loop: true, + swfPath: "lib/Jplayer.swf", + volume: 0.6 + }); + this.soundPlayerElt.jPlayer({ + wmode: "window", + loop: false, + supplied: 'wav', + swfPath: "lib/Jplayer.swf" + }); + + $(window).focus(function () { + $(sound.bgPlayerElt).jPlayer('play'); + }).blur(function () { + $(sound.bgPlayerElt).jPlayer('pause'); + }); + }; + + this.playTrackByName = function (name) { + this.trackForLevel = name; + + var track = this.tracks[name]; + if (track.url) { + var nowPlayingMsg = 'Now playing: "' + track.title + '" - ' + track.artist + ''; + } else { + var nowPlayingMsg = 'Now playing: "' + track.title + '" - ' + track.artist; + } + $('#nowPlayingMsg').html(nowPlayingMsg); + + if (!this.muted && this.currentlyPlayingTrack !== name) { + var path = this.source + track.path; + $(this.bgPlayerElt).jPlayer('stop'); + $(this.bgPlayerElt).jPlayer("setMedia", { + 'mp3': path + }); + $(this.bgPlayerElt).jPlayer('play'); + + this.currentlyPlayingTrack = name; + } + }; + + this.playTrackByNum = function (num) { + this.playTrackByName(this.defaultTracks[(num - 1) % this.defaultTracks.length]); + }; + + this.playSound = function (name) { + $(this.soundPlayerElt).jPlayer('stop'); + $(this.soundPlayerElt).jPlayer("setMedia", { + 'wav': 'sound/' + name + '.wav' + }); + $(this.soundPlayerElt).jPlayer('play'); + }; + + this.toggleSound = function() { + if (this.muted) { + this.bgPlayerElt.jPlayer('unmute'); + this.soundPlayerElt.jPlayer('unmute'); + $("#muteButton img").attr('src', 'images/mute-off.png'); + this.muted = false; + this.playTrackByName(this.trackForLevel); + } else { + this.bgPlayerElt.jPlayer('mute'); + this.soundPlayerElt.jPlayer('mute'); + $("#muteButton img").attr('src', 'images/mute-on.png'); + this.muted = true; + } + }; + + // constructor + this.init(); +} diff --git a/scripts/ui.js b/scripts/ui.js new file mode 100644 index 0000000000000000000000000000000000000000..ca43c8af48ac25d5c5f770f77c969267e9a5fc5c --- /dev/null +++ b/scripts/ui.js @@ -0,0 +1,283 @@ +var toggleFocus = (function () { + var focus_state = undefined; + return function do_toggle(game) { + if (!focus_state || focus_state === 'display') { + focus_state = 'editor'; + game.editor.focus(); + } else if (focus_state === 'editor') { + focus_state = 'display'; + game.display.focus(); + } + }; +})(); + +Game.prototype.enableShortcutKeys = function () { + var game = this; + + shortcut.add('ctrl+1', function () { + $("#helpButton").click(); + return true; + }); + + shortcut.add('ctrl+2', function () { + $("#toggleFocusButton").click(); + return true; + }); + + shortcut.add('ctrl+3', function () { + $("#notepadButton").click(); + return true; + }); + + shortcut.add('ctrl+4', function () { + $("#resetButton").click(); + return true; + }); + + shortcut.add('ctrl+5', function () { + $("#executeButton").click(); + return true; + }); + + shortcut.add('ctrl+6', function () { + $("#phoneButton").click(); + return true; + }); + + shortcut.add('ctrl+0', function () { + $("#menuButton").click(); + return true; + }); +}; + +Game.prototype.enableButtons = function () { + var game = this; + + $("#helpButton").click( function () { + game.sound.playSound('select'); + game.openHelp(); + }); + + $("#toggleFocusButton").click( function () { + game.sound.playSound('select'); + toggleFocus(game); + }); + + $('#notepadButton').click( function () { + game.sound.playSound('select'); + $('#helpPane, #menuPane').hide(); + $('#notepadPane').toggle(); + game.notepadEditor.refresh(); + return true; + }); + + $("#resetButton").click( function () { + game.sound.playSound('blip'); + game._resetLevel( game._currentLevel ); + }); + + $("#executeButton").click( function () { + game.sound.playSound('blip'); + game._evalLevelCode(); + }); + + $("#phoneButton").click( function () { + game.sound.playSound('select'); + game.usePhone(); + }); + + $("#menuButton").click( function () { + game.sound.playSound('select'); + game.openMenu(); + }); + + $("#helpPaneCloseButton").click ( function () { + game.sound.playSound('select'); + $('#helpPane').hide(); + }); + + $("#muteButton").click( function () { + game.sound.toggleSound(); + }); +}; + +Game.prototype.setUpNotepad = function () { + var game = this; + + var textarea = document.getElementById('notepadTextarea'); + this.notepadEditor = CodeMirror.fromTextArea(textarea, { + theme: 'vibrant-ink', + lineNumbers: true, + mode: 'javascript' + }); + + this.notepadEditor.setSize(null, 275); + + var ls_tag = 'notepadContent'; + var content = localStorage.getItem(this._getLocalKey(ls_tag)); + if (content === null) { + content = ''; + } + this.notepadEditor.setValue(content); + + $('#notepadPaneCloseButton').click(function () { + $('#notepadPane').hide(); + }); + + $('#notepadSaveButton').click(function () { + var v = game.notepadEditor.getValue(); + localStorage.setItem(this._getLocalKey(ls_tag), v); + }); +}; + +Game.prototype.openMenu = function () { + var game = this; + + $('#menuPane #levels').html(''); + $.each(game._levelFileNames, function (levelNum, fileName) { + levelNum += 1; + var levelName = fileName.split('.')[0]; + levelName = levelName.split('_').join(' '); + + var levelButton = $('